blob: 7babb34633794e4303f2c3470adf52d1fcb607a4 [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);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800573 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800574
575 if (data != null) {
576 InstallArgs args = data.args;
577 PackageInstalledInfo res = data.res;
578
579 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
580 res.removedInfo.sendBroadcast(false, true);
581 Bundle extras = new Bundle(1);
582 extras.putInt(Intent.EXTRA_UID, res.uid);
583 final boolean update = res.removedInfo.removedPackage != null;
584 if (update) {
585 extras.putBoolean(Intent.EXTRA_REPLACING, true);
586 }
587 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
588 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700589 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 if (update) {
591 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
592 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700593 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 }
595 if (res.removedInfo.args != null) {
596 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800597 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 }
599 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800600 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800601 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800602 // We delete after a gc for applications on sdcard.
603 if (deleteOld) {
604 synchronized (mInstallLock) {
605 res.removedInfo.args.doPostDeleteLI(true);
606 }
607 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800608 if (args.observer != null) {
609 try {
610 args.observer.packageInstalled(res.name, res.returnCode);
611 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800612 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800613 }
614 }
615 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800616 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800617 }
618 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700619 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700620 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
621 boolean reportStatus = msg.arg1 == 1;
622 boolean doGc = msg.arg2 == 1;
623 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
624 if (doGc) {
625 // Force a gc to clear up stale containers.
626 Runtime.getRuntime().gc();
627 }
628 if (msg.obj != null) {
629 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
630 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
631 // Unload containers
632 unloadAllContainers(args);
633 }
634 if (reportStatus) {
635 try {
636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
637 PackageHelper.getMountService().finishMediaUpdate();
638 } catch (RemoteException e) {
639 Log.e(TAG, "MountService not running?");
640 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700641 }
642 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700643 case WRITE_SETTINGS: {
644 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
645 synchronized (mPackages) {
646 removeMessages(WRITE_SETTINGS);
647 mSettings.writeLP();
648 }
649 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
650 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700651 }
652 }
653 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800654
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700655 void scheduleWriteSettingsLocked() {
656 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
657 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
658 }
659 }
660
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800661 static boolean installOnSd(int flags) {
662 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700663 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800664 return false;
665 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700666 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
667 return true;
668 }
669 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800670 }
671
672 static boolean isFwdLocked(int flags) {
673 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
674 return true;
675 }
676 return false;
677 }
678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 public static final IPackageManager main(Context context, boolean factoryTest) {
680 PackageManagerService m = new PackageManagerService(context, factoryTest);
681 ServiceManager.addService("package", m);
682 return m;
683 }
684
685 static String[] splitString(String str, char sep) {
686 int count = 1;
687 int i = 0;
688 while ((i=str.indexOf(sep, i)) >= 0) {
689 count++;
690 i++;
691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 String[] res = new String[count];
694 i=0;
695 count = 0;
696 int lastI=0;
697 while ((i=str.indexOf(sep, i)) >= 0) {
698 res[count] = str.substring(lastI, i);
699 count++;
700 i++;
701 lastI = i;
702 }
703 res[count] = str.substring(lastI, str.length());
704 return res;
705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800708 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800712 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 mContext = context;
716 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700717 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 mMetrics = new DisplayMetrics();
719 mSettings = new Settings();
720 mSettings.addSharedUserLP("android.uid.system",
721 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
722 mSettings.addSharedUserLP("android.uid.phone",
723 MULTIPLE_APPLICATION_UIDS
724 ? RADIO_UID : FIRST_APPLICATION_UID,
725 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400726 mSettings.addSharedUserLP("android.uid.log",
727 MULTIPLE_APPLICATION_UIDS
728 ? LOG_UID : FIRST_APPLICATION_UID,
729 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730
731 String separateProcesses = SystemProperties.get("debug.separate_processes");
732 if (separateProcesses != null && separateProcesses.length() > 0) {
733 if ("*".equals(separateProcesses)) {
734 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
735 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800736 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 } else {
738 mDefParseFlags = 0;
739 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800740 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 + separateProcesses);
742 }
743 } else {
744 mDefParseFlags = 0;
745 mSeparateProcesses = null;
746 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 Installer installer = new Installer();
749 // Little hacky thing to check if installd is here, to determine
750 // whether we are running on the simulator and thus need to take
751 // care of building the /data file structure ourself.
752 // (apparently the sim now has a working installer)
753 if (installer.ping() && Process.supportsProcesses()) {
754 mInstaller = installer;
755 } else {
756 mInstaller = null;
757 }
758
759 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
760 Display d = wm.getDefaultDisplay();
761 d.getMetrics(mMetrics);
762
763 synchronized (mInstallLock) {
764 synchronized (mPackages) {
765 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700766 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 File dataDir = Environment.getDataDirectory();
769 mAppDataDir = new File(dataDir, "data");
770 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
771
772 if (mInstaller == null) {
773 // Make sure these dirs exist, when we are running in
774 // the simulator.
775 // Make a wide-open directory for random misc stuff.
776 File miscDir = new File(dataDir, "misc");
777 miscDir.mkdirs();
778 mAppDataDir.mkdirs();
779 mDrmAppPrivateInstallDir.mkdirs();
780 }
781
782 readPermissions();
783
784 mRestoredSettings = mSettings.readLP();
785 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800786
787 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800789
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800790 // Set flag to monitor and not change apk file paths when
791 // scanning install directories.
792 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700793 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800794 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800795 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700801 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700804 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 /**
807 * Out of paranoia, ensure that everything in the boot class
808 * path has been dexed.
809 */
810 String bootClassPath = System.getProperty("java.boot.class.path");
811 if (bootClassPath != null) {
812 String[] paths = splitString(bootClassPath, ':');
813 for (int i=0; i<paths.length; i++) {
814 try {
815 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
816 libFiles.add(paths[i]);
817 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700818 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 }
820 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800821 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800822 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800823 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 }
825 }
826 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800827 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 /**
831 * Also ensure all external libraries have had dexopt run on them.
832 */
833 if (mSharedLibraries.size() > 0) {
834 Iterator<String> libs = mSharedLibraries.values().iterator();
835 while (libs.hasNext()) {
836 String lib = libs.next();
837 try {
838 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
839 libFiles.add(lib);
840 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700841 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800844 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800846 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
848 }
849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 // Gross hack for now: we know this file doesn't contain any
852 // code, so don't dexopt it to avoid the resulting log spew.
853 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 /**
856 * And there are a number of commands implemented in Java, which
857 * we currently need to do the dexopt on so that they can be
858 * run from a non-root shell.
859 */
860 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700861 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 for (int i=0; i<frameworkFiles.length; i++) {
863 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
864 String path = libPath.getPath();
865 // Skip the file if we alrady did it.
866 if (libFiles.contains(path)) {
867 continue;
868 }
869 // Skip the file if it is not a type we want to dexopt.
870 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
871 continue;
872 }
873 try {
874 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
875 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700876 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 }
878 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800879 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800881 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 }
883 }
884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800885
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700886 if (didDexOpt) {
887 // If we had to do a dexopt of one of the previous
888 // things, then something on the system has changed.
889 // Consider this significant, and wipe away all other
890 // existing dexopt files to ensure we don't leave any
891 // dangling around.
892 String[] files = mDalvikCacheDir.list();
893 if (files != null) {
894 for (int i=0; i<files.length; i++) {
895 String fn = files[i];
896 if (fn.startsWith("data@app@")
897 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800898 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700899 (new File(mDalvikCacheDir, fn)).delete();
900 }
901 }
902 }
903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800906 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 mFrameworkInstallObserver = new AppDirObserver(
908 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
909 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700910 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
911 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800912 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800913
914 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
916 mSystemInstallObserver = new AppDirObserver(
917 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
918 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700919 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
920 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921
922 if (mInstaller != null) {
923 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
924 mInstaller.moveFiles();
925 }
926
927 // Prune any system packages that no longer exist.
928 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
929 while (psit.hasNext()) {
930 PackageSetting ps = psit.next();
931 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800932 && !mPackages.containsKey(ps.name)
933 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800934 psit.remove();
935 String msg = "System package " + ps.name
936 + " no longer exists; wiping its data";
937 reportSettingsProblem(Log.WARN, msg);
938 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700939 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800940 }
941 }
942 }
943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 mAppInstallDir = new File(dataDir, "app");
945 if (mInstaller == null) {
946 // Make sure these dirs exist, when we are running in
947 // the simulator.
948 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
949 }
950 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800951 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 //clean up list
953 for(int i = 0; i < deletePkgsList.size(); i++) {
954 //clean up here
955 cleanupInstallFailedPackage(deletePkgsList.get(i));
956 }
957 //delete tmp files
958 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800959
960 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 SystemClock.uptimeMillis());
962 mAppInstallObserver = new AppDirObserver(
963 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
964 mAppInstallObserver.startWatching();
965 scanDirLI(mAppInstallDir, 0, scanMode);
966
967 mDrmAppInstallObserver = new AppDirObserver(
968 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
969 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800970 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800972 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800974 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 + ((SystemClock.uptimeMillis()-startTime)/1000f)
976 + " seconds");
977
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700978 // If the platform SDK has changed since the last time we booted,
979 // we need to re-grant app permission to catch any new ones that
980 // appear. This is really a hack, and means that apps can in some
981 // cases get permissions that the user didn't initially explicitly
982 // allow... it would be nice to have some better way to handle
983 // this situation.
984 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
985 != mSdkVersion;
986 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
987 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
988 + "; regranting permissions for internal storage");
989 mSettings.mInternalSdkPlatform = mSdkVersion;
990
991 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992
993 mSettings.writeLP();
994
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 // Now after opening every single application zip, make sure they
999 // are all flushed. Not really needed, but keeps things nice and
1000 // tidy.
1001 Runtime.getRuntime().gc();
1002 } // synchronized (mPackages)
1003 } // synchronized (mInstallLock)
1004 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 @Override
1007 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1008 throws RemoteException {
1009 try {
1010 return super.onTransact(code, data, reply, flags);
1011 } catch (RuntimeException e) {
1012 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001013 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 }
1015 throw e;
1016 }
1017 }
1018
Dianne Hackborne6620b22010-01-22 14:46:21 -08001019 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001020 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07001022 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001024 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001025 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 }
1027 } else {
1028 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001029 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 File dataDir = new File(pkg.applicationInfo.dataDir);
1031 dataDir.delete();
1032 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001033 if (ps.codePath != null) {
1034 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001036 }
1037 }
1038 if (ps.resourcePath != null) {
1039 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001040 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001041 }
1042 }
1043 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
1045
1046 void readPermissions() {
1047 // Read permissions from .../etc/permission directory.
1048 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1049 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001050 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 return;
1052 }
1053 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001054 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 return;
1056 }
1057
1058 // Iterate over the files in the directory and scan .xml files
1059 for (File f : libraryDir.listFiles()) {
1060 // We'll read platform.xml last
1061 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1062 continue;
1063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001066 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 continue;
1068 }
1069 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001070 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 continue;
1072 }
1073
1074 readPermissionsFromXml(f);
1075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1078 final File permFile = new File(Environment.getRootDirectory(),
1079 "etc/permissions/platform.xml");
1080 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001081
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001082 StringBuilder sb = new StringBuilder(128);
1083 sb.append("Libs:");
1084 Iterator<String> it = mSharedLibraries.keySet().iterator();
1085 while (it.hasNext()) {
1086 sb.append(' ');
1087 String name = it.next();
1088 sb.append(name);
1089 sb.append(':');
1090 sb.append(mSharedLibraries.get(name));
1091 }
1092 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001093
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001094 sb.setLength(0);
1095 sb.append("Features:");
1096 it = mAvailableFeatures.keySet().iterator();
1097 while (it.hasNext()) {
1098 sb.append(' ');
1099 sb.append(it.next());
1100 }
1101 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001103
1104 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 FileReader permReader = null;
1106 try {
1107 permReader = new FileReader(permFile);
1108 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001109 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 return;
1111 }
1112
1113 try {
1114 XmlPullParser parser = Xml.newPullParser();
1115 parser.setInput(permReader);
1116
1117 XmlUtils.beginDocument(parser, "permissions");
1118
1119 while (true) {
1120 XmlUtils.nextElement(parser);
1121 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1122 break;
1123 }
1124
1125 String name = parser.getName();
1126 if ("group".equals(name)) {
1127 String gidStr = parser.getAttributeValue(null, "gid");
1128 if (gidStr != null) {
1129 int gid = Integer.parseInt(gidStr);
1130 mGlobalGids = appendInt(mGlobalGids, gid);
1131 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001132 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 + parser.getPositionDescription());
1134 }
1135
1136 XmlUtils.skipCurrentTag(parser);
1137 continue;
1138 } else if ("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, "<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 perm = perm.intern();
1147 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 } else if ("assign-permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 String uidStr = parser.getAttributeValue(null, "uid");
1158 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001159 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 + parser.getPositionDescription());
1161 XmlUtils.skipCurrentTag(parser);
1162 continue;
1163 }
1164 int uid = Process.getUidForName(uidStr);
1165 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001166 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 + uidStr + "\" at "
1168 + parser.getPositionDescription());
1169 XmlUtils.skipCurrentTag(parser);
1170 continue;
1171 }
1172 perm = perm.intern();
1173 HashSet<String> perms = mSystemPermissions.get(uid);
1174 if (perms == null) {
1175 perms = new HashSet<String>();
1176 mSystemPermissions.put(uid, perms);
1177 }
1178 perms.add(perm);
1179 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 } else if ("library".equals(name)) {
1182 String lname = parser.getAttributeValue(null, "name");
1183 String lfile = parser.getAttributeValue(null, "file");
1184 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001185 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 + parser.getPositionDescription());
1187 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001188 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 + parser.getPositionDescription());
1190 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001191 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001192 mSharedLibraries.put(lname, lfile);
1193 }
1194 XmlUtils.skipCurrentTag(parser);
1195 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001196
Dianne Hackborn49237342009-08-27 20:08:01 -07001197 } else if ("feature".equals(name)) {
1198 String fname = parser.getAttributeValue(null, "name");
1199 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001200 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001201 + parser.getPositionDescription());
1202 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001203 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001204 FeatureInfo fi = new FeatureInfo();
1205 fi.name = fname;
1206 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 }
1208 XmlUtils.skipCurrentTag(parser);
1209 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 } else {
1212 XmlUtils.skipCurrentTag(parser);
1213 continue;
1214 }
1215
1216 }
1217 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001218 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001220 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
1222 }
1223
1224 void readPermission(XmlPullParser parser, String name)
1225 throws IOException, XmlPullParserException {
1226
1227 name = name.intern();
1228
1229 BasePermission bp = mSettings.mPermissions.get(name);
1230 if (bp == null) {
1231 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1232 mSettings.mPermissions.put(name, bp);
1233 }
1234 int outerDepth = parser.getDepth();
1235 int type;
1236 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1237 && (type != XmlPullParser.END_TAG
1238 || parser.getDepth() > outerDepth)) {
1239 if (type == XmlPullParser.END_TAG
1240 || type == XmlPullParser.TEXT) {
1241 continue;
1242 }
1243
1244 String tagName = parser.getName();
1245 if ("group".equals(tagName)) {
1246 String gidStr = parser.getAttributeValue(null, "gid");
1247 if (gidStr != null) {
1248 int gid = Process.getGidForName(gidStr);
1249 bp.gids = appendInt(bp.gids, gid);
1250 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001251 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 + parser.getPositionDescription());
1253 }
1254 }
1255 XmlUtils.skipCurrentTag(parser);
1256 }
1257 }
1258
1259 static int[] appendInt(int[] cur, int val) {
1260 if (cur == null) {
1261 return new int[] { val };
1262 }
1263 final int N = cur.length;
1264 for (int i=0; i<N; i++) {
1265 if (cur[i] == val) {
1266 return cur;
1267 }
1268 }
1269 int[] ret = new int[N+1];
1270 System.arraycopy(cur, 0, ret, 0, N);
1271 ret[N] = val;
1272 return ret;
1273 }
1274
1275 static int[] appendInts(int[] cur, int[] add) {
1276 if (add == null) return cur;
1277 if (cur == null) return add;
1278 final int N = add.length;
1279 for (int i=0; i<N; i++) {
1280 cur = appendInt(cur, add[i]);
1281 }
1282 return cur;
1283 }
1284
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001285 static int[] removeInt(int[] cur, int val) {
1286 if (cur == null) {
1287 return null;
1288 }
1289 final int N = cur.length;
1290 for (int i=0; i<N; i++) {
1291 if (cur[i] == val) {
1292 int[] ret = new int[N-1];
1293 if (i > 0) {
1294 System.arraycopy(cur, 0, ret, 0, i);
1295 }
1296 if (i < (N-1)) {
1297 System.arraycopy(cur, i, ret, i+1, N-i-1);
1298 }
1299 return ret;
1300 }
1301 }
1302 return cur;
1303 }
1304
1305 static int[] removeInts(int[] cur, int[] rem) {
1306 if (rem == null) return cur;
1307 if (cur == null) return cur;
1308 final int N = rem.length;
1309 for (int i=0; i<N; i++) {
1310 cur = removeInt(cur, rem[i]);
1311 }
1312 return cur;
1313 }
1314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001316 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1317 // The package has been uninstalled but has retained data and resources.
1318 return PackageParser.generatePackageInfo(p, null, flags);
1319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 final PackageSetting ps = (PackageSetting)p.mExtras;
1321 if (ps == null) {
1322 return null;
1323 }
1324 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1325 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1326 }
1327
1328 public PackageInfo getPackageInfo(String packageName, int flags) {
1329 synchronized (mPackages) {
1330 PackageParser.Package p = mPackages.get(packageName);
1331 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001332 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 + ": " + p);
1334 if (p != null) {
1335 return generatePackageInfo(p, flags);
1336 }
1337 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1338 return generatePackageInfoFromSettingsLP(packageName, flags);
1339 }
1340 }
1341 return null;
1342 }
1343
Dianne Hackborn47096932010-02-11 15:57:09 -08001344 public String[] currentToCanonicalPackageNames(String[] names) {
1345 String[] out = new String[names.length];
1346 synchronized (mPackages) {
1347 for (int i=names.length-1; i>=0; i--) {
1348 PackageSetting ps = mSettings.mPackages.get(names[i]);
1349 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1350 }
1351 }
1352 return out;
1353 }
1354
1355 public String[] canonicalToCurrentPackageNames(String[] names) {
1356 String[] out = new String[names.length];
1357 synchronized (mPackages) {
1358 for (int i=names.length-1; i>=0; i--) {
1359 String cur = mSettings.mRenamedPackages.get(names[i]);
1360 out[i] = cur != null ? cur : names[i];
1361 }
1362 }
1363 return out;
1364 }
1365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 public int getPackageUid(String packageName) {
1367 synchronized (mPackages) {
1368 PackageParser.Package p = mPackages.get(packageName);
1369 if(p != null) {
1370 return p.applicationInfo.uid;
1371 }
1372 PackageSetting ps = mSettings.mPackages.get(packageName);
1373 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1374 return -1;
1375 }
1376 p = ps.pkg;
1377 return p != null ? p.applicationInfo.uid : -1;
1378 }
1379 }
1380
1381 public int[] getPackageGids(String packageName) {
1382 synchronized (mPackages) {
1383 PackageParser.Package p = mPackages.get(packageName);
1384 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001385 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 + ": " + p);
1387 if (p != null) {
1388 final PackageSetting ps = (PackageSetting)p.mExtras;
1389 final SharedUserSetting suid = ps.sharedUser;
1390 return suid != null ? suid.gids : ps.gids;
1391 }
1392 }
1393 // stupid thing to indicate an error.
1394 return new int[0];
1395 }
1396
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001397 static final PermissionInfo generatePermissionInfo(
1398 BasePermission bp, int flags) {
1399 if (bp.perm != null) {
1400 return PackageParser.generatePermissionInfo(bp.perm, flags);
1401 }
1402 PermissionInfo pi = new PermissionInfo();
1403 pi.name = bp.name;
1404 pi.packageName = bp.sourcePackage;
1405 pi.nonLocalizedLabel = bp.name;
1406 pi.protectionLevel = bp.protectionLevel;
1407 return pi;
1408 }
1409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 public PermissionInfo getPermissionInfo(String name, int flags) {
1411 synchronized (mPackages) {
1412 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001413 if (p != null) {
1414 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
1416 return null;
1417 }
1418 }
1419
1420 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1421 synchronized (mPackages) {
1422 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1423 for (BasePermission p : mSettings.mPermissions.values()) {
1424 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001425 if (p.perm == null || p.perm.info.group == null) {
1426 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001429 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1431 }
1432 }
1433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 if (out.size() > 0) {
1436 return out;
1437 }
1438 return mPermissionGroups.containsKey(group) ? out : null;
1439 }
1440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1443 synchronized (mPackages) {
1444 return PackageParser.generatePermissionGroupInfo(
1445 mPermissionGroups.get(name), flags);
1446 }
1447 }
1448
1449 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1450 synchronized (mPackages) {
1451 final int N = mPermissionGroups.size();
1452 ArrayList<PermissionGroupInfo> out
1453 = new ArrayList<PermissionGroupInfo>(N);
1454 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1455 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1456 }
1457 return out;
1458 }
1459 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1462 PackageSetting ps = mSettings.mPackages.get(packageName);
1463 if(ps != null) {
1464 if(ps.pkg == null) {
1465 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1466 if(pInfo != null) {
1467 return pInfo.applicationInfo;
1468 }
1469 return null;
1470 }
1471 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1472 }
1473 return null;
1474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1477 PackageSetting ps = mSettings.mPackages.get(packageName);
1478 if(ps != null) {
1479 if(ps.pkg == null) {
1480 ps.pkg = new PackageParser.Package(packageName);
1481 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001482 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1483 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1484 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1485 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487 return generatePackageInfo(ps.pkg, flags);
1488 }
1489 return null;
1490 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1493 synchronized (mPackages) {
1494 PackageParser.Package p = mPackages.get(packageName);
1495 if (Config.LOGV) Log.v(
1496 TAG, "getApplicationInfo " + packageName
1497 + ": " + p);
1498 if (p != null) {
1499 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001500 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 if ("android".equals(packageName)||"system".equals(packageName)) {
1503 return mAndroidApplication;
1504 }
1505 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1506 return generateApplicationInfoFromSettingsLP(packageName, flags);
1507 }
1508 }
1509 return null;
1510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001511
1512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1514 mContext.enforceCallingOrSelfPermission(
1515 android.Manifest.permission.CLEAR_APP_CACHE, null);
1516 // Queue up an async operation since clearing cache may take a little while.
1517 mHandler.post(new Runnable() {
1518 public void run() {
1519 mHandler.removeCallbacks(this);
1520 int retCode = -1;
1521 if (mInstaller != null) {
1522 retCode = mInstaller.freeCache(freeStorageSize);
1523 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001524 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
1526 } //end if mInstaller
1527 if (observer != null) {
1528 try {
1529 observer.onRemoveCompleted(null, (retCode >= 0));
1530 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001531 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
1533 }
1534 }
1535 });
1536 }
1537
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001538 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001539 mContext.enforceCallingOrSelfPermission(
1540 android.Manifest.permission.CLEAR_APP_CACHE, null);
1541 // Queue up an async operation since clearing cache may take a little while.
1542 mHandler.post(new Runnable() {
1543 public void run() {
1544 mHandler.removeCallbacks(this);
1545 int retCode = -1;
1546 if (mInstaller != null) {
1547 retCode = mInstaller.freeCache(freeStorageSize);
1548 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001549 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001550 }
1551 }
1552 if(pi != null) {
1553 try {
1554 // Callback via pending intent
1555 int code = (retCode >= 0) ? 1 : 0;
1556 pi.sendIntent(null, code, null,
1557 null, null);
1558 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001559 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001560 }
1561 }
1562 }
1563 });
1564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1567 synchronized (mPackages) {
1568 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001569
1570 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001572 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
1574 if (mResolveComponentName.equals(component)) {
1575 return mResolveActivity;
1576 }
1577 }
1578 return null;
1579 }
1580
1581 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1582 synchronized (mPackages) {
1583 PackageParser.Activity a = mReceivers.mActivities.get(component);
1584 if (Config.LOGV) Log.v(
1585 TAG, "getReceiverInfo " + component + ": " + a);
1586 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1587 return PackageParser.generateActivityInfo(a, flags);
1588 }
1589 }
1590 return null;
1591 }
1592
1593 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1594 synchronized (mPackages) {
1595 PackageParser.Service s = mServices.mServices.get(component);
1596 if (Config.LOGV) Log.v(
1597 TAG, "getServiceInfo " + component + ": " + s);
1598 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1599 return PackageParser.generateServiceInfo(s, flags);
1600 }
1601 }
1602 return null;
1603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 public String[] getSystemSharedLibraryNames() {
1606 Set<String> libSet;
1607 synchronized (mPackages) {
1608 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001609 int size = libSet.size();
1610 if (size > 0) {
1611 String[] libs = new String[size];
1612 libSet.toArray(libs);
1613 return libs;
1614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001616 return null;
1617 }
1618
1619 public FeatureInfo[] getSystemAvailableFeatures() {
1620 Collection<FeatureInfo> featSet;
1621 synchronized (mPackages) {
1622 featSet = mAvailableFeatures.values();
1623 int size = featSet.size();
1624 if (size > 0) {
1625 FeatureInfo[] features = new FeatureInfo[size+1];
1626 featSet.toArray(features);
1627 FeatureInfo fi = new FeatureInfo();
1628 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1629 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1630 features[size] = fi;
1631 return features;
1632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 return null;
1635 }
1636
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001637 public boolean hasSystemFeature(String name) {
1638 synchronized (mPackages) {
1639 return mAvailableFeatures.containsKey(name);
1640 }
1641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 public int checkPermission(String permName, String pkgName) {
1644 synchronized (mPackages) {
1645 PackageParser.Package p = mPackages.get(pkgName);
1646 if (p != null && p.mExtras != null) {
1647 PackageSetting ps = (PackageSetting)p.mExtras;
1648 if (ps.sharedUser != null) {
1649 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1650 return PackageManager.PERMISSION_GRANTED;
1651 }
1652 } else if (ps.grantedPermissions.contains(permName)) {
1653 return PackageManager.PERMISSION_GRANTED;
1654 }
1655 }
1656 }
1657 return PackageManager.PERMISSION_DENIED;
1658 }
1659
1660 public int checkUidPermission(String permName, int uid) {
1661 synchronized (mPackages) {
1662 Object obj = mSettings.getUserIdLP(uid);
1663 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001664 GrantedPermissions gp = (GrantedPermissions)obj;
1665 if (gp.grantedPermissions.contains(permName)) {
1666 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668 } else {
1669 HashSet<String> perms = mSystemPermissions.get(uid);
1670 if (perms != null && perms.contains(permName)) {
1671 return PackageManager.PERMISSION_GRANTED;
1672 }
1673 }
1674 }
1675 return PackageManager.PERMISSION_DENIED;
1676 }
1677
1678 private BasePermission findPermissionTreeLP(String permName) {
1679 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1680 if (permName.startsWith(bp.name) &&
1681 permName.length() > bp.name.length() &&
1682 permName.charAt(bp.name.length()) == '.') {
1683 return bp;
1684 }
1685 }
1686 return null;
1687 }
1688
1689 private BasePermission checkPermissionTreeLP(String permName) {
1690 if (permName != null) {
1691 BasePermission bp = findPermissionTreeLP(permName);
1692 if (bp != null) {
1693 if (bp.uid == Binder.getCallingUid()) {
1694 return bp;
1695 }
1696 throw new SecurityException("Calling uid "
1697 + Binder.getCallingUid()
1698 + " is not allowed to add to permission tree "
1699 + bp.name + " owned by uid " + bp.uid);
1700 }
1701 }
1702 throw new SecurityException("No permission tree found for " + permName);
1703 }
1704
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001705 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1706 if (s1 == null) {
1707 return s2 == null;
1708 }
1709 if (s2 == null) {
1710 return false;
1711 }
1712 if (s1.getClass() != s2.getClass()) {
1713 return false;
1714 }
1715 return s1.equals(s2);
1716 }
1717
1718 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1719 if (pi1.icon != pi2.icon) return false;
1720 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1721 if (!compareStrings(pi1.name, pi2.name)) return false;
1722 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1723 // We'll take care of setting this one.
1724 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1725 // These are not currently stored in settings.
1726 //if (!compareStrings(pi1.group, pi2.group)) return false;
1727 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1728 //if (pi1.labelRes != pi2.labelRes) return false;
1729 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1730 return true;
1731 }
1732
1733 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1734 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1735 throw new SecurityException("Label must be specified in permission");
1736 }
1737 BasePermission tree = checkPermissionTreeLP(info.name);
1738 BasePermission bp = mSettings.mPermissions.get(info.name);
1739 boolean added = bp == null;
1740 boolean changed = true;
1741 if (added) {
1742 bp = new BasePermission(info.name, tree.sourcePackage,
1743 BasePermission.TYPE_DYNAMIC);
1744 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1745 throw new SecurityException(
1746 "Not allowed to modify non-dynamic permission "
1747 + info.name);
1748 } else {
1749 if (bp.protectionLevel == info.protectionLevel
1750 && bp.perm.owner.equals(tree.perm.owner)
1751 && bp.uid == tree.uid
1752 && comparePermissionInfos(bp.perm.info, info)) {
1753 changed = false;
1754 }
1755 }
1756 bp.protectionLevel = info.protectionLevel;
1757 bp.perm = new PackageParser.Permission(tree.perm.owner,
1758 new PermissionInfo(info));
1759 bp.perm.info.packageName = tree.perm.info.packageName;
1760 bp.uid = tree.uid;
1761 if (added) {
1762 mSettings.mPermissions.put(info.name, bp);
1763 }
1764 if (changed) {
1765 if (!async) {
1766 mSettings.writeLP();
1767 } else {
1768 scheduleWriteSettingsLocked();
1769 }
1770 }
1771 return added;
1772 }
1773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 public boolean addPermission(PermissionInfo info) {
1775 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001776 return addPermissionLocked(info, false);
1777 }
1778 }
1779
1780 public boolean addPermissionAsync(PermissionInfo info) {
1781 synchronized (mPackages) {
1782 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784 }
1785
1786 public void removePermission(String name) {
1787 synchronized (mPackages) {
1788 checkPermissionTreeLP(name);
1789 BasePermission bp = mSettings.mPermissions.get(name);
1790 if (bp != null) {
1791 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1792 throw new SecurityException(
1793 "Not allowed to modify non-dynamic permission "
1794 + name);
1795 }
1796 mSettings.mPermissions.remove(name);
1797 mSettings.writeLP();
1798 }
1799 }
1800 }
1801
Dianne Hackborn854060af2009-07-09 18:14:31 -07001802 public boolean isProtectedBroadcast(String actionName) {
1803 synchronized (mPackages) {
1804 return mProtectedBroadcasts.contains(actionName);
1805 }
1806 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 public int checkSignatures(String pkg1, String pkg2) {
1809 synchronized (mPackages) {
1810 PackageParser.Package p1 = mPackages.get(pkg1);
1811 PackageParser.Package p2 = mPackages.get(pkg2);
1812 if (p1 == null || p1.mExtras == null
1813 || p2 == null || p2.mExtras == null) {
1814 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1815 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001816 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
1818 }
1819
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001820 public int checkUidSignatures(int uid1, int uid2) {
1821 synchronized (mPackages) {
1822 Signature[] s1;
1823 Signature[] s2;
1824 Object obj = mSettings.getUserIdLP(uid1);
1825 if (obj != null) {
1826 if (obj instanceof SharedUserSetting) {
1827 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1828 } else if (obj instanceof PackageSetting) {
1829 s1 = ((PackageSetting)obj).signatures.mSignatures;
1830 } else {
1831 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1832 }
1833 } else {
1834 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1835 }
1836 obj = mSettings.getUserIdLP(uid2);
1837 if (obj != null) {
1838 if (obj instanceof SharedUserSetting) {
1839 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1840 } else if (obj instanceof PackageSetting) {
1841 s2 = ((PackageSetting)obj).signatures.mSignatures;
1842 } else {
1843 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1844 }
1845 } else {
1846 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1847 }
1848 return checkSignaturesLP(s1, s2);
1849 }
1850 }
1851
1852 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1853 if (s1 == null) {
1854 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1856 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1857 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001858 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1860 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001861 HashSet<Signature> set1 = new HashSet<Signature>();
1862 for (Signature sig : s1) {
1863 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001865 HashSet<Signature> set2 = new HashSet<Signature>();
1866 for (Signature sig : s2) {
1867 set2.add(sig);
1868 }
1869 // Make sure s2 contains all signatures in s1.
1870 if (set1.equals(set2)) {
1871 return PackageManager.SIGNATURE_MATCH;
1872 }
1873 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 }
1875
1876 public String[] getPackagesForUid(int uid) {
1877 synchronized (mPackages) {
1878 Object obj = mSettings.getUserIdLP(uid);
1879 if (obj instanceof SharedUserSetting) {
1880 SharedUserSetting sus = (SharedUserSetting)obj;
1881 final int N = sus.packages.size();
1882 String[] res = new String[N];
1883 Iterator<PackageSetting> it = sus.packages.iterator();
1884 int i=0;
1885 while (it.hasNext()) {
1886 res[i++] = it.next().name;
1887 }
1888 return res;
1889 } else if (obj instanceof PackageSetting) {
1890 PackageSetting ps = (PackageSetting)obj;
1891 return new String[] { ps.name };
1892 }
1893 }
1894 return null;
1895 }
1896
1897 public String getNameForUid(int uid) {
1898 synchronized (mPackages) {
1899 Object obj = mSettings.getUserIdLP(uid);
1900 if (obj instanceof SharedUserSetting) {
1901 SharedUserSetting sus = (SharedUserSetting)obj;
1902 return sus.name + ":" + sus.userId;
1903 } else if (obj instanceof PackageSetting) {
1904 PackageSetting ps = (PackageSetting)obj;
1905 return ps.name;
1906 }
1907 }
1908 return null;
1909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 public int getUidForSharedUser(String sharedUserName) {
1912 if(sharedUserName == null) {
1913 return -1;
1914 }
1915 synchronized (mPackages) {
1916 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1917 if(suid == null) {
1918 return -1;
1919 }
1920 return suid.userId;
1921 }
1922 }
1923
1924 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1925 int flags) {
1926 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001927 return chooseBestActivity(intent, resolvedType, flags, query);
1928 }
1929
Mihai Predaeae850c2009-05-13 10:13:48 +02001930 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1931 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 if (query != null) {
1933 final int N = query.size();
1934 if (N == 1) {
1935 return query.get(0);
1936 } else if (N > 1) {
1937 // If there is more than one activity with the same priority,
1938 // then let the user decide between them.
1939 ResolveInfo r0 = query.get(0);
1940 ResolveInfo r1 = query.get(1);
1941 if (false) {
1942 System.out.println(r0.activityInfo.name +
1943 "=" + r0.priority + " vs " +
1944 r1.activityInfo.name +
1945 "=" + r1.priority);
1946 }
1947 // If the first activity has a higher priority, or a different
1948 // default, then it is always desireable to pick it.
1949 if (r0.priority != r1.priority
1950 || r0.preferredOrder != r1.preferredOrder
1951 || r0.isDefault != r1.isDefault) {
1952 return query.get(0);
1953 }
1954 // If we have saved a preference for a preferred activity for
1955 // this Intent, use that.
1956 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1957 flags, query, r0.priority);
1958 if (ri != null) {
1959 return ri;
1960 }
1961 return mResolveInfo;
1962 }
1963 }
1964 return null;
1965 }
1966
1967 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1968 int flags, List<ResolveInfo> query, int priority) {
1969 synchronized (mPackages) {
1970 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1971 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001972 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1974 if (prefs != null && prefs.size() > 0) {
1975 // First figure out how good the original match set is.
1976 // We will only allow preferred activities that came
1977 // from the same match quality.
1978 int match = 0;
1979 final int N = query.size();
1980 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1981 for (int j=0; j<N; j++) {
1982 ResolveInfo ri = query.get(j);
1983 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1984 + ": 0x" + Integer.toHexString(match));
1985 if (ri.match > match) match = ri.match;
1986 }
1987 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1988 + Integer.toHexString(match));
1989 match &= IntentFilter.MATCH_CATEGORY_MASK;
1990 final int M = prefs.size();
1991 for (int i=0; i<M; i++) {
1992 PreferredActivity pa = prefs.get(i);
1993 if (pa.mMatch != match) {
1994 continue;
1995 }
1996 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1997 if (DEBUG_PREFERRED) {
1998 Log.v(TAG, "Got preferred activity:");
1999 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2000 }
2001 if (ai != null) {
2002 for (int j=0; j<N; j++) {
2003 ResolveInfo ri = query.get(j);
2004 if (!ri.activityInfo.applicationInfo.packageName
2005 .equals(ai.applicationInfo.packageName)) {
2006 continue;
2007 }
2008 if (!ri.activityInfo.name.equals(ai.name)) {
2009 continue;
2010 }
2011
2012 // Okay we found a previously set preferred app.
2013 // If the result set is different from when this
2014 // was created, we need to clear it and re-ask the
2015 // user their preference.
2016 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002017 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 + intent + " type " + resolvedType);
2019 mSettings.mPreferredActivities.removeFilter(pa);
2020 return null;
2021 }
2022
2023 // Yay!
2024 return ri;
2025 }
2026 }
2027 }
2028 }
2029 }
2030 return null;
2031 }
2032
2033 public List<ResolveInfo> queryIntentActivities(Intent intent,
2034 String resolvedType, int flags) {
2035 ComponentName comp = intent.getComponent();
2036 if (comp != null) {
2037 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2038 ActivityInfo ai = getActivityInfo(comp, flags);
2039 if (ai != null) {
2040 ResolveInfo ri = new ResolveInfo();
2041 ri.activityInfo = ai;
2042 list.add(ri);
2043 }
2044 return list;
2045 }
2046
2047 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002048 String pkgName = intent.getPackage();
2049 if (pkgName == null) {
2050 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2051 resolvedType, flags);
2052 }
2053 PackageParser.Package pkg = mPackages.get(pkgName);
2054 if (pkg != null) {
2055 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2056 resolvedType, flags, pkg.activities);
2057 }
2058 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
2060 }
2061
2062 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2063 Intent[] specifics, String[] specificTypes, Intent intent,
2064 String resolvedType, int flags) {
2065 final String resultsAction = intent.getAction();
2066
2067 List<ResolveInfo> results = queryIntentActivities(
2068 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2069 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2070
2071 int specificsPos = 0;
2072 int N;
2073
2074 // todo: note that the algorithm used here is O(N^2). This
2075 // isn't a problem in our current environment, but if we start running
2076 // into situations where we have more than 5 or 10 matches then this
2077 // should probably be changed to something smarter...
2078
2079 // First we go through and resolve each of the specific items
2080 // that were supplied, taking care of removing any corresponding
2081 // duplicate items in the generic resolve list.
2082 if (specifics != null) {
2083 for (int i=0; i<specifics.length; i++) {
2084 final Intent sintent = specifics[i];
2085 if (sintent == null) {
2086 continue;
2087 }
2088
2089 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2090 String action = sintent.getAction();
2091 if (resultsAction != null && resultsAction.equals(action)) {
2092 // If this action was explicitly requested, then don't
2093 // remove things that have it.
2094 action = null;
2095 }
2096 ComponentName comp = sintent.getComponent();
2097 ResolveInfo ri = null;
2098 ActivityInfo ai = null;
2099 if (comp == null) {
2100 ri = resolveIntent(
2101 sintent,
2102 specificTypes != null ? specificTypes[i] : null,
2103 flags);
2104 if (ri == null) {
2105 continue;
2106 }
2107 if (ri == mResolveInfo) {
2108 // ACK! Must do something better with this.
2109 }
2110 ai = ri.activityInfo;
2111 comp = new ComponentName(ai.applicationInfo.packageName,
2112 ai.name);
2113 } else {
2114 ai = getActivityInfo(comp, flags);
2115 if (ai == null) {
2116 continue;
2117 }
2118 }
2119
2120 // Look for any generic query activities that are duplicates
2121 // of this specific one, and remove them from the results.
2122 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2123 N = results.size();
2124 int j;
2125 for (j=specificsPos; j<N; j++) {
2126 ResolveInfo sri = results.get(j);
2127 if ((sri.activityInfo.name.equals(comp.getClassName())
2128 && sri.activityInfo.applicationInfo.packageName.equals(
2129 comp.getPackageName()))
2130 || (action != null && sri.filter.matchAction(action))) {
2131 results.remove(j);
2132 if (Config.LOGV) Log.v(
2133 TAG, "Removing duplicate item from " + j
2134 + " due to specific " + specificsPos);
2135 if (ri == null) {
2136 ri = sri;
2137 }
2138 j--;
2139 N--;
2140 }
2141 }
2142
2143 // Add this specific item to its proper place.
2144 if (ri == null) {
2145 ri = new ResolveInfo();
2146 ri.activityInfo = ai;
2147 }
2148 results.add(specificsPos, ri);
2149 ri.specificIndex = i;
2150 specificsPos++;
2151 }
2152 }
2153
2154 // Now we go through the remaining generic results and remove any
2155 // duplicate actions that are found here.
2156 N = results.size();
2157 for (int i=specificsPos; i<N-1; i++) {
2158 final ResolveInfo rii = results.get(i);
2159 if (rii.filter == null) {
2160 continue;
2161 }
2162
2163 // Iterate over all of the actions of this result's intent
2164 // filter... typically this should be just one.
2165 final Iterator<String> it = rii.filter.actionsIterator();
2166 if (it == null) {
2167 continue;
2168 }
2169 while (it.hasNext()) {
2170 final String action = it.next();
2171 if (resultsAction != null && resultsAction.equals(action)) {
2172 // If this action was explicitly requested, then don't
2173 // remove things that have it.
2174 continue;
2175 }
2176 for (int j=i+1; j<N; j++) {
2177 final ResolveInfo rij = results.get(j);
2178 if (rij.filter != null && rij.filter.hasAction(action)) {
2179 results.remove(j);
2180 if (Config.LOGV) Log.v(
2181 TAG, "Removing duplicate item from " + j
2182 + " due to action " + action + " at " + i);
2183 j--;
2184 N--;
2185 }
2186 }
2187 }
2188
2189 // If the caller didn't request filter information, drop it now
2190 // so we don't have to marshall/unmarshall it.
2191 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2192 rii.filter = null;
2193 }
2194 }
2195
2196 // Filter out the caller activity if so requested.
2197 if (caller != null) {
2198 N = results.size();
2199 for (int i=0; i<N; i++) {
2200 ActivityInfo ainfo = results.get(i).activityInfo;
2201 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2202 && caller.getClassName().equals(ainfo.name)) {
2203 results.remove(i);
2204 break;
2205 }
2206 }
2207 }
2208
2209 // If the caller didn't request filter information,
2210 // drop them now so we don't have to
2211 // marshall/unmarshall it.
2212 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2213 N = results.size();
2214 for (int i=0; i<N; i++) {
2215 results.get(i).filter = null;
2216 }
2217 }
2218
2219 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2220 return results;
2221 }
2222
2223 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2224 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002225 ComponentName comp = intent.getComponent();
2226 if (comp != null) {
2227 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2228 ActivityInfo ai = getReceiverInfo(comp, flags);
2229 if (ai != null) {
2230 ResolveInfo ri = new ResolveInfo();
2231 ri.activityInfo = ai;
2232 list.add(ri);
2233 }
2234 return list;
2235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002238 String pkgName = intent.getPackage();
2239 if (pkgName == null) {
2240 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2241 resolvedType, flags);
2242 }
2243 PackageParser.Package pkg = mPackages.get(pkgName);
2244 if (pkg != null) {
2245 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2246 resolvedType, flags, pkg.receivers);
2247 }
2248 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 }
2250 }
2251
2252 public ResolveInfo resolveService(Intent intent, String resolvedType,
2253 int flags) {
2254 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2255 flags);
2256 if (query != null) {
2257 if (query.size() >= 1) {
2258 // If there is more than one service with the same priority,
2259 // just arbitrarily pick the first one.
2260 return query.get(0);
2261 }
2262 }
2263 return null;
2264 }
2265
2266 public List<ResolveInfo> queryIntentServices(Intent intent,
2267 String resolvedType, int flags) {
2268 ComponentName comp = intent.getComponent();
2269 if (comp != null) {
2270 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2271 ServiceInfo si = getServiceInfo(comp, flags);
2272 if (si != null) {
2273 ResolveInfo ri = new ResolveInfo();
2274 ri.serviceInfo = si;
2275 list.add(ri);
2276 }
2277 return list;
2278 }
2279
2280 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002281 String pkgName = intent.getPackage();
2282 if (pkgName == null) {
2283 return (List<ResolveInfo>)mServices.queryIntent(intent,
2284 resolvedType, flags);
2285 }
2286 PackageParser.Package pkg = mPackages.get(pkgName);
2287 if (pkg != null) {
2288 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2289 resolvedType, flags, pkg.services);
2290 }
2291 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
2293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002295 public List<PackageInfo> getInstalledPackages(int flags) {
2296 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2297
2298 synchronized (mPackages) {
2299 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2300 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2301 while (i.hasNext()) {
2302 final PackageSetting ps = i.next();
2303 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2304 if(psPkg != null) {
2305 finalList.add(psPkg);
2306 }
2307 }
2308 }
2309 else {
2310 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2311 while (i.hasNext()) {
2312 final PackageParser.Package p = i.next();
2313 if (p.applicationInfo != null) {
2314 PackageInfo pi = generatePackageInfo(p, flags);
2315 if(pi != null) {
2316 finalList.add(pi);
2317 }
2318 }
2319 }
2320 }
2321 }
2322 return finalList;
2323 }
2324
2325 public List<ApplicationInfo> getInstalledApplications(int flags) {
2326 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2327 synchronized(mPackages) {
2328 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2329 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2330 while (i.hasNext()) {
2331 final PackageSetting ps = i.next();
2332 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2333 if(ai != null) {
2334 finalList.add(ai);
2335 }
2336 }
2337 }
2338 else {
2339 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2340 while (i.hasNext()) {
2341 final PackageParser.Package p = i.next();
2342 if (p.applicationInfo != null) {
2343 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2344 if(ai != null) {
2345 finalList.add(ai);
2346 }
2347 }
2348 }
2349 }
2350 }
2351 return finalList;
2352 }
2353
2354 public List<ApplicationInfo> getPersistentApplications(int flags) {
2355 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2356
2357 synchronized (mPackages) {
2358 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2359 while (i.hasNext()) {
2360 PackageParser.Package p = i.next();
2361 if (p.applicationInfo != null
2362 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2363 && (!mSafeMode || (p.applicationInfo.flags
2364 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2365 finalList.add(p.applicationInfo);
2366 }
2367 }
2368 }
2369
2370 return finalList;
2371 }
2372
2373 public ProviderInfo resolveContentProvider(String name, int flags) {
2374 synchronized (mPackages) {
2375 final PackageParser.Provider provider = mProviders.get(name);
2376 return provider != null
2377 && mSettings.isEnabledLP(provider.info, flags)
2378 && (!mSafeMode || (provider.info.applicationInfo.flags
2379 &ApplicationInfo.FLAG_SYSTEM) != 0)
2380 ? PackageParser.generateProviderInfo(provider, flags)
2381 : null;
2382 }
2383 }
2384
Fred Quintana718d8a22009-04-29 17:53:20 -07002385 /**
2386 * @deprecated
2387 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 public void querySyncProviders(List outNames, List outInfo) {
2389 synchronized (mPackages) {
2390 Iterator<Map.Entry<String, PackageParser.Provider>> i
2391 = mProviders.entrySet().iterator();
2392
2393 while (i.hasNext()) {
2394 Map.Entry<String, PackageParser.Provider> entry = i.next();
2395 PackageParser.Provider p = entry.getValue();
2396
2397 if (p.syncable
2398 && (!mSafeMode || (p.info.applicationInfo.flags
2399 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2400 outNames.add(entry.getKey());
2401 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2402 }
2403 }
2404 }
2405 }
2406
2407 public List<ProviderInfo> queryContentProviders(String processName,
2408 int uid, int flags) {
2409 ArrayList<ProviderInfo> finalList = null;
2410
2411 synchronized (mPackages) {
2412 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2413 while (i.hasNext()) {
2414 PackageParser.Provider p = i.next();
2415 if (p.info.authority != null
2416 && (processName == null ||
2417 (p.info.processName.equals(processName)
2418 && p.info.applicationInfo.uid == uid))
2419 && mSettings.isEnabledLP(p.info, flags)
2420 && (!mSafeMode || (p.info.applicationInfo.flags
2421 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2422 if (finalList == null) {
2423 finalList = new ArrayList<ProviderInfo>(3);
2424 }
2425 finalList.add(PackageParser.generateProviderInfo(p,
2426 flags));
2427 }
2428 }
2429 }
2430
2431 if (finalList != null) {
2432 Collections.sort(finalList, mProviderInitOrderSorter);
2433 }
2434
2435 return finalList;
2436 }
2437
2438 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2439 int flags) {
2440 synchronized (mPackages) {
2441 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2442 return PackageParser.generateInstrumentationInfo(i, flags);
2443 }
2444 }
2445
2446 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2447 int flags) {
2448 ArrayList<InstrumentationInfo> finalList =
2449 new ArrayList<InstrumentationInfo>();
2450
2451 synchronized (mPackages) {
2452 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2453 while (i.hasNext()) {
2454 PackageParser.Instrumentation p = i.next();
2455 if (targetPackage == null
2456 || targetPackage.equals(p.info.targetPackage)) {
2457 finalList.add(PackageParser.generateInstrumentationInfo(p,
2458 flags));
2459 }
2460 }
2461 }
2462
2463 return finalList;
2464 }
2465
2466 private void scanDirLI(File dir, int flags, int scanMode) {
2467 Log.d(TAG, "Scanning app dir " + dir);
2468
2469 String[] files = dir.list();
2470
2471 int i;
2472 for (i=0; i<files.length; i++) {
2473 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002474 if (!isPackageFilename(files[i])) {
2475 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002476 continue;
2477 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002478 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002480 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002481 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2482 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002483 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002484 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002485 file.delete();
2486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 }
2488 }
2489
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002490 private static File getSettingsProblemFile() {
2491 File dataDir = Environment.getDataDirectory();
2492 File systemDir = new File(dataDir, "system");
2493 File fname = new File(systemDir, "uiderrors.txt");
2494 return fname;
2495 }
2496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 private static void reportSettingsProblem(int priority, String msg) {
2498 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002499 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 FileOutputStream out = new FileOutputStream(fname, true);
2501 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002502 SimpleDateFormat formatter = new SimpleDateFormat();
2503 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2504 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 pw.close();
2506 FileUtils.setPermissions(
2507 fname.toString(),
2508 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2509 -1, -1);
2510 } catch (java.io.IOException e) {
2511 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002512 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514
2515 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2516 PackageParser.Package pkg, File srcFile, int parseFlags) {
2517 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002518 if (ps != null
2519 && ps.codePath.equals(srcFile)
2520 && ps.getTimeStamp() == srcFile.lastModified()) {
2521 if (ps.signatures.mSignatures != null
2522 && ps.signatures.mSignatures.length != 0) {
2523 // Optimization: reuse the existing cached certificates
2524 // if the package appears to be unchanged.
2525 pkg.mSignatures = ps.signatures.mSignatures;
2526 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
Jeff Browne7600722010-04-07 18:28:23 -07002528
2529 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002530 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002531 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2532 }
2533
2534 if (!pp.collectCertificates(pkg, parseFlags)) {
2535 mLastScanError = pp.getParseError();
2536 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
2538 }
2539 return true;
2540 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 /*
2543 * Scan a package and return the newly parsed package.
2544 * Returns null in case of errors and the error code is stored in mLastScanError
2545 */
2546 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002547 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002549 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002551 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002554 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 if (pkg == null) {
2556 mLastScanError = pp.getParseError();
2557 return null;
2558 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002559 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 PackageSetting updatedPkg;
2561 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002562 // Look to see if we already know about this package.
2563 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002564 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002565 // This package has been renamed to its original name. Let's
2566 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002567 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002568 }
2569 // If there was no original package, see one for the real package name.
2570 if (ps == null) {
2571 ps = mSettings.peekPackageLP(pkg.packageName);
2572 }
2573 // Check to see if this package could be hiding/updating a system
2574 // package. Must look for it either under the original or real
2575 // package name depending on our state.
2576 updatedPkg = mSettings.mDisabledSysPackages.get(
2577 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002579 // First check if this is a system package that may involve an update
2580 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2581 if (!ps.codePath.equals(scanFile)) {
2582 // The path has changed from what was last scanned... check the
2583 // version of the new path against what we have stored to determine
2584 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002585 if (pkg.mVersionCode < ps.versionCode) {
2586 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 // Ignore entry. Skip it.
2588 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2589 + "ignored: updated version " + ps.versionCode
2590 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002591 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2592 return null;
2593 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 // The current app on the system partion is better than
2595 // what we have updated to on the data partition; switch
2596 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002597 // At this point, its safely assumed that package installation for
2598 // apps in system partition will go through. If not there won't be a working
2599 // version of the app
2600 synchronized (mPackages) {
2601 // Just remove the loaded entries from package lists.
2602 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002603 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002604 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002605 + "reverting from " + ps.codePathString
2606 + ": new version " + pkg.mVersionCode
2607 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002608 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2609 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 }
2613 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 if (updatedPkg != null) {
2615 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2616 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2617 }
2618 // Verify certificates against what was last scanned
2619 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002620 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 return null;
2622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 // The apk is forward locked (not public) if its code and resources
2624 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002625 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002627 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002628 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002629
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002630 String codePath = null;
2631 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002632 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2633 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002634 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002635 } else {
2636 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002637 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002638 }
2639 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002640 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002641 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002642 codePath = pkg.mScanPath;
2643 // Set application objects path explicitly.
2644 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002646 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002649 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2650 String destCodePath, String destResPath) {
2651 pkg.mPath = pkg.mScanPath = destCodePath;
2652 pkg.applicationInfo.sourceDir = destCodePath;
2653 pkg.applicationInfo.publicSourceDir = destResPath;
2654 }
2655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 private static String fixProcessName(String defProcessName,
2657 String processName, int uid) {
2658 if (processName == null) {
2659 return defProcessName;
2660 }
2661 return processName;
2662 }
2663
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002664 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002665 PackageParser.Package pkg) {
2666 if (pkgSetting.signatures.mSignatures != null) {
2667 // Already existing package. Make sure signatures match
2668 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2669 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002670 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002671 + " signatures do not match the previously installed version; ignoring!");
2672 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 return false;
2674 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002675 }
2676 // Check for shared user signatures
2677 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2678 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2679 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2680 Slog.e(TAG, "Package " + pkg.packageName
2681 + " has no signatures that match those in shared user "
2682 + pkgSetting.sharedUser.name + "; ignoring!");
2683 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2684 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 }
2687 return true;
2688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002689
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002690 public boolean performDexOpt(String packageName) {
2691 if (!mNoDexOpt) {
2692 return false;
2693 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002694
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002695 PackageParser.Package p;
2696 synchronized (mPackages) {
2697 p = mPackages.get(packageName);
2698 if (p == null || p.mDidDexOpt) {
2699 return false;
2700 }
2701 }
2702 synchronized (mInstallLock) {
2703 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2704 }
2705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002706
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002707 static final int DEX_OPT_SKIPPED = 0;
2708 static final int DEX_OPT_PERFORMED = 1;
2709 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002710
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002711 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2712 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002713 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002714 String path = pkg.mScanPath;
2715 int ret = 0;
2716 try {
2717 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002718 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002719 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 pkg.mDidDexOpt = true;
2721 performed = true;
2722 }
2723 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002724 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 ret = -1;
2726 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002727 Slog.w(TAG, "IOException reading apk: " + path, e);
2728 ret = -1;
2729 } catch (dalvik.system.StaleDexCacheError e) {
2730 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2731 ret = -1;
2732 } catch (Exception e) {
2733 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002734 ret = -1;
2735 }
2736 if (ret < 0) {
2737 //error from installer
2738 return DEX_OPT_FAILED;
2739 }
2740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002741
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2743 }
2744
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002745 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2746 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002747 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002748 + " to " + newPkg.packageName
2749 + ": old package not in system partition");
2750 return false;
2751 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002752 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002753 + " to " + newPkg.packageName
2754 + ": old package still exists");
2755 return false;
2756 }
2757 return true;
2758 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002759
2760 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002761 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002762 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002763
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002764 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2765 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002766 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002767 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2768 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002769 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002770 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002771 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2772 return null;
2773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 mScanningPath = scanFile;
2775 if (pkg == null) {
2776 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2777 return null;
2778 }
2779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2781 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2782 }
2783
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002784 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 synchronized (mPackages) {
2786 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "*************************************************");
2788 Slog.w(TAG, "Core android package being redefined. Skipping.");
2789 Slog.w(TAG, " file=" + mScanningPath);
2790 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2792 return null;
2793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 // Set up information for our fall-back user intent resolution
2796 // activity.
2797 mPlatformPackage = pkg;
2798 pkg.mVersionCode = mSdkVersion;
2799 mAndroidApplication = pkg.applicationInfo;
2800 mResolveActivity.applicationInfo = mAndroidApplication;
2801 mResolveActivity.name = ResolverActivity.class.getName();
2802 mResolveActivity.packageName = mAndroidApplication.packageName;
2803 mResolveActivity.processName = mAndroidApplication.processName;
2804 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2805 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2806 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2807 mResolveActivity.exported = true;
2808 mResolveActivity.enabled = true;
2809 mResolveInfo.activityInfo = mResolveActivity;
2810 mResolveInfo.priority = 0;
2811 mResolveInfo.preferredOrder = 0;
2812 mResolveInfo.match = 0;
2813 mResolveComponentName = new ComponentName(
2814 mAndroidApplication.packageName, mResolveActivity.name);
2815 }
2816 }
2817
2818 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002819 TAG, "Scanning package " + pkg.packageName);
2820 if (mPackages.containsKey(pkg.packageName)
2821 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002822 Slog.w(TAG, "*************************************************");
2823 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002825 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2827 return null;
2828 }
2829
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002830 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002831 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2832 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 SharedUserSetting suid = null;
2835 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002836
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002837 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2838 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002839 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002840 pkg.mRealPackage = null;
2841 pkg.mAdoptPermissions = null;
2842 }
2843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 synchronized (mPackages) {
2845 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002846 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2847 if (mTmpSharedLibraries == null ||
2848 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2849 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2850 }
2851 int num = 0;
2852 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2853 for (int i=0; i<N; i++) {
2854 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002856 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002858 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2860 return null;
2861 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002862 mTmpSharedLibraries[num] = file;
2863 num++;
2864 }
2865 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2866 for (int i=0; i<N; i++) {
2867 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2868 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002869 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002870 + " desires unavailable shared library "
2871 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2872 } else {
2873 mTmpSharedLibraries[num] = file;
2874 num++;
2875 }
2876 }
2877 if (num > 0) {
2878 pkg.usesLibraryFiles = new String[num];
2879 System.arraycopy(mTmpSharedLibraries, 0,
2880 pkg.usesLibraryFiles, 0, num);
2881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002882
Dianne Hackborn49237342009-08-27 20:08:01 -07002883 if (pkg.reqFeatures != null) {
2884 N = pkg.reqFeatures.size();
2885 for (int i=0; i<N; i++) {
2886 FeatureInfo fi = pkg.reqFeatures.get(i);
2887 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2888 // Don't care.
2889 continue;
2890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002891
Dianne Hackborn49237342009-08-27 20:08:01 -07002892 if (fi.name != null) {
2893 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002894 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002895 + " requires unavailable feature "
2896 + fi.name + "; failing!");
2897 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2898 return null;
2899 }
2900 }
2901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 if (pkg.mSharedUserId != null) {
2906 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2907 pkg.applicationInfo.flags, true);
2908 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002909 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 + " for shared user failed");
2911 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2912 return null;
2913 }
2914 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2915 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2916 + suid.userId + "): packages=" + suid.packages);
2917 }
2918 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002919
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002920 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002921 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002922 Log.w(TAG, "WAITING FOR DEBUGGER");
2923 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002924 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2925 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002926 }
2927 }
2928
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002929 // Check if we are renaming from an original package name.
2930 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002931 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002932 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002933 // This package may need to be renamed to a previously
2934 // installed name. Let's check on that...
2935 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002936 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002937 // This package had originally been installed as the
2938 // original name, and we have already taken care of
2939 // transitioning to the new one. Just update the new
2940 // one to continue using the old name.
2941 realName = pkg.mRealPackage;
2942 if (!pkg.packageName.equals(renamed)) {
2943 // Callers into this function may have already taken
2944 // care of renaming the package; only do it here if
2945 // it is not already done.
2946 pkg.setPackageName(renamed);
2947 }
2948
Dianne Hackbornc1552392010-03-03 16:19:01 -08002949 } else {
2950 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2951 if ((origPackage=mSettings.peekPackageLP(
2952 pkg.mOriginalPackages.get(i))) != null) {
2953 // We do have the package already installed under its
2954 // original name... should we use it?
2955 if (!verifyPackageUpdate(origPackage, pkg)) {
2956 // New package is not compatible with original.
2957 origPackage = null;
2958 continue;
2959 } else if (origPackage.sharedUser != null) {
2960 // Make sure uid is compatible between packages.
2961 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002962 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 + " to " + pkg.packageName + ": old uid "
2964 + origPackage.sharedUser.name
2965 + " differs from " + pkg.mSharedUserId);
2966 origPackage = null;
2967 continue;
2968 }
2969 } else {
2970 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2971 + pkg.packageName + " to old name " + origPackage.name);
2972 }
2973 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002974 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002975 }
2976 }
2977 }
2978
2979 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002980 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002981 + " was transferred to another, but its .apk remains");
2982 }
2983
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002984 // Just create the setting, don't add it yet. For already existing packages
2985 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002986 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 destResourceFile, pkg.applicationInfo.flags, true, false);
2988 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002989 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2991 return null;
2992 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002993
2994 if (pkgSetting.origPackage != null) {
2995 // If we are first transitioning from an original package,
2996 // fix up the new package's name now. We need to do this after
2997 // looking up the package under its new name, so getPackageLP
2998 // can take care of fiddling things correctly.
2999 pkg.setPackageName(origPackage.name);
3000
3001 // File a report about this.
3002 String msg = "New package " + pkgSetting.realName
3003 + " renamed to replace old package " + pkgSetting.name;
3004 reportSettingsProblem(Log.WARN, msg);
3005
3006 // Make a note of it.
3007 mTransferedPackages.add(origPackage.name);
3008
3009 // No longer need to retain this.
3010 pkgSetting.origPackage = null;
3011 }
3012
3013 if (realName != null) {
3014 // Make a note of it.
3015 mTransferedPackages.add(pkg.packageName);
3016 }
3017
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003018 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3020 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 pkg.applicationInfo.uid = pkgSetting.userId;
3023 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003024
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003025 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003026 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 return null;
3028 }
3029 // The signature has changed, but this package is in the system
3030 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003031 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 // However... if this package is part of a shared user, but it
3033 // doesn't match the signature of the shared user, let's fail.
3034 // What this means is that you can't change the signatures
3035 // associated with an overall shared user, which doesn't seem all
3036 // that unreasonable.
3037 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003038 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3039 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3040 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3042 return null;
3043 }
3044 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003045 // File a report about this.
3046 String msg = "System package " + pkg.packageName
3047 + " signature changed; retaining data.";
3048 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003050
The Android Open Source Project10592532009-03-18 17:39:46 -07003051 // Verify that this new package doesn't have any content providers
3052 // that conflict with existing packages. Only do this if the
3053 // package isn't already installed, since we don't want to break
3054 // things that are installed.
3055 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3056 int N = pkg.providers.size();
3057 int i;
3058 for (i=0; i<N; i++) {
3059 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003060 if (p.info.authority != null) {
3061 String names[] = p.info.authority.split(";");
3062 for (int j = 0; j < names.length; j++) {
3063 if (mProviders.containsKey(names[j])) {
3064 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003065 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003066 " (in package " + pkg.applicationInfo.packageName +
3067 ") is already used by "
3068 + ((other != null && other.getComponentName() != null)
3069 ? other.getComponentName().getPackageName() : "?"));
3070 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3071 return null;
3072 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003073 }
3074 }
3075 }
3076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 }
3078
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003079 final String pkgName = pkg.packageName;
3080
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003081 if (pkg.mAdoptPermissions != null) {
3082 // This package wants to adopt ownership of permissions from
3083 // another package.
3084 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3085 String origName = pkg.mAdoptPermissions.get(i);
3086 PackageSetting orig = mSettings.peekPackageLP(origName);
3087 if (orig != null) {
3088 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003089 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003090 + origName + " to " + pkg.packageName);
3091 mSettings.transferPermissions(origName, pkg.packageName);
3092 }
3093 }
3094 }
3095 }
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 long scanFileTime = scanFile.lastModified();
3098 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3099 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3100 pkg.applicationInfo.processName = fixProcessName(
3101 pkg.applicationInfo.packageName,
3102 pkg.applicationInfo.processName,
3103 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104
3105 File dataPath;
3106 if (mPlatformPackage == pkg) {
3107 // The system package is special.
3108 dataPath = new File (Environment.getDataDirectory(), "system");
3109 pkg.applicationInfo.dataDir = dataPath.getPath();
3110 } else {
3111 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003112 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003113
3114 boolean uidError = false;
3115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 if (dataPath.exists()) {
3117 mOutPermissions[1] = 0;
3118 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3119 if (mOutPermissions[1] == pkg.applicationInfo.uid
3120 || !Process.supportsProcesses()) {
3121 pkg.applicationInfo.dataDir = dataPath.getPath();
3122 } else {
3123 boolean recovered = false;
3124 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3125 // If this is a system app, we can at least delete its
3126 // current data so the application will still work.
3127 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003128 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003129 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 // Old data gone!
3131 String msg = "System package " + pkg.packageName
3132 + " has changed from uid: "
3133 + mOutPermissions[1] + " to "
3134 + pkg.applicationInfo.uid + "; old data erased";
3135 reportSettingsProblem(Log.WARN, msg);
3136 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003138 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003139 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 pkg.applicationInfo.uid);
3141 if (ret == -1) {
3142 // Ack should not happen!
3143 msg = "System package " + pkg.packageName
3144 + " could not have data directory re-created after delete.";
3145 reportSettingsProblem(Log.WARN, msg);
3146 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3147 return null;
3148 }
3149 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 if (!recovered) {
3152 mHasSystemUidErrors = true;
3153 }
3154 }
3155 if (!recovered) {
3156 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3157 + pkg.applicationInfo.uid + "/fs_"
3158 + mOutPermissions[1];
3159 String msg = "Package " + pkg.packageName
3160 + " has mismatched uid: "
3161 + mOutPermissions[1] + " on disk, "
3162 + pkg.applicationInfo.uid + " in settings";
3163 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003164 mSettings.mReadMessages.append(msg);
3165 mSettings.mReadMessages.append('\n');
3166 uidError = true;
3167 if (!pkgSetting.uidError) {
3168 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 }
3171 }
3172 }
3173 pkg.applicationInfo.dataDir = dataPath.getPath();
3174 } else {
3175 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3176 Log.v(TAG, "Want this data dir: " + dataPath);
3177 //invoke installer to do the actual installation
3178 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003179 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 pkg.applicationInfo.uid);
3181 if(ret < 0) {
3182 // Error from installer
3183 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3184 return null;
3185 }
3186 } else {
3187 dataPath.mkdirs();
3188 if (dataPath.exists()) {
3189 FileUtils.setPermissions(
3190 dataPath.toString(),
3191 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3192 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3193 }
3194 }
3195 if (dataPath.exists()) {
3196 pkg.applicationInfo.dataDir = dataPath.getPath();
3197 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003198 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 pkg.applicationInfo.dataDir = null;
3200 }
3201 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003202
3203 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 }
3205
3206 // Perform shared library installation and dex validation and
3207 // optimization, if this is not a system app.
3208 if (mInstaller != null) {
3209 String path = scanFile.getPath();
3210 if (scanFileNewer) {
3211 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003212 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3213 if (err != PackageManager.INSTALL_SUCCEEDED) {
3214 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 return null;
3216 }
3217 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003218 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003219
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003220 if ((scanMode&SCAN_NO_DEX) == 0) {
3221 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3223 return null;
3224 }
3225 }
3226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 if (mFactoryTest && pkg.requestedPermissions.contains(
3229 android.Manifest.permission.FACTORY_TEST)) {
3230 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3231 }
3232
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003233 // Request the ActivityManager to kill the process(only for existing packages)
3234 // so that we do not end up in a confused state while the user is still using the older
3235 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003236 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003237 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003238 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003239 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003242 // We don't expect installation to fail beyond this point,
3243 if ((scanMode&SCAN_MONITOR) != 0) {
3244 mAppDirs.put(pkg.mPath, pkg);
3245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003247 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003249 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003250 // Make sure we don't accidentally delete its data.
3251 mSettings.mPackagesToBeCleaned.remove(pkgName);
3252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003253 int N = pkg.providers.size();
3254 StringBuilder r = null;
3255 int i;
3256 for (i=0; i<N; i++) {
3257 PackageParser.Provider p = pkg.providers.get(i);
3258 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3259 p.info.processName, pkg.applicationInfo.uid);
3260 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3261 p.info.name), p);
3262 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003263 if (p.info.authority != null) {
3264 String names[] = p.info.authority.split(";");
3265 p.info.authority = null;
3266 for (int j = 0; j < names.length; j++) {
3267 if (j == 1 && p.syncable) {
3268 // We only want the first authority for a provider to possibly be
3269 // syncable, so if we already added this provider using a different
3270 // authority clear the syncable flag. We copy the provider before
3271 // changing it because the mProviders object contains a reference
3272 // to a provider that we don't want to change.
3273 // Only do this for the second authority since the resulting provider
3274 // object can be the same for all future authorities for this provider.
3275 p = new PackageParser.Provider(p);
3276 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003278 if (!mProviders.containsKey(names[j])) {
3279 mProviders.put(names[j], p);
3280 if (p.info.authority == null) {
3281 p.info.authority = names[j];
3282 } else {
3283 p.info.authority = p.info.authority + ";" + names[j];
3284 }
3285 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3286 Log.d(TAG, "Registered content provider: " + names[j] +
3287 ", className = " + p.info.name +
3288 ", isSyncable = " + p.info.isSyncable);
3289 } else {
3290 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003291 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003292 " (in package " + pkg.applicationInfo.packageName +
3293 "): name already used by "
3294 + ((other != null && other.getComponentName() != null)
3295 ? other.getComponentName().getPackageName() : "?"));
3296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298 }
3299 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3300 if (r == null) {
3301 r = new StringBuilder(256);
3302 } else {
3303 r.append(' ');
3304 }
3305 r.append(p.info.name);
3306 }
3307 }
3308 if (r != null) {
3309 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 N = pkg.services.size();
3313 r = null;
3314 for (i=0; i<N; i++) {
3315 PackageParser.Service s = pkg.services.get(i);
3316 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3317 s.info.processName, pkg.applicationInfo.uid);
3318 mServices.addService(s);
3319 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3320 if (r == null) {
3321 r = new StringBuilder(256);
3322 } else {
3323 r.append(' ');
3324 }
3325 r.append(s.info.name);
3326 }
3327 }
3328 if (r != null) {
3329 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 N = pkg.receivers.size();
3333 r = null;
3334 for (i=0; i<N; i++) {
3335 PackageParser.Activity a = pkg.receivers.get(i);
3336 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3337 a.info.processName, pkg.applicationInfo.uid);
3338 mReceivers.addActivity(a, "receiver");
3339 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3340 if (r == null) {
3341 r = new StringBuilder(256);
3342 } else {
3343 r.append(' ');
3344 }
3345 r.append(a.info.name);
3346 }
3347 }
3348 if (r != null) {
3349 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3350 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 N = pkg.activities.size();
3353 r = null;
3354 for (i=0; i<N; i++) {
3355 PackageParser.Activity a = pkg.activities.get(i);
3356 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3357 a.info.processName, pkg.applicationInfo.uid);
3358 mActivities.addActivity(a, "activity");
3359 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3360 if (r == null) {
3361 r = new StringBuilder(256);
3362 } else {
3363 r.append(' ');
3364 }
3365 r.append(a.info.name);
3366 }
3367 }
3368 if (r != null) {
3369 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 N = pkg.permissionGroups.size();
3373 r = null;
3374 for (i=0; i<N; i++) {
3375 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3376 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3377 if (cur == null) {
3378 mPermissionGroups.put(pg.info.name, pg);
3379 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3380 if (r == null) {
3381 r = new StringBuilder(256);
3382 } else {
3383 r.append(' ');
3384 }
3385 r.append(pg.info.name);
3386 }
3387 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003388 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 + pg.info.packageName + " ignored: original from "
3390 + cur.info.packageName);
3391 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3392 if (r == null) {
3393 r = new StringBuilder(256);
3394 } else {
3395 r.append(' ');
3396 }
3397 r.append("DUP:");
3398 r.append(pg.info.name);
3399 }
3400 }
3401 }
3402 if (r != null) {
3403 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3404 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 N = pkg.permissions.size();
3407 r = null;
3408 for (i=0; i<N; i++) {
3409 PackageParser.Permission p = pkg.permissions.get(i);
3410 HashMap<String, BasePermission> permissionMap =
3411 p.tree ? mSettings.mPermissionTrees
3412 : mSettings.mPermissions;
3413 p.group = mPermissionGroups.get(p.info.group);
3414 if (p.info.group == null || p.group != null) {
3415 BasePermission bp = permissionMap.get(p.info.name);
3416 if (bp == null) {
3417 bp = new BasePermission(p.info.name, p.info.packageName,
3418 BasePermission.TYPE_NORMAL);
3419 permissionMap.put(p.info.name, bp);
3420 }
3421 if (bp.perm == null) {
3422 if (bp.sourcePackage == null
3423 || bp.sourcePackage.equals(p.info.packageName)) {
3424 BasePermission tree = findPermissionTreeLP(p.info.name);
3425 if (tree == null
3426 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003427 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 bp.perm = p;
3429 bp.uid = pkg.applicationInfo.uid;
3430 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3431 if (r == null) {
3432 r = new StringBuilder(256);
3433 } else {
3434 r.append(' ');
3435 }
3436 r.append(p.info.name);
3437 }
3438 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003439 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 + p.info.packageName + " ignored: base tree "
3441 + tree.name + " is from package "
3442 + tree.sourcePackage);
3443 }
3444 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003445 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 + p.info.packageName + " ignored: original from "
3447 + bp.sourcePackage);
3448 }
3449 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3450 if (r == null) {
3451 r = new StringBuilder(256);
3452 } else {
3453 r.append(' ');
3454 }
3455 r.append("DUP:");
3456 r.append(p.info.name);
3457 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003458 if (bp.perm == p) {
3459 bp.protectionLevel = p.info.protectionLevel;
3460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003462 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 + p.info.packageName + " ignored: no group "
3464 + p.group);
3465 }
3466 }
3467 if (r != null) {
3468 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3469 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 N = pkg.instrumentation.size();
3472 r = null;
3473 for (i=0; i<N; i++) {
3474 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3475 a.info.packageName = pkg.applicationInfo.packageName;
3476 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3477 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3478 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003479 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3481 if (r == null) {
3482 r = new StringBuilder(256);
3483 } else {
3484 r.append(' ');
3485 }
3486 r.append(a.info.name);
3487 }
3488 }
3489 if (r != null) {
3490 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003492
Dianne Hackborn854060af2009-07-09 18:14:31 -07003493 if (pkg.protectedBroadcasts != null) {
3494 N = pkg.protectedBroadcasts.size();
3495 for (i=0; i<N; i++) {
3496 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3497 }
3498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 pkgSetting.setTimeStamp(scanFileTime);
3501 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 return pkg;
3504 }
3505
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003506 private void killApplication(String pkgName, int uid) {
3507 // Request the ActivityManager to kill the process(only for existing packages)
3508 // so that we do not end up in a confused state while the user is still using the older
3509 // version of the application while the new one gets installed.
3510 IActivityManager am = ActivityManagerNative.getDefault();
3511 if (am != null) {
3512 try {
3513 am.killApplicationWithUid(pkgName, uid);
3514 } catch (RemoteException e) {
3515 }
3516 }
3517 }
3518
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003519 // The following constants are returned by cachePackageSharedLibsForAbiLI
3520 // to indicate if native shared libraries were found in the package.
3521 // Values are:
3522 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3523 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3524 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3525 // in package (and not installed)
3526 //
3527 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3528 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3529 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003531 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3532 // and automatically copy them to /data/data/<appname>/lib if present.
3533 //
3534 // NOTE: this method may throw an IOException if the library cannot
3535 // be copied to its final destination, e.g. if there isn't enough
3536 // room left on the data partition, or a ZipException if the package
3537 // file is malformed.
3538 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003539 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3540 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003541 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3542 final String apkLib = "lib/";
3543 final int apkLibLen = apkLib.length();
3544 final int cpuAbiLen = cpuAbi.length();
3545 final String libPrefix = "lib";
3546 final int libPrefixLen = libPrefix.length();
3547 final String libSuffix = ".so";
3548 final int libSuffixLen = libSuffix.length();
3549 boolean hasNativeLibraries = false;
3550 boolean installedNativeLibraries = false;
3551
3552 // the minimum length of a valid native shared library of the form
3553 // lib/<something>/lib<name>.so.
3554 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3555
3556 ZipFile zipFile = new ZipFile(scanFile);
3557 Enumeration<ZipEntry> entries =
3558 (Enumeration<ZipEntry>) zipFile.entries();
3559
3560 while (entries.hasMoreElements()) {
3561 ZipEntry entry = entries.nextElement();
3562 // skip directories
3563 if (entry.isDirectory()) {
3564 continue;
3565 }
3566 String entryName = entry.getName();
3567
3568 // check that the entry looks like lib/<something>/lib<name>.so
3569 // here, but don't check the ABI just yet.
3570 //
3571 // - must be sufficiently long
3572 // - must end with libSuffix, i.e. ".so"
3573 // - must start with apkLib, i.e. "lib/"
3574 if (entryName.length() < minEntryLen ||
3575 !entryName.endsWith(libSuffix) ||
3576 !entryName.startsWith(apkLib) ) {
3577 continue;
3578 }
3579
3580 // file name must start with libPrefix, i.e. "lib"
3581 int lastSlash = entryName.lastIndexOf('/');
3582
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003583 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003584 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3585 continue;
3586 }
3587
3588 hasNativeLibraries = true;
3589
3590 // check the cpuAbi now, between lib/ and /lib<name>.so
3591 //
3592 if (lastSlash != apkLibLen + cpuAbiLen ||
3593 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3594 continue;
3595
3596 // extract the library file name, ensure it doesn't contain
3597 // weird characters. we're guaranteed here that it doesn't contain
3598 // a directory separator though.
3599 String libFileName = entryName.substring(lastSlash+1);
3600 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3601 continue;
3602 }
3603
3604 installedNativeLibraries = true;
3605
3606 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3607 File.separator + libFileName;
3608 File sharedLibraryFile = new File(sharedLibraryFilePath);
3609 if (! sharedLibraryFile.exists() ||
3610 sharedLibraryFile.length() != entry.getSize() ||
3611 sharedLibraryFile.lastModified() != entry.getTime()) {
3612 if (Config.LOGD) {
3613 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003614 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003615 if (mInstaller == null) {
3616 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003617 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003618 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003619 sharedLibraryFile);
3620 }
3621 }
3622 if (!hasNativeLibraries)
3623 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3624
3625 if (!installedNativeLibraries)
3626 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3627
3628 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3629 }
3630
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003631 // Find the gdbserver executable program in a package at
3632 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3633 //
3634 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3635 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3636 //
3637 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3638 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3639 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3640 final String GDBSERVER = "gdbserver";
3641 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3642
3643 ZipFile zipFile = new ZipFile(scanFile);
3644 Enumeration<ZipEntry> entries =
3645 (Enumeration<ZipEntry>) zipFile.entries();
3646
3647 while (entries.hasMoreElements()) {
3648 ZipEntry entry = entries.nextElement();
3649 // skip directories
3650 if (entry.isDirectory()) {
3651 continue;
3652 }
3653 String entryName = entry.getName();
3654
3655 if (!entryName.equals(apkGdbServerPath)) {
3656 continue;
3657 }
3658
3659 String installGdbServerPath = installGdbServerDir.getPath() +
3660 "/" + GDBSERVER;
3661 File installGdbServerFile = new File(installGdbServerPath);
3662 if (! installGdbServerFile.exists() ||
3663 installGdbServerFile.length() != entry.getSize() ||
3664 installGdbServerFile.lastModified() != entry.getTime()) {
3665 if (Config.LOGD) {
3666 Log.d(TAG, "Caching gdbserver " + entry.getName());
3667 }
3668 if (mInstaller == null) {
3669 installGdbServerDir.mkdir();
3670 }
3671 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3672 installGdbServerFile);
3673 }
3674 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3675 }
3676 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3677 }
3678
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003679 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3680 // and copy them to /data/data/<appname>/lib.
3681 //
3682 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3683 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3684 // one if ro.product.cpu.abi2 is defined.
3685 //
3686 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3687 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003688 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003689 try {
3690 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3691
3692 // some architectures are capable of supporting several CPU ABIs
3693 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3694 // this is indicated by the definition of the ro.product.cpu.abi2
3695 // system property.
3696 //
3697 // only scan the package twice in case of ABI mismatch
3698 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003699 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003700 if (cpuAbi2 != null) {
3701 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003703
3704 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003705 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003706 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003708
3709 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3710 cpuAbi = cpuAbi2;
3711 }
3712 }
3713
3714 // for debuggable packages, also extract gdbserver from lib/<abi>
3715 // into /data/data/<appname>/lib too.
3716 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3717 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3718 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3719 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3720 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003723 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003724 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003725 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003727 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003728 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003730 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 }
3732
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003733 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003735 File binaryDir,
3736 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 InputStream inputStream = zipFile.getInputStream(entry);
3738 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003739 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003741 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 // now need to be left as world readable and owned by the system.
3743 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3744 ! tempFile.setLastModified(entry.getTime()) ||
3745 FileUtils.setPermissions(tempFilePath,
3746 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003747 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003748 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003749 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 // Failed to properly write file.
3751 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003752 throw new IOException("Couldn't create cached binary "
3753 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754 }
3755 } finally {
3756 inputStream.close();
3757 }
3758 }
3759
3760 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3761 if (chatty && Config.LOGD) Log.d(
3762 TAG, "Removing package " + pkg.applicationInfo.packageName );
3763
3764 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 mPackages.remove(pkg.applicationInfo.packageName);
3768 if (pkg.mPath != null) {
3769 mAppDirs.remove(pkg.mPath);
3770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 PackageSetting ps = (PackageSetting)pkg.mExtras;
3773 if (ps != null && ps.sharedUser != null) {
3774 // XXX don't do this until the data is removed.
3775 if (false) {
3776 ps.sharedUser.packages.remove(ps);
3777 if (ps.sharedUser.packages.size() == 0) {
3778 // Remove.
3779 }
3780 }
3781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 int N = pkg.providers.size();
3784 StringBuilder r = null;
3785 int i;
3786 for (i=0; i<N; i++) {
3787 PackageParser.Provider p = pkg.providers.get(i);
3788 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3789 p.info.name));
3790 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 /* The is another ContentProvider with this authority when
3793 * this app was installed so this authority is null,
3794 * Ignore it as we don't have to unregister the provider.
3795 */
3796 continue;
3797 }
3798 String names[] = p.info.authority.split(";");
3799 for (int j = 0; j < names.length; j++) {
3800 if (mProviders.get(names[j]) == p) {
3801 mProviders.remove(names[j]);
3802 if (chatty && Config.LOGD) Log.d(
3803 TAG, "Unregistered content provider: " + names[j] +
3804 ", className = " + p.info.name +
3805 ", isSyncable = " + p.info.isSyncable);
3806 }
3807 }
3808 if (chatty) {
3809 if (r == null) {
3810 r = new StringBuilder(256);
3811 } else {
3812 r.append(' ');
3813 }
3814 r.append(p.info.name);
3815 }
3816 }
3817 if (r != null) {
3818 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 N = pkg.services.size();
3822 r = null;
3823 for (i=0; i<N; i++) {
3824 PackageParser.Service s = pkg.services.get(i);
3825 mServices.removeService(s);
3826 if (chatty) {
3827 if (r == null) {
3828 r = new StringBuilder(256);
3829 } else {
3830 r.append(' ');
3831 }
3832 r.append(s.info.name);
3833 }
3834 }
3835 if (r != null) {
3836 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 N = pkg.receivers.size();
3840 r = null;
3841 for (i=0; i<N; i++) {
3842 PackageParser.Activity a = pkg.receivers.get(i);
3843 mReceivers.removeActivity(a, "receiver");
3844 if (chatty) {
3845 if (r == null) {
3846 r = new StringBuilder(256);
3847 } else {
3848 r.append(' ');
3849 }
3850 r.append(a.info.name);
3851 }
3852 }
3853 if (r != null) {
3854 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 N = pkg.activities.size();
3858 r = null;
3859 for (i=0; i<N; i++) {
3860 PackageParser.Activity a = pkg.activities.get(i);
3861 mActivities.removeActivity(a, "activity");
3862 if (chatty) {
3863 if (r == null) {
3864 r = new StringBuilder(256);
3865 } else {
3866 r.append(' ');
3867 }
3868 r.append(a.info.name);
3869 }
3870 }
3871 if (r != null) {
3872 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 N = pkg.permissions.size();
3876 r = null;
3877 for (i=0; i<N; i++) {
3878 PackageParser.Permission p = pkg.permissions.get(i);
3879 boolean tree = false;
3880 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3881 if (bp == null) {
3882 tree = true;
3883 bp = mSettings.mPermissionTrees.get(p.info.name);
3884 }
3885 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 if (chatty) {
3888 if (r == null) {
3889 r = new StringBuilder(256);
3890 } else {
3891 r.append(' ');
3892 }
3893 r.append(p.info.name);
3894 }
3895 }
3896 }
3897 if (r != null) {
3898 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 N = pkg.instrumentation.size();
3902 r = null;
3903 for (i=0; i<N; i++) {
3904 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003905 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 if (chatty) {
3907 if (r == null) {
3908 r = new StringBuilder(256);
3909 } else {
3910 r.append(' ');
3911 }
3912 r.append(a.info.name);
3913 }
3914 }
3915 if (r != null) {
3916 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3917 }
3918 }
3919 }
3920
3921 private static final boolean isPackageFilename(String name) {
3922 return name != null && name.endsWith(".apk");
3923 }
3924
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003925 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3926 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3927 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3928 return true;
3929 }
3930 }
3931 return false;
3932 }
3933
3934 private void updatePermissionsLP(String changingPkg,
3935 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 // Make sure there are no dangling permission trees.
3937 Iterator<BasePermission> it = mSettings.mPermissionTrees
3938 .values().iterator();
3939 while (it.hasNext()) {
3940 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003941 if (bp.packageSetting == null) {
3942 // We may not yet have parsed the package, so just see if
3943 // we still know about its settings.
3944 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3945 }
3946 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003947 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 + " from package " + bp.sourcePackage);
3949 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003950 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3951 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3952 Slog.i(TAG, "Removing old permission tree: " + bp.name
3953 + " from package " + bp.sourcePackage);
3954 grantPermissions = true;
3955 it.remove();
3956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 }
3958 }
3959
3960 // Make sure all dynamic permissions have been assigned to a package,
3961 // and make sure there are no dangling permissions.
3962 it = mSettings.mPermissions.values().iterator();
3963 while (it.hasNext()) {
3964 BasePermission bp = it.next();
3965 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3966 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3967 + bp.name + " pkg=" + bp.sourcePackage
3968 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003969 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 BasePermission tree = findPermissionTreeLP(bp.name);
3971 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003972 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 bp.perm = new PackageParser.Permission(tree.perm.owner,
3974 new PermissionInfo(bp.pendingInfo));
3975 bp.perm.info.packageName = tree.perm.info.packageName;
3976 bp.perm.info.name = bp.name;
3977 bp.uid = tree.uid;
3978 }
3979 }
3980 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003981 if (bp.packageSetting == null) {
3982 // We may not yet have parsed the package, so just see if
3983 // we still know about its settings.
3984 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3985 }
3986 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003987 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 + " from package " + bp.sourcePackage);
3989 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003990 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3991 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3992 Slog.i(TAG, "Removing old permission: " + bp.name
3993 + " from package " + bp.sourcePackage);
3994 grantPermissions = true;
3995 it.remove();
3996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 }
3998 }
3999
4000 // Now update the permissions for all packages, in particular
4001 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004002 if (grantPermissions) {
4003 for (PackageParser.Package pkg : mPackages.values()) {
4004 if (pkg != pkgInfo) {
4005 grantPermissionsLP(pkg, false);
4006 }
4007 }
4008 }
4009
4010 if (pkgInfo != null) {
4011 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 }
4013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4016 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4017 if (ps == null) {
4018 return;
4019 }
4020 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004021 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 if (replace) {
4024 ps.permissionsFixed = false;
4025 if (gp == ps) {
4026 gp.grantedPermissions.clear();
4027 gp.gids = mGlobalGids;
4028 }
4029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 if (gp.gids == null) {
4032 gp.gids = mGlobalGids;
4033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 final int N = pkg.requestedPermissions.size();
4036 for (int i=0; i<N; i++) {
4037 String name = pkg.requestedPermissions.get(i);
4038 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 if (false) {
4040 if (gp != ps) {
4041 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004042 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 }
4044 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004045 if (bp != null && bp.packageSetting != null) {
4046 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004048 boolean allowedSig = false;
4049 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4050 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004052 } else if (bp.packageSetting == null) {
4053 // This permission is invalid; skip it.
4054 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004055 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4056 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4057 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004059 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004061 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4063 // For updated system applications, the signatureOrSystem permission
4064 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004065 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4067 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4068 if(sysPs.grantedPermissions.contains(perm)) {
4069 allowed = true;
4070 } else {
4071 allowed = false;
4072 }
4073 } else {
4074 allowed = true;
4075 }
4076 }
4077 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004078 if (allowed) {
4079 allowedSig = true;
4080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 } else {
4082 allowed = false;
4083 }
4084 if (false) {
4085 if (gp != ps) {
4086 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4087 }
4088 }
4089 if (allowed) {
4090 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4091 && ps.permissionsFixed) {
4092 // If this is an existing, non-system package, then
4093 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004094 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004096 // Except... if this is a permission that was added
4097 // to the platform (note: need to only do this when
4098 // updating the platform).
4099 final int NP = PackageParser.NEW_PERMISSIONS.length;
4100 for (int ip=0; ip<NP; ip++) {
4101 final PackageParser.NewPermissionInfo npi
4102 = PackageParser.NEW_PERMISSIONS[ip];
4103 if (npi.name.equals(perm)
4104 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4105 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004106 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004107 + pkg.packageName);
4108 break;
4109 }
4110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 }
4112 }
4113 if (allowed) {
4114 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004115 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 gp.grantedPermissions.add(perm);
4117 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004118 } else if (!ps.haveGids) {
4119 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 }
4121 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004122 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 + " to package " + pkg.packageName
4124 + " because it was previously installed without");
4125 }
4126 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004127 if (gp.grantedPermissions.remove(perm)) {
4128 changedPermission = true;
4129 gp.gids = removeInts(gp.gids, bp.gids);
4130 Slog.i(TAG, "Un-granting permission " + perm
4131 + " from package " + pkg.packageName
4132 + " (protectionLevel=" + bp.protectionLevel
4133 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4134 + ")");
4135 } else {
4136 Slog.w(TAG, "Not granting permission " + perm
4137 + " to package " + pkg.packageName
4138 + " (protectionLevel=" + bp.protectionLevel
4139 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4140 + ")");
4141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 }
4143 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004144 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 + " in package " + pkg.packageName);
4146 }
4147 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004148
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004149 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004150 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4151 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 // This is the first that we have heard about this package, so the
4153 // permissions we have now selected are fixed until explicitly
4154 // changed.
4155 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004157 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 private final class ActivityIntentResolver
4161 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004162 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004164 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 }
4166
Mihai Preda074edef2009-05-18 17:13:31 +02004167 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004169 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4171 }
4172
Mihai Predaeae850c2009-05-13 10:13:48 +02004173 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4174 ArrayList<PackageParser.Activity> packageActivities) {
4175 if (packageActivities == null) {
4176 return null;
4177 }
4178 mFlags = flags;
4179 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4180 int N = packageActivities.size();
4181 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4182 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004183
4184 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004185 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004186 intentFilters = packageActivities.get(i).intents;
4187 if (intentFilters != null && intentFilters.size() > 0) {
4188 listCut.add(intentFilters);
4189 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004190 }
4191 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4192 }
4193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004195 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 if (SHOW_INFO || Config.LOGV) Log.v(
4197 TAG, " " + type + " " +
4198 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4199 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4200 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004201 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4203 if (SHOW_INFO || Config.LOGV) {
4204 Log.v(TAG, " IntentFilter:");
4205 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4206 }
4207 if (!intent.debugCheck()) {
4208 Log.w(TAG, "==> For Activity " + a.info.name);
4209 }
4210 addFilter(intent);
4211 }
4212 }
4213
4214 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004215 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 if (SHOW_INFO || Config.LOGV) Log.v(
4217 TAG, " " + type + " " +
4218 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4219 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4220 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004221 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4223 if (SHOW_INFO || Config.LOGV) {
4224 Log.v(TAG, " IntentFilter:");
4225 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4226 }
4227 removeFilter(intent);
4228 }
4229 }
4230
4231 @Override
4232 protected boolean allowFilterResult(
4233 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4234 ActivityInfo filterAi = filter.activity.info;
4235 for (int i=dest.size()-1; i>=0; i--) {
4236 ActivityInfo destAi = dest.get(i).activityInfo;
4237 if (destAi.name == filterAi.name
4238 && destAi.packageName == filterAi.packageName) {
4239 return false;
4240 }
4241 }
4242 return true;
4243 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004246 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4247 return info.activity.owner.packageName;
4248 }
4249
4250 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4252 int match) {
4253 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4254 return null;
4255 }
4256 final PackageParser.Activity activity = info.activity;
4257 if (mSafeMode && (activity.info.applicationInfo.flags
4258 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4259 return null;
4260 }
4261 final ResolveInfo res = new ResolveInfo();
4262 res.activityInfo = PackageParser.generateActivityInfo(activity,
4263 mFlags);
4264 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4265 res.filter = info;
4266 }
4267 res.priority = info.getPriority();
4268 res.preferredOrder = activity.owner.mPreferredOrder;
4269 //System.out.println("Result: " + res.activityInfo.className +
4270 // " = " + res.priority);
4271 res.match = match;
4272 res.isDefault = info.hasDefault;
4273 res.labelRes = info.labelRes;
4274 res.nonLocalizedLabel = info.nonLocalizedLabel;
4275 res.icon = info.icon;
4276 return res;
4277 }
4278
4279 @Override
4280 protected void sortResults(List<ResolveInfo> results) {
4281 Collections.sort(results, mResolvePrioritySorter);
4282 }
4283
4284 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004285 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004287 out.print(prefix); out.print(
4288 Integer.toHexString(System.identityHashCode(filter.activity)));
4289 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004290 out.print(filter.activity.getComponentShortName());
4291 out.print(" filter ");
4292 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 }
4294
4295// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4296// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4297// final List<ResolveInfo> retList = Lists.newArrayList();
4298// while (i.hasNext()) {
4299// final ResolveInfo resolveInfo = i.next();
4300// if (isEnabledLP(resolveInfo.activityInfo)) {
4301// retList.add(resolveInfo);
4302// }
4303// }
4304// return retList;
4305// }
4306
4307 // Keys are String (activity class name), values are Activity.
4308 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4309 = new HashMap<ComponentName, PackageParser.Activity>();
4310 private int mFlags;
4311 }
4312
4313 private final class ServiceIntentResolver
4314 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004315 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004317 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319
Mihai Preda074edef2009-05-18 17:13:31 +02004320 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004322 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4324 }
4325
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004326 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4327 ArrayList<PackageParser.Service> packageServices) {
4328 if (packageServices == null) {
4329 return null;
4330 }
4331 mFlags = flags;
4332 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4333 int N = packageServices.size();
4334 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4335 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4336
4337 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4338 for (int i = 0; i < N; ++i) {
4339 intentFilters = packageServices.get(i).intents;
4340 if (intentFilters != null && intentFilters.size() > 0) {
4341 listCut.add(intentFilters);
4342 }
4343 }
4344 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4345 }
4346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004348 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 if (SHOW_INFO || Config.LOGV) Log.v(
4350 TAG, " " + (s.info.nonLocalizedLabel != null
4351 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4352 if (SHOW_INFO || Config.LOGV) Log.v(
4353 TAG, " Class=" + s.info.name);
4354 int NI = s.intents.size();
4355 int j;
4356 for (j=0; j<NI; j++) {
4357 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4358 if (SHOW_INFO || Config.LOGV) {
4359 Log.v(TAG, " IntentFilter:");
4360 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4361 }
4362 if (!intent.debugCheck()) {
4363 Log.w(TAG, "==> For Service " + s.info.name);
4364 }
4365 addFilter(intent);
4366 }
4367 }
4368
4369 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004370 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 if (SHOW_INFO || Config.LOGV) Log.v(
4372 TAG, " " + (s.info.nonLocalizedLabel != null
4373 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4374 if (SHOW_INFO || Config.LOGV) Log.v(
4375 TAG, " Class=" + s.info.name);
4376 int NI = s.intents.size();
4377 int j;
4378 for (j=0; j<NI; j++) {
4379 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4380 if (SHOW_INFO || Config.LOGV) {
4381 Log.v(TAG, " IntentFilter:");
4382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4383 }
4384 removeFilter(intent);
4385 }
4386 }
4387
4388 @Override
4389 protected boolean allowFilterResult(
4390 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4391 ServiceInfo filterSi = filter.service.info;
4392 for (int i=dest.size()-1; i>=0; i--) {
4393 ServiceInfo destAi = dest.get(i).serviceInfo;
4394 if (destAi.name == filterSi.name
4395 && destAi.packageName == filterSi.packageName) {
4396 return false;
4397 }
4398 }
4399 return true;
4400 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004403 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4404 return info.service.owner.packageName;
4405 }
4406
4407 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4409 int match) {
4410 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4411 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4412 return null;
4413 }
4414 final PackageParser.Service service = info.service;
4415 if (mSafeMode && (service.info.applicationInfo.flags
4416 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4417 return null;
4418 }
4419 final ResolveInfo res = new ResolveInfo();
4420 res.serviceInfo = PackageParser.generateServiceInfo(service,
4421 mFlags);
4422 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4423 res.filter = filter;
4424 }
4425 res.priority = info.getPriority();
4426 res.preferredOrder = service.owner.mPreferredOrder;
4427 //System.out.println("Result: " + res.activityInfo.className +
4428 // " = " + res.priority);
4429 res.match = match;
4430 res.isDefault = info.hasDefault;
4431 res.labelRes = info.labelRes;
4432 res.nonLocalizedLabel = info.nonLocalizedLabel;
4433 res.icon = info.icon;
4434 return res;
4435 }
4436
4437 @Override
4438 protected void sortResults(List<ResolveInfo> results) {
4439 Collections.sort(results, mResolvePrioritySorter);
4440 }
4441
4442 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004443 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004445 out.print(prefix); out.print(
4446 Integer.toHexString(System.identityHashCode(filter.service)));
4447 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004448 out.print(filter.service.getComponentShortName());
4449 out.print(" filter ");
4450 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 }
4452
4453// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4454// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4455// final List<ResolveInfo> retList = Lists.newArrayList();
4456// while (i.hasNext()) {
4457// final ResolveInfo resolveInfo = (ResolveInfo) i;
4458// if (isEnabledLP(resolveInfo.serviceInfo)) {
4459// retList.add(resolveInfo);
4460// }
4461// }
4462// return retList;
4463// }
4464
4465 // Keys are String (activity class name), values are Activity.
4466 private final HashMap<ComponentName, PackageParser.Service> mServices
4467 = new HashMap<ComponentName, PackageParser.Service>();
4468 private int mFlags;
4469 };
4470
4471 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4472 new Comparator<ResolveInfo>() {
4473 public int compare(ResolveInfo r1, ResolveInfo r2) {
4474 int v1 = r1.priority;
4475 int v2 = r2.priority;
4476 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4477 if (v1 != v2) {
4478 return (v1 > v2) ? -1 : 1;
4479 }
4480 v1 = r1.preferredOrder;
4481 v2 = r2.preferredOrder;
4482 if (v1 != v2) {
4483 return (v1 > v2) ? -1 : 1;
4484 }
4485 if (r1.isDefault != r2.isDefault) {
4486 return r1.isDefault ? -1 : 1;
4487 }
4488 v1 = r1.match;
4489 v2 = r2.match;
4490 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4491 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4492 }
4493 };
4494
4495 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4496 new Comparator<ProviderInfo>() {
4497 public int compare(ProviderInfo p1, ProviderInfo p2) {
4498 final int v1 = p1.initOrder;
4499 final int v2 = p2.initOrder;
4500 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4501 }
4502 };
4503
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004504 private static final void sendPackageBroadcast(String action, String pkg,
4505 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 IActivityManager am = ActivityManagerNative.getDefault();
4507 if (am != null) {
4508 try {
4509 final Intent intent = new Intent(action,
4510 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4511 if (extras != null) {
4512 intent.putExtras(extras);
4513 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004514 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004515 am.broadcastIntent(null, intent, null, finishedReceiver,
4516 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 } catch (RemoteException ex) {
4518 }
4519 }
4520 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004521
4522 public String nextPackageToClean(String lastPackage) {
4523 synchronized (mPackages) {
4524 if (!mMediaMounted) {
4525 // If the external storage is no longer mounted at this point,
4526 // the caller may not have been able to delete all of this
4527 // packages files and can not delete any more. Bail.
4528 return null;
4529 }
4530 if (lastPackage != null) {
4531 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4532 }
4533 return mSettings.mPackagesToBeCleaned.size() > 0
4534 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4535 }
4536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004538 void schedulePackageCleaning(String packageName) {
4539 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4540 }
4541
4542 void startCleaningPackages() {
4543 synchronized (mPackages) {
4544 if (!mMediaMounted) {
4545 return;
4546 }
4547 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4548 return;
4549 }
4550 }
4551 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4552 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4553 IActivityManager am = ActivityManagerNative.getDefault();
4554 if (am != null) {
4555 try {
4556 am.startService(null, intent, null);
4557 } catch (RemoteException e) {
4558 }
4559 }
4560 }
4561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 private final class AppDirObserver extends FileObserver {
4563 public AppDirObserver(String path, int mask, boolean isrom) {
4564 super(path, mask);
4565 mRootDir = path;
4566 mIsRom = isrom;
4567 }
4568
4569 public void onEvent(int event, String path) {
4570 String removedPackage = null;
4571 int removedUid = -1;
4572 String addedPackage = null;
4573 int addedUid = -1;
4574
4575 synchronized (mInstallLock) {
4576 String fullPathStr = null;
4577 File fullPath = null;
4578 if (path != null) {
4579 fullPath = new File(mRootDir, path);
4580 fullPathStr = fullPath.getPath();
4581 }
4582
4583 if (Config.LOGV) Log.v(
4584 TAG, "File " + fullPathStr + " changed: "
4585 + Integer.toHexString(event));
4586
4587 if (!isPackageFilename(path)) {
4588 if (Config.LOGV) Log.v(
4589 TAG, "Ignoring change of non-package file: " + fullPathStr);
4590 return;
4591 }
4592
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004593 // Ignore packages that are being installed or
4594 // have just been installed.
4595 if (ignoreCodePath(fullPathStr)) {
4596 return;
4597 }
4598 PackageParser.Package p = null;
4599 synchronized (mPackages) {
4600 p = mAppDirs.get(fullPathStr);
4601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004603 if (p != null) {
4604 removePackageLI(p, true);
4605 removedPackage = p.applicationInfo.packageName;
4606 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 }
4608 }
4609
4610 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004612 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004613 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4614 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 PackageParser.PARSE_CHATTY |
4616 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004617 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 if (p != null) {
4619 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004620 updatePermissionsLP(p.packageName, p,
4621 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 }
4623 addedPackage = p.applicationInfo.packageName;
4624 addedUid = p.applicationInfo.uid;
4625 }
4626 }
4627 }
4628
4629 synchronized (mPackages) {
4630 mSettings.writeLP();
4631 }
4632 }
4633
4634 if (removedPackage != null) {
4635 Bundle extras = new Bundle(1);
4636 extras.putInt(Intent.EXTRA_UID, removedUid);
4637 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004638 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4639 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 }
4641 if (addedPackage != null) {
4642 Bundle extras = new Bundle(1);
4643 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004644 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4645 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 }
4647 }
4648
4649 private final String mRootDir;
4650 private final boolean mIsRom;
4651 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004653 /* Called when a downloaded package installation has been confirmed by the user */
4654 public void installPackage(
4655 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004656 installPackage(packageURI, observer, flags, null);
4657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004658
Jacek Surazski65e13172009-04-28 15:26:38 +02004659 /* Called when a downloaded package installation has been confirmed by the user */
4660 public void installPackage(
4661 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4662 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 mContext.enforceCallingOrSelfPermission(
4664 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004665
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004666 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004667 msg.obj = new InstallParams(packageURI, observer, flags,
4668 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004669 mHandler.sendMessage(msg);
4670 }
4671
Christopher Tate1bb69062010-02-19 17:02:12 -08004672 public void finishPackageInstall(int token) {
4673 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4674 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4675 mHandler.sendMessage(msg);
4676 }
4677
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004678 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 // Queue up an async operation since the package installation may take a little while.
4680 mHandler.post(new Runnable() {
4681 public void run() {
4682 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004683 // Result object to be returned
4684 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004685 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004686 res.uid = -1;
4687 res.pkg = null;
4688 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004689 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004690 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004691 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004692 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004693 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004694 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004696
4697 // A restore should be performed at this point if (a) the install
4698 // succeeded, (b) the operation is not an update, and (c) the new
4699 // package has a backupAgent defined.
4700 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004701 boolean doRestore = (!update
4702 && res.pkg != null
4703 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004704
4705 // Set up the post-install work request bookkeeping. This will be used
4706 // and cleaned up by the post-install event handling regardless of whether
4707 // there's a restore pass performed. Token values are >= 1.
4708 int token;
4709 if (mNextInstallToken < 0) mNextInstallToken = 1;
4710 token = mNextInstallToken++;
4711
4712 PostInstallData data = new PostInstallData(args, res);
4713 mRunningInstalls.put(token, data);
4714 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4715
4716 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4717 // Pass responsibility to the Backup Manager. It will perform a
4718 // restore if appropriate, then pass responsibility back to the
4719 // Package Manager to run the post-install observer callbacks
4720 // and broadcasts.
4721 IBackupManager bm = IBackupManager.Stub.asInterface(
4722 ServiceManager.getService(Context.BACKUP_SERVICE));
4723 if (bm != null) {
4724 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4725 + " to BM for possible restore");
4726 try {
4727 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4728 } catch (RemoteException e) {
4729 // can't happen; the backup manager is local
4730 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004731 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004732 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004733 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004734 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004735 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004736 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004738 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004739
4740 if (!doRestore) {
4741 // No restore possible, or the Backup Manager was mysteriously not
4742 // available -- just fire the post-install work request directly.
4743 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4744 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4745 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 }
4748 });
4749 }
4750
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004751 abstract class HandlerParams {
4752 final static int MAX_RETRIES = 4;
4753 int retry = 0;
4754 final void startCopy() {
4755 try {
4756 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4757 retry++;
4758 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004759 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004760 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4761 handleServiceError();
4762 return;
4763 } else {
4764 handleStartCopy();
4765 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4766 mHandler.sendEmptyMessage(MCS_UNBIND);
4767 }
4768 } catch (RemoteException e) {
4769 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4770 mHandler.sendEmptyMessage(MCS_RECONNECT);
4771 }
4772 handleReturnCode();
4773 }
4774
4775 final void serviceError() {
4776 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4777 handleServiceError();
4778 handleReturnCode();
4779 }
4780 abstract void handleStartCopy() throws RemoteException;
4781 abstract void handleServiceError();
4782 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004783 }
4784
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004785 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004786 final IPackageInstallObserver observer;
4787 int flags;
4788 final Uri packageURI;
4789 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 private InstallArgs mArgs;
4791 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004792 InstallParams(Uri packageURI,
4793 IPackageInstallObserver observer, int flags,
4794 String installerPackageName) {
4795 this.packageURI = packageURI;
4796 this.flags = flags;
4797 this.observer = observer;
4798 this.installerPackageName = installerPackageName;
4799 }
4800
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004801 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4802 String packageName = pkgLite.packageName;
4803 int installLocation = pkgLite.installLocation;
4804 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4805 synchronized (mPackages) {
4806 PackageParser.Package pkg = mPackages.get(packageName);
4807 if (pkg != null) {
4808 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4809 // Check for updated system application.
4810 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4811 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004812 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004813 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4814 }
4815 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4816 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004817 if (onSd) {
4818 // Install flag overrides everything.
4819 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4820 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004821 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004822 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4823 // Application explicitly specified internal.
4824 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4825 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4826 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004827 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004828 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004829 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4830 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4831 }
4832 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004833 }
4834 }
4835 } else {
4836 // Invalid install. Return error code
4837 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4838 }
4839 }
4840 }
4841 // All the special cases have been taken care of.
4842 // Return result based on recommended install location.
4843 if (onSd) {
4844 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4845 }
4846 return pkgLite.recommendedInstallLocation;
4847 }
4848
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004849 /*
4850 * Invoke remote method to get package information and install
4851 * location values. Override install location based on default
4852 * policy if needed and then create install arguments based
4853 * on the install location.
4854 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004855 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004856 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004857 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4858 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004859 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4860 if (onInt && onSd) {
4861 // Check if both bits are set.
4862 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4863 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4864 } else if (fwdLocked && onSd) {
4865 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004866 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004867 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004868 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004869 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004870 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004871 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004872 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4873 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4874 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4875 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4876 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4878 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4879 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004880 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4881 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004883 // Override with defaults if needed.
4884 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004885 if (!onSd && !onInt) {
4886 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4888 // Set the flag to install on external media.
4889 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004890 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 } else {
4892 // Make sure the flag for installing on external
4893 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004894 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004895 flags &= ~PackageManager.INSTALL_EXTERNAL;
4896 }
4897 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 }
4899 }
4900 // Create the file args now.
4901 mArgs = createInstallArgs(this);
4902 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4903 // Create copy only if we are not in an erroneous state.
4904 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004905 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 }
4907 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004908 }
4909
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004910 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 void handleReturnCode() {
4912 processPendingInstall(mArgs, mRet);
4913 }
4914
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004915 @Override
4916 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004917 mArgs = createInstallArgs(this);
4918 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004920 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004921
4922 /*
4923 * Utility class used in movePackage api.
4924 * srcArgs and targetArgs are not set for invalid flags and make
4925 * sure to do null checks when invoking methods on them.
4926 * We probably want to return ErrorPrams for both failed installs
4927 * and moves.
4928 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004929 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004930 final IPackageMoveObserver observer;
4931 final int flags;
4932 final String packageName;
4933 final InstallArgs srcArgs;
4934 final InstallArgs targetArgs;
4935 int mRet;
4936 MoveParams(InstallArgs srcArgs,
4937 IPackageMoveObserver observer,
4938 int flags, String packageName) {
4939 this.srcArgs = srcArgs;
4940 this.observer = observer;
4941 this.flags = flags;
4942 this.packageName = packageName;
4943 if (srcArgs != null) {
4944 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4945 targetArgs = createInstallArgs(packageUri, flags, packageName);
4946 } else {
4947 targetArgs = null;
4948 }
4949 }
4950
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004951 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004952 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4953 // Check for storage space on target medium
4954 if (!targetArgs.checkFreeStorage(mContainerService)) {
4955 Log.w(TAG, "Insufficient storage to install");
4956 return;
4957 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004958 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004959 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004960 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004961 if (DEBUG_SD_INSTALL) {
4962 StringBuilder builder = new StringBuilder();
4963 if (srcArgs != null) {
4964 builder.append("src: ");
4965 builder.append(srcArgs.getCodePath());
4966 }
4967 if (targetArgs != null) {
4968 builder.append(" target : ");
4969 builder.append(targetArgs.getCodePath());
4970 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004971 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004972 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004973 }
4974
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004975 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004976 void handleReturnCode() {
4977 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004978 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4979 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4980 currentStatus = PackageManager.MOVE_SUCCEEDED;
4981 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4982 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4983 }
4984 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004985 }
4986
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004987 @Override
4988 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004989 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004991 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004992
4993 private InstallArgs createInstallArgs(InstallParams params) {
4994 if (installOnSd(params.flags)) {
4995 return new SdInstallArgs(params);
4996 } else {
4997 return new FileInstallArgs(params);
4998 }
4999 }
5000
5001 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5002 if (installOnSd(flags)) {
5003 return new SdInstallArgs(fullCodePath, fullResourcePath);
5004 } else {
5005 return new FileInstallArgs(fullCodePath, fullResourcePath);
5006 }
5007 }
5008
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005009 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
5010 if (installOnSd(flags)) {
5011 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5012 return new SdInstallArgs(packageURI, cid);
5013 } else {
5014 return new FileInstallArgs(packageURI, pkgName);
5015 }
5016 }
5017
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 static abstract class InstallArgs {
5019 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005020 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005021 final int flags;
5022 final Uri packageURI;
5023 final String installerPackageName;
5024
5025 InstallArgs(Uri packageURI,
5026 IPackageInstallObserver observer, int flags,
5027 String installerPackageName) {
5028 this.packageURI = packageURI;
5029 this.flags = flags;
5030 this.observer = observer;
5031 this.installerPackageName = installerPackageName;
5032 }
5033
5034 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005035 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005036 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005037 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005038 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005039 abstract String getCodePath();
5040 abstract String getResourcePath();
5041 // Need installer lock especially for dex file removal.
5042 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005043 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005044 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 }
5046
5047 class FileInstallArgs extends InstallArgs {
5048 File installDir;
5049 String codeFileName;
5050 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005051 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005052
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005053 FileInstallArgs(InstallParams params) {
5054 super(params.packageURI, params.observer,
5055 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005056 }
5057
5058 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5059 super(null, null, 0, null);
5060 File codeFile = new File(fullCodePath);
5061 installDir = codeFile.getParentFile();
5062 codeFileName = fullCodePath;
5063 resourceFileName = fullResourcePath;
5064 }
5065
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005066 FileInstallArgs(Uri packageURI, String pkgName) {
5067 super(packageURI, null, 0, null);
5068 boolean fwdLocked = isFwdLocked(flags);
5069 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5070 String apkName = getNextCodePath(null, pkgName, ".apk");
5071 codeFileName = new File(installDir, apkName + ".apk").getPath();
5072 resourceFileName = getResourcePathFromCodePath();
5073 }
5074
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005075 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5076 return imcs.checkFreeStorage(false, packageURI);
5077 }
5078
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005079 String getCodePath() {
5080 return codeFileName;
5081 }
5082
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 void createCopyFile() {
5084 boolean fwdLocked = isFwdLocked(flags);
5085 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5086 codeFileName = createTempPackageFile(installDir).getPath();
5087 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005088 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005089 }
5090
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005091 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005092 if (temp) {
5093 // Generate temp file name
5094 createCopyFile();
5095 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 // Get a ParcelFileDescriptor to write to the output file
5097 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005098 if (!created) {
5099 try {
5100 codeFile.createNewFile();
5101 // Set permissions
5102 if (!setPermissions()) {
5103 // Failed setting permissions.
5104 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5105 }
5106 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005107 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005108 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5109 }
5110 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 ParcelFileDescriptor out = null;
5112 try {
5113 out = ParcelFileDescriptor.open(codeFile,
5114 ParcelFileDescriptor.MODE_READ_WRITE);
5115 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005116 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005117 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5118 }
5119 // Copy the resource now
5120 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5121 try {
5122 if (imcs.copyResource(packageURI, out)) {
5123 ret = PackageManager.INSTALL_SUCCEEDED;
5124 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 } finally {
5126 try { if (out != null) out.close(); } catch (IOException e) {}
5127 }
5128 return ret;
5129 }
5130
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005131 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 if (status != PackageManager.INSTALL_SUCCEEDED) {
5133 cleanUp();
5134 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005135 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 }
5137
5138 boolean doRename(int status, final String pkgName, String oldCodePath) {
5139 if (status != PackageManager.INSTALL_SUCCEEDED) {
5140 cleanUp();
5141 return false;
5142 } else {
5143 // Rename based on packageName
5144 File codeFile = new File(getCodePath());
5145 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5146 File desFile = new File(installDir, apkName + ".apk");
5147 if (!codeFile.renameTo(desFile)) {
5148 return false;
5149 }
5150 // Reset paths since the file has been renamed.
5151 codeFileName = desFile.getPath();
5152 resourceFileName = getResourcePathFromCodePath();
5153 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005154 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005155 // Failed setting permissions.
5156 return false;
5157 }
5158 return true;
5159 }
5160 }
5161
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005162 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 if (status != PackageManager.INSTALL_SUCCEEDED) {
5164 cleanUp();
5165 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005166 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 }
5168
5169 String getResourcePath() {
5170 return resourceFileName;
5171 }
5172
5173 String getResourcePathFromCodePath() {
5174 String codePath = getCodePath();
5175 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5176 String apkNameOnly = getApkName(codePath);
5177 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5178 } else {
5179 return codePath;
5180 }
5181 }
5182
5183 private boolean cleanUp() {
5184 boolean ret = true;
5185 String sourceDir = getCodePath();
5186 String publicSourceDir = getResourcePath();
5187 if (sourceDir != null) {
5188 File sourceFile = new File(sourceDir);
5189 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005190 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 ret = false;
5192 }
5193 // Delete application's code and resources
5194 sourceFile.delete();
5195 }
5196 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5197 final File publicSourceFile = new File(publicSourceDir);
5198 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005199 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005200 }
5201 if (publicSourceFile.exists()) {
5202 publicSourceFile.delete();
5203 }
5204 }
5205 return ret;
5206 }
5207
5208 void cleanUpResourcesLI() {
5209 String sourceDir = getCodePath();
5210 if (cleanUp() && mInstaller != null) {
5211 int retCode = mInstaller.rmdex(sourceDir);
5212 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005213 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005214 + " at location "
5215 + sourceDir + ", retcode=" + retCode);
5216 // we don't consider this to be a failure of the core package deletion
5217 }
5218 }
5219 }
5220
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005221 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 // TODO Do this in a more elegant way later on. for now just a hack
5223 if (!isFwdLocked(flags)) {
5224 final int filePermissions =
5225 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5226 |FileUtils.S_IROTH;
5227 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5228 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005229 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 getCodePath()
5231 + ". The return code was: " + retCode);
5232 // TODO Define new internal error
5233 return false;
5234 }
5235 return true;
5236 }
5237 return true;
5238 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005239
5240 boolean doPostDeleteLI(boolean delete) {
5241 cleanUpResourcesLI();
5242 return true;
5243 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 }
5245
5246 class SdInstallArgs extends InstallArgs {
5247 String cid;
5248 String cachePath;
5249 static final String RES_FILE_NAME = "pkg.apk";
5250
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005251 SdInstallArgs(InstallParams params) {
5252 super(params.packageURI, params.observer,
5253 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005254 }
5255
5256 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005257 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005258 // Extract cid from fullCodePath
5259 int eidx = fullCodePath.lastIndexOf("/");
5260 String subStr1 = fullCodePath.substring(0, eidx);
5261 int sidx = subStr1.lastIndexOf("/");
5262 cid = subStr1.substring(sidx+1, eidx);
5263 cachePath = subStr1;
5264 }
5265
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005266 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005267 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5268 this.cid = cid;
5269 }
5270
5271 SdInstallArgs(Uri packageURI, String cid) {
5272 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005273 this.cid = cid;
5274 }
5275
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005276 void createCopyFile() {
5277 cid = getTempContainerId();
5278 }
5279
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005280 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5281 return imcs.checkFreeStorage(true, packageURI);
5282 }
5283
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005284 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005285 if (temp) {
5286 createCopyFile();
5287 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005288 cachePath = imcs.copyResourceToContainer(
5289 packageURI, cid,
5290 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005291 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5292 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 }
5294
5295 @Override
5296 String getCodePath() {
5297 return cachePath + "/" + RES_FILE_NAME;
5298 }
5299
5300 @Override
5301 String getResourcePath() {
5302 return cachePath + "/" + RES_FILE_NAME;
5303 }
5304
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005305 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 if (status != PackageManager.INSTALL_SUCCEEDED) {
5307 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005308 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005310 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005312 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 if (cachePath == null) {
5314 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5315 }
5316 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005317 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005318 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005319 }
5320
5321 boolean doRename(int status, final String pkgName,
5322 String oldCodePath) {
5323 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005324 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005325 if (PackageHelper.isContainerMounted(cid)) {
5326 // Unmount the container
5327 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005328 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005329 return false;
5330 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005331 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005332 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005333 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5334 " which might be stale. Will try to clean up.");
5335 // Clean up the stale container and proceed to recreate.
5336 if (!PackageHelper.destroySdDir(newCacheId)) {
5337 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5338 return false;
5339 }
5340 // Successfully cleaned up stale container. Try to rename again.
5341 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5342 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5343 + " inspite of cleaning it up.");
5344 return false;
5345 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005346 }
5347 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005348 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005349 newCachePath = PackageHelper.mountSdDir(newCacheId,
5350 getEncryptKey(), Process.SYSTEM_UID);
5351 } else {
5352 newCachePath = PackageHelper.getSdDir(newCacheId);
5353 }
5354 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005355 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005356 return false;
5357 }
5358 Log.i(TAG, "Succesfully renamed " + cid +
5359 " at path: " + cachePath + " to " + newCacheId +
5360 " at new path: " + newCachePath);
5361 cid = newCacheId;
5362 cachePath = newCachePath;
5363 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005364 }
5365
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005366 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 if (status != PackageManager.INSTALL_SUCCEEDED) {
5368 cleanUp();
5369 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005370 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005371 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005372 PackageHelper.mountSdDir(cid,
5373 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005374 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005376 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005377 }
5378
5379 private void cleanUp() {
5380 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005381 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005382 }
5383
5384 void cleanUpResourcesLI() {
5385 String sourceFile = getCodePath();
5386 // Remove dex file
5387 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005388 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005389 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005390 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005391 + " at location "
5392 + sourceFile.toString() + ", retcode=" + retCode);
5393 // we don't consider this to be a failure of the core package deletion
5394 }
5395 }
5396 cleanUp();
5397 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005398
5399 boolean matchContainer(String app) {
5400 if (cid.startsWith(app)) {
5401 return true;
5402 }
5403 return false;
5404 }
5405
5406 String getPackageName() {
5407 int idx = cid.lastIndexOf("-");
5408 if (idx == -1) {
5409 return cid;
5410 }
5411 return cid.substring(0, idx);
5412 }
5413
5414 boolean doPostDeleteLI(boolean delete) {
5415 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005416 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 if (mounted) {
5418 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005419 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005420 }
5421 if (ret && delete) {
5422 cleanUpResourcesLI();
5423 }
5424 return ret;
5425 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005426 };
5427
5428 // Utility method used to create code paths based on package name and available index.
5429 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5430 String idxStr = "";
5431 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005432 // Fall back to default value of idx=1 if prefix is not
5433 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005434 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005435 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005436 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005437 if (subStr.endsWith(suffix)) {
5438 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005439 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005440 // If oldCodePath already contains prefix find out the
5441 // ending index to either increment or decrement.
5442 int sidx = subStr.lastIndexOf(prefix);
5443 if (sidx != -1) {
5444 subStr = subStr.substring(sidx + prefix.length());
5445 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005446 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5447 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005448 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005449 try {
5450 idx = Integer.parseInt(subStr);
5451 if (idx <= 1) {
5452 idx++;
5453 } else {
5454 idx--;
5455 }
5456 } catch(NumberFormatException e) {
5457 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005458 }
5459 }
5460 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005461 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005462 return prefix + idxStr;
5463 }
5464
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005465 // Utility method used to ignore ADD/REMOVE events
5466 // by directory observer.
5467 private static boolean ignoreCodePath(String fullPathStr) {
5468 String apkName = getApkName(fullPathStr);
5469 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5470 if (idx != -1 && ((idx+1) < apkName.length())) {
5471 // Make sure the package ends with a numeral
5472 String version = apkName.substring(idx+1);
5473 try {
5474 Integer.parseInt(version);
5475 return true;
5476 } catch (NumberFormatException e) {}
5477 }
5478 return false;
5479 }
5480
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005481 // Utility method that returns the relative package path with respect
5482 // to the installation directory. Like say for /data/data/com.test-1.apk
5483 // string com.test-1 is returned.
5484 static String getApkName(String codePath) {
5485 if (codePath == null) {
5486 return null;
5487 }
5488 int sidx = codePath.lastIndexOf("/");
5489 int eidx = codePath.lastIndexOf(".");
5490 if (eidx == -1) {
5491 eidx = codePath.length();
5492 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005493 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005494 return null;
5495 }
5496 return codePath.substring(sidx+1, eidx);
5497 }
5498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 class PackageInstalledInfo {
5500 String name;
5501 int uid;
5502 PackageParser.Package pkg;
5503 int returnCode;
5504 PackageRemovedInfo removedInfo;
5505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 /*
5508 * Install a non-existing package.
5509 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005510 private void installNewPackageLI(PackageParser.Package pkg,
5511 int parseFlags,
5512 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005513 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005515 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005516
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005517 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 res.name = pkgName;
5519 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005520 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5521 // A package with the same name is already installed, though
5522 // it has been renamed to an older name. The package we
5523 // are trying to install should be installed as an update to
5524 // the existing one, but that has not been requested, so bail.
5525 Slog.w(TAG, "Attempt to re-install " + pkgName
5526 + " without first uninstalling package running as "
5527 + mSettings.mRenamedPackages.get(pkgName));
5528 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5529 return;
5530 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005533 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 + " without first uninstalling.");
5535 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5536 return;
5537 }
5538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005540 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005542 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5544 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5545 }
5546 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005547 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005548 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 res);
5550 // delete the partially installed application. the data directory will have to be
5551 // restored if it was already existing
5552 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5553 // remove package from internal structures. Note that we want deletePackageX to
5554 // delete the package data and cache directories that it created in
5555 // scanPackageLocked, unless those directories existed before we even tried to
5556 // install.
5557 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005558 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5560 res.removedInfo);
5561 }
5562 }
5563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005564
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005565 private void replacePackageLI(PackageParser.Package pkg,
5566 int parseFlags,
5567 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005568 String installerPackageName, PackageInstalledInfo res) {
5569
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005570 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 // First find the old package info and check signatures
5573 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005574 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005575 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005576 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5578 return;
5579 }
5580 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005581 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005582 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005583 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005585 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 }
5587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005590 PackageParser.Package pkg,
5591 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005592 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 PackageParser.Package newPackage = null;
5594 String pkgName = deletedPackage.packageName;
5595 boolean deletedPkg = true;
5596 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005597
Jacek Surazski65e13172009-04-28 15:26:38 +02005598 String oldInstallerPackageName = null;
5599 synchronized (mPackages) {
5600 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005604 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 res.removedInfo)) {
5606 // If the existing package was'nt successfully deleted
5607 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5608 deletedPkg = false;
5609 } else {
5610 // Successfully deleted the old package. Now proceed with re-installation
5611 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005612 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005614 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5616 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005617 }
5618 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005619 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005620 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 res);
5622 updatedSettings = true;
5623 }
5624 }
5625
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005626 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 // remove package from internal structures. Note that we want deletePackageX to
5628 // delete the package data and cache directories that it created in
5629 // scanPackageLocked, unless those directories existed before we even tried to
5630 // install.
5631 if(updatedSettings) {
5632 deletePackageLI(
5633 pkgName, true,
5634 PackageManager.DONT_DELETE_DATA,
5635 res.removedInfo);
5636 }
5637 // Since we failed to install the new package we need to restore the old
5638 // package that we deleted.
5639 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005640 File restoreFile = new File(deletedPackage.mPath);
5641 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005642 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005643 return;
5644 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005645 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005646 boolean oldOnSd = isExternal(deletedPackage);
5647 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5648 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5649 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5650 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5651 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5652 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5653 return;
5654 }
5655 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005656 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005657 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5658 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005659 mSettings.writeLP();
5660 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005661 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 }
5663 }
5664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005667 PackageParser.Package pkg,
5668 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005669 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 PackageParser.Package newPackage = null;
5671 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 PackageParser.PARSE_IS_SYSTEM;
5674 String packageName = deletedPackage.packageName;
5675 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5676 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005677 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 return;
5679 }
5680 PackageParser.Package oldPkg;
5681 PackageSetting oldPkgSetting;
5682 synchronized (mPackages) {
5683 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005684 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5686 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005687 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 return;
5689 }
5690 }
5691 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5692 res.removedInfo.removedPackage = packageName;
5693 // Remove existing system package
5694 removePackageLI(oldPkg, true);
5695 synchronized (mPackages) {
5696 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5697 }
5698
5699 // Successfully disabled the old package. Now proceed with re-installation
5700 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5701 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005702 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005704 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5706 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5707 }
5708 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005709 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 updatedSettings = true;
5711 }
5712
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005713 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 // Re installation failed. Restore old information
5715 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005716 if (newPackage != null) {
5717 removePackageLI(newPackage, true);
5718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005720 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005722 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 // Restore the old system information in Settings
5724 synchronized(mPackages) {
5725 if(updatedSettings) {
5726 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005727 mSettings.setInstallerPackageName(packageName,
5728 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 }
5730 mSettings.writeLP();
5731 }
5732 }
5733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005734
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005735 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005736 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005737 int retCode;
5738 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5739 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5740 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005741 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005742 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5743 }
5744 }
5745 return PackageManager.INSTALL_SUCCEEDED;
5746 }
5747
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005748 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005749 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005750 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 synchronized (mPackages) {
5752 //write settings. the installStatus will be incomplete at this stage.
5753 //note that the new package setting would have already been
5754 //added to mPackages. It hasn't been persisted yet.
5755 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5756 mSettings.writeLP();
5757 }
5758
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005759 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005760 != PackageManager.INSTALL_SUCCEEDED) {
5761 // Discontinue if moving dex files failed.
5762 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005764 if((res.returnCode = setPermissionsLI(newPackage))
5765 != PackageManager.INSTALL_SUCCEEDED) {
5766 if (mInstaller != null) {
5767 mInstaller.rmdex(newPackage.mScanPath);
5768 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005769 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005771 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005774 updatePermissionsLP(newPackage.packageName, newPackage,
5775 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 res.name = pkgName;
5777 res.uid = newPackage.applicationInfo.uid;
5778 res.pkg = newPackage;
5779 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005780 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5782 //to update install status
5783 mSettings.writeLP();
5784 }
5785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005786
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005787 private void installPackageLI(InstallArgs args,
5788 boolean newInstall, PackageInstalledInfo res) {
5789 int pFlags = args.flags;
5790 String installerPackageName = args.installerPackageName;
5791 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005792 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005793 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005794 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005795 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005796 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005797 // Result object to be returned
5798 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5799
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005800 // Retrieve PackageSettings and parse package
5801 int parseFlags = PackageParser.PARSE_CHATTY |
5802 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5803 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5804 parseFlags |= mDefParseFlags;
5805 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5806 pp.setSeparateProcesses(mSeparateProcesses);
5807 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5808 null, mMetrics, parseFlags);
5809 if (pkg == null) {
5810 res.returnCode = pp.getParseError();
5811 return;
5812 }
5813 String pkgName = res.name = pkg.packageName;
5814 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5815 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5816 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5817 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005819 }
5820 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5821 res.returnCode = pp.getParseError();
5822 return;
5823 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005824 // Get rid of all references to package scan path via parser.
5825 pp = null;
5826 String oldCodePath = null;
5827 boolean systemApp = false;
5828 synchronized (mPackages) {
5829 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005830 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5831 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005832 if (pkg.mOriginalPackages != null
5833 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005834 && mPackages.containsKey(oldName)) {
5835 // This package is derived from an original package,
5836 // and this device has been updating from that original
5837 // name. We must continue using the original name, so
5838 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005839 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005840 pkgName = pkg.packageName;
5841 replace = true;
5842 } else if (mPackages.containsKey(pkgName)) {
5843 // This package, under its official name, already exists
5844 // on the device; we should replace it.
5845 replace = true;
5846 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005847 }
5848 PackageSetting ps = mSettings.mPackages.get(pkgName);
5849 if (ps != null) {
5850 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5851 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5852 systemApp = (ps.pkg.applicationInfo.flags &
5853 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005854 }
5855 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005857
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005858 if (systemApp && onSd) {
5859 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005860 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005861 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5862 return;
5863 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005864
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005865 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5866 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5867 return;
5868 }
5869 // Set application objects path explicitly after the rename
5870 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005871 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005872 replacePackageLI(pkg, parseFlags, scanMode,
5873 installerPackageName, res);
5874 } else {
5875 installNewPackageLI(pkg, parseFlags, scanMode,
5876 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
5878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005879
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005880 private int setPermissionsLI(PackageParser.Package newPackage) {
5881 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005882 int retCode = 0;
5883 // TODO Gross hack but fix later. Ideally move this to be a post installation
5884 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005885 if ((newPackage.applicationInfo.flags
5886 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5887 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 try {
5889 extractPublicFiles(newPackage, destResourceFile);
5890 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005891 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 -08005892 " forward-locked app.");
5893 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5894 } finally {
5895 //TODO clean up the extracted public files
5896 }
5897 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005898 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005899 newPackage.applicationInfo.uid);
5900 } else {
5901 final int filePermissions =
5902 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005903 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 newPackage.applicationInfo.uid);
5905 }
5906 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005907 // The permissions on the resource file was set when it was copied for
5908 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005912 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005913 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005915 // TODO Define new internal error
5916 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 }
5918 return PackageManager.INSTALL_SUCCEEDED;
5919 }
5920
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005921 private boolean isForwardLocked(PackageParser.Package pkg) {
5922 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 }
5924
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005925 private boolean isExternal(PackageParser.Package pkg) {
5926 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5927 }
5928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 private void extractPublicFiles(PackageParser.Package newPackage,
5930 File publicZipFile) throws IOException {
5931 final ZipOutputStream publicZipOutStream =
5932 new ZipOutputStream(new FileOutputStream(publicZipFile));
5933 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5934
5935 // Copy manifest, resources.arsc and res directory to public zip
5936
5937 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5938 while (privateZipEntries.hasMoreElements()) {
5939 final ZipEntry zipEntry = privateZipEntries.nextElement();
5940 final String zipEntryName = zipEntry.getName();
5941 if ("AndroidManifest.xml".equals(zipEntryName)
5942 || "resources.arsc".equals(zipEntryName)
5943 || zipEntryName.startsWith("res/")) {
5944 try {
5945 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5946 } catch (IOException e) {
5947 try {
5948 publicZipOutStream.close();
5949 throw e;
5950 } finally {
5951 publicZipFile.delete();
5952 }
5953 }
5954 }
5955 }
5956
5957 publicZipOutStream.close();
5958 FileUtils.setPermissions(
5959 publicZipFile.getAbsolutePath(),
5960 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5961 -1, -1);
5962 }
5963
5964 private static void copyZipEntry(ZipEntry zipEntry,
5965 ZipFile inZipFile,
5966 ZipOutputStream outZipStream) throws IOException {
5967 byte[] buffer = new byte[4096];
5968 int num;
5969
5970 ZipEntry newEntry;
5971 if (zipEntry.getMethod() == ZipEntry.STORED) {
5972 // Preserve the STORED method of the input entry.
5973 newEntry = new ZipEntry(zipEntry);
5974 } else {
5975 // Create a new entry so that the compressed len is recomputed.
5976 newEntry = new ZipEntry(zipEntry.getName());
5977 }
5978 outZipStream.putNextEntry(newEntry);
5979
5980 InputStream data = inZipFile.getInputStream(zipEntry);
5981 while ((num = data.read(buffer)) > 0) {
5982 outZipStream.write(buffer, 0, num);
5983 }
5984 outZipStream.flush();
5985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 private void deleteTempPackageFiles() {
5988 FilenameFilter filter = new FilenameFilter() {
5989 public boolean accept(File dir, String name) {
5990 return name.startsWith("vmdl") && name.endsWith(".tmp");
5991 }
5992 };
5993 String tmpFilesList[] = mAppInstallDir.list(filter);
5994 if(tmpFilesList == null) {
5995 return;
5996 }
5997 for(int i = 0; i < tmpFilesList.length; i++) {
5998 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5999 tmpFile.delete();
6000 }
6001 }
6002
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006003 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 File tmpPackageFile;
6005 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006006 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006008 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 return null;
6010 }
6011 try {
6012 FileUtils.setPermissions(
6013 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6014 -1, -1);
6015 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006016 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 return null;
6018 }
6019 return tmpPackageFile;
6020 }
6021
6022 public void deletePackage(final String packageName,
6023 final IPackageDeleteObserver observer,
6024 final int flags) {
6025 mContext.enforceCallingOrSelfPermission(
6026 android.Manifest.permission.DELETE_PACKAGES, null);
6027 // Queue up an async operation since the package deletion may take a little while.
6028 mHandler.post(new Runnable() {
6029 public void run() {
6030 mHandler.removeCallbacks(this);
6031 final boolean succeded = deletePackageX(packageName, true, true, flags);
6032 if (observer != null) {
6033 try {
6034 observer.packageDeleted(succeded);
6035 } catch (RemoteException e) {
6036 Log.i(TAG, "Observer no longer exists.");
6037 } //end catch
6038 } //end if
6039 } //end run
6040 });
6041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 /**
6044 * This method is an internal method that could be get invoked either
6045 * to delete an installed package or to clean up a failed installation.
6046 * After deleting an installed package, a broadcast is sent to notify any
6047 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006048 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 * installation wouldn't have sent the initial broadcast either
6050 * The key steps in deleting a package are
6051 * deleting the package information in internal structures like mPackages,
6052 * deleting the packages base directories through installd
6053 * updating mSettings to reflect current status
6054 * persisting settings for later use
6055 * sending a broadcast if necessary
6056 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6058 boolean deleteCodeAndResources, int flags) {
6059 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006060 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006062 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6063 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6064 try {
6065 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006066 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006067 return false;
6068 }
6069 } catch (RemoteException e) {
6070 }
6071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006073 res = deletePackageLI(packageName, deleteCodeAndResources,
6074 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006078 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6079 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6080
6081 // If the removed package was a system update, the old system packaged
6082 // was re-enabled; we need to broadcast this information
6083 if (systemUpdate) {
6084 Bundle extras = new Bundle(1);
6085 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6086 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6087
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006088 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6089 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006092 // Force a gc here.
6093 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006094 // Delete the resources here after sending the broadcast to let
6095 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006096 if (info.args != null) {
6097 synchronized (mInstallLock) {
6098 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006099 }
6100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 return res;
6102 }
6103
6104 static class PackageRemovedInfo {
6105 String removedPackage;
6106 int uid = -1;
6107 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006108 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006109 // Clean up resources deleted packages.
6110 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 void sendBroadcast(boolean fullRemove, boolean replacing) {
6113 Bundle extras = new Bundle(1);
6114 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6115 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6116 if (replacing) {
6117 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6118 }
6119 if (removedPackage != null) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006120 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006123 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 }
6125 }
6126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 /*
6129 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6130 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006131 * 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 -08006132 * delete a partially installed application.
6133 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006134 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 int flags) {
6136 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006137 if (outInfo != null) {
6138 outInfo.removedPackage = packageName;
6139 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006140 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 // Retrieve object to delete permissions for shared user later on
6142 PackageSetting deletedPs;
6143 synchronized (mPackages) {
6144 deletedPs = mSettings.mPackages.get(packageName);
6145 }
6146 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6147 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006148 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006150 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 + packageName + ", retcode=" + retCode);
6152 // we don't consider this to be a failure of the core package deletion
6153 }
6154 } else {
6155 //for emulator
6156 PackageParser.Package pkg = mPackages.get(packageName);
6157 File dataDir = new File(pkg.applicationInfo.dataDir);
6158 dataDir.delete();
6159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 }
6161 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006162 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006163 schedulePackageCleaning(packageName);
6164
6165 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6166 if (outInfo != null) {
6167 outInfo.removedUid = mSettings.removePackageLP(packageName);
6168 }
6169 if (deletedPs != null) {
6170 updatePermissionsLP(deletedPs.name, null, false, false);
6171 if (deletedPs.sharedUser != null) {
6172 // remove permissions associated with package
6173 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6174 }
6175 }
6176 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006177 // remove from preferred activities.
6178 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6179 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6180 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6181 removed.add(pa);
6182 }
6183 }
6184 for (PreferredActivity pa : removed) {
6185 mSettings.mPreferredActivities.removeFilter(pa);
6186 }
6187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006189 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 }
6191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 /*
6194 * Tries to delete system package.
6195 */
6196 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006197 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 ApplicationInfo applicationInfo = p.applicationInfo;
6199 //applicable for non-partially installed applications only
6200 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006201 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 return false;
6203 }
6204 PackageSetting ps = null;
6205 // Confirm if the system package has been updated
6206 // An updated system app can be deleted. This will also have to restore
6207 // the system pkg from system partition
6208 synchronized (mPackages) {
6209 ps = mSettings.getDisabledSystemPkg(p.packageName);
6210 }
6211 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006212 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 return false;
6214 } else {
6215 Log.i(TAG, "Deleting system pkg from data partition");
6216 }
6217 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006218 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006219 boolean deleteCodeAndResources = false;
6220 if (ps.versionCode < p.mVersionCode) {
6221 // Delete code and resources for downgrades
6222 deleteCodeAndResources = true;
6223 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6224 flags &= ~PackageManager.DONT_DELETE_DATA;
6225 }
6226 } else {
6227 // Preserve data by setting flag
6228 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6229 flags |= PackageManager.DONT_DELETE_DATA;
6230 }
6231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6233 if (!ret) {
6234 return false;
6235 }
6236 synchronized (mPackages) {
6237 // Reinstate the old system package
6238 mSettings.enableSystemPackageLP(p.packageName);
6239 }
6240 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006241 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006243 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006246 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 return false;
6248 }
6249 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006250 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 mSettings.writeLP();
6252 }
6253 return true;
6254 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6257 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6258 ApplicationInfo applicationInfo = p.applicationInfo;
6259 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006260 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 return false;
6262 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006263 if (outInfo != null) {
6264 outInfo.uid = applicationInfo.uid;
6265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266
6267 // Delete package data from internal structures and also remove data if flag is set
6268 removePackageDataLI(p, outInfo, flags);
6269
6270 // Delete application code and resources
6271 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006272 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006273 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006274 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006275 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6276 PackageManager.INSTALL_FORWARD_LOCK : 0;
6277 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006278 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 }
6280 return true;
6281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 /*
6284 * This method handles package deletion in general
6285 */
6286 private boolean deletePackageLI(String packageName,
6287 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6288 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006289 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 return false;
6291 }
6292 PackageParser.Package p;
6293 boolean dataOnly = false;
6294 synchronized (mPackages) {
6295 p = mPackages.get(packageName);
6296 if (p == null) {
6297 //this retrieves partially installed apps
6298 dataOnly = true;
6299 PackageSetting ps = mSettings.mPackages.get(packageName);
6300 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006301 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 return false;
6303 }
6304 p = ps.pkg;
6305 }
6306 }
6307 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006308 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006309 return false;
6310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 if (dataOnly) {
6313 // Delete application data first
6314 removePackageDataLI(p, outInfo, flags);
6315 return true;
6316 }
6317 // At this point the package should have ApplicationInfo associated with it
6318 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006319 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 return false;
6321 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006322 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6324 Log.i(TAG, "Removing system package:"+p.packageName);
6325 // When an updated system application is deleted we delete the existing resources as well and
6326 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006327 ret = deleteSystemPackageLI(p, flags, outInfo);
6328 } else {
6329 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006330 // Kill application pre-emptively especially for apps on sd.
6331 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006332 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006334 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 public void clearApplicationUserData(final String packageName,
6338 final IPackageDataObserver observer) {
6339 mContext.enforceCallingOrSelfPermission(
6340 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6341 // Queue up an async operation since the package deletion may take a little while.
6342 mHandler.post(new Runnable() {
6343 public void run() {
6344 mHandler.removeCallbacks(this);
6345 final boolean succeeded;
6346 synchronized (mInstallLock) {
6347 succeeded = clearApplicationUserDataLI(packageName);
6348 }
6349 if (succeeded) {
6350 // invoke DeviceStorageMonitor's update method to clear any notifications
6351 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6352 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6353 if (dsm != null) {
6354 dsm.updateMemory();
6355 }
6356 }
6357 if(observer != null) {
6358 try {
6359 observer.onRemoveCompleted(packageName, succeeded);
6360 } catch (RemoteException e) {
6361 Log.i(TAG, "Observer no longer exists.");
6362 }
6363 } //end if observer
6364 } //end run
6365 });
6366 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 private boolean clearApplicationUserDataLI(String packageName) {
6369 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006370 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 return false;
6372 }
6373 PackageParser.Package p;
6374 boolean dataOnly = false;
6375 synchronized (mPackages) {
6376 p = mPackages.get(packageName);
6377 if(p == null) {
6378 dataOnly = true;
6379 PackageSetting ps = mSettings.mPackages.get(packageName);
6380 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006381 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 return false;
6383 }
6384 p = ps.pkg;
6385 }
6386 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 if(!dataOnly) {
6389 //need to check this only for fully installed applications
6390 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006391 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 return false;
6393 }
6394 final ApplicationInfo applicationInfo = p.applicationInfo;
6395 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006396 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 return false;
6398 }
6399 }
6400 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006401 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006403 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 + packageName);
6405 return false;
6406 }
6407 }
6408 return true;
6409 }
6410
6411 public void deleteApplicationCacheFiles(final String packageName,
6412 final IPackageDataObserver observer) {
6413 mContext.enforceCallingOrSelfPermission(
6414 android.Manifest.permission.DELETE_CACHE_FILES, null);
6415 // Queue up an async operation since the package deletion may take a little while.
6416 mHandler.post(new Runnable() {
6417 public void run() {
6418 mHandler.removeCallbacks(this);
6419 final boolean succeded;
6420 synchronized (mInstallLock) {
6421 succeded = deleteApplicationCacheFilesLI(packageName);
6422 }
6423 if(observer != null) {
6424 try {
6425 observer.onRemoveCompleted(packageName, succeded);
6426 } catch (RemoteException e) {
6427 Log.i(TAG, "Observer no longer exists.");
6428 }
6429 } //end if observer
6430 } //end run
6431 });
6432 }
6433
6434 private boolean deleteApplicationCacheFilesLI(String packageName) {
6435 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006436 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437 return false;
6438 }
6439 PackageParser.Package p;
6440 synchronized (mPackages) {
6441 p = mPackages.get(packageName);
6442 }
6443 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006444 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 return false;
6446 }
6447 final ApplicationInfo applicationInfo = p.applicationInfo;
6448 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006449 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 return false;
6451 }
6452 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006453 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006455 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 + packageName);
6457 return false;
6458 }
6459 }
6460 return true;
6461 }
6462
6463 public void getPackageSizeInfo(final String packageName,
6464 final IPackageStatsObserver observer) {
6465 mContext.enforceCallingOrSelfPermission(
6466 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6467 // Queue up an async operation since the package deletion may take a little while.
6468 mHandler.post(new Runnable() {
6469 public void run() {
6470 mHandler.removeCallbacks(this);
6471 PackageStats lStats = new PackageStats(packageName);
6472 final boolean succeded;
6473 synchronized (mInstallLock) {
6474 succeded = getPackageSizeInfoLI(packageName, lStats);
6475 }
6476 if(observer != null) {
6477 try {
6478 observer.onGetStatsCompleted(lStats, succeded);
6479 } catch (RemoteException e) {
6480 Log.i(TAG, "Observer no longer exists.");
6481 }
6482 } //end if observer
6483 } //end run
6484 });
6485 }
6486
6487 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6488 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 return false;
6491 }
6492 PackageParser.Package p;
6493 boolean dataOnly = false;
6494 synchronized (mPackages) {
6495 p = mPackages.get(packageName);
6496 if(p == null) {
6497 dataOnly = true;
6498 PackageSetting ps = mSettings.mPackages.get(packageName);
6499 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006500 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 return false;
6502 }
6503 p = ps.pkg;
6504 }
6505 }
6506 String publicSrcDir = null;
6507 if(!dataOnly) {
6508 final ApplicationInfo applicationInfo = p.applicationInfo;
6509 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006510 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 return false;
6512 }
6513 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6514 }
6515 if (mInstaller != null) {
6516 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006517 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 if (res < 0) {
6519 return false;
6520 } else {
6521 return true;
6522 }
6523 }
6524 return true;
6525 }
6526
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 public void addPackageToPreferred(String packageName) {
6529 mContext.enforceCallingOrSelfPermission(
6530 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006531 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
6533
6534 public void removePackageFromPreferred(String packageName) {
6535 mContext.enforceCallingOrSelfPermission(
6536 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006537 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 }
6539
6540 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006541 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 }
6543
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006544 int getUidTargetSdkVersionLockedLP(int uid) {
6545 Object obj = mSettings.getUserIdLP(uid);
6546 if (obj instanceof SharedUserSetting) {
6547 SharedUserSetting sus = (SharedUserSetting)obj;
6548 final int N = sus.packages.size();
6549 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6550 Iterator<PackageSetting> it = sus.packages.iterator();
6551 int i=0;
6552 while (it.hasNext()) {
6553 PackageSetting ps = it.next();
6554 if (ps.pkg != null) {
6555 int v = ps.pkg.applicationInfo.targetSdkVersion;
6556 if (v < vers) vers = v;
6557 }
6558 }
6559 return vers;
6560 } else if (obj instanceof PackageSetting) {
6561 PackageSetting ps = (PackageSetting)obj;
6562 if (ps.pkg != null) {
6563 return ps.pkg.applicationInfo.targetSdkVersion;
6564 }
6565 }
6566 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6567 }
6568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 public void addPreferredActivity(IntentFilter filter, int match,
6570 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006572 if (mContext.checkCallingOrSelfPermission(
6573 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6574 != PackageManager.PERMISSION_GRANTED) {
6575 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6576 < Build.VERSION_CODES.FROYO) {
6577 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6578 + Binder.getCallingUid());
6579 return;
6580 }
6581 mContext.enforceCallingOrSelfPermission(
6582 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6583 }
6584
6585 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6587 mSettings.mPreferredActivities.addFilter(
6588 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006589 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 }
6591 }
6592
Satish Sampath8dbe6122009-06-02 23:35:54 +01006593 public void replacePreferredActivity(IntentFilter filter, int match,
6594 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006595 if (filter.countActions() != 1) {
6596 throw new IllegalArgumentException(
6597 "replacePreferredActivity expects filter to have only 1 action.");
6598 }
6599 if (filter.countCategories() != 1) {
6600 throw new IllegalArgumentException(
6601 "replacePreferredActivity expects filter to have only 1 category.");
6602 }
6603 if (filter.countDataAuthorities() != 0
6604 || filter.countDataPaths() != 0
6605 || filter.countDataSchemes() != 0
6606 || filter.countDataTypes() != 0) {
6607 throw new IllegalArgumentException(
6608 "replacePreferredActivity expects filter to have no data authorities, " +
6609 "paths, schemes or types.");
6610 }
6611 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006612 if (mContext.checkCallingOrSelfPermission(
6613 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6614 != PackageManager.PERMISSION_GRANTED) {
6615 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6616 < Build.VERSION_CODES.FROYO) {
6617 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6618 + Binder.getCallingUid());
6619 return;
6620 }
6621 mContext.enforceCallingOrSelfPermission(
6622 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6623 }
6624
Satish Sampath8dbe6122009-06-02 23:35:54 +01006625 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6626 String action = filter.getAction(0);
6627 String category = filter.getCategory(0);
6628 while (it.hasNext()) {
6629 PreferredActivity pa = it.next();
6630 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6631 it.remove();
6632 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6633 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6634 }
6635 }
6636 addPreferredActivity(filter, match, set, activity);
6637 }
6638 }
6639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006642 int uid = Binder.getCallingUid();
6643 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006644 if (pkg == null || pkg.applicationInfo.uid != uid) {
6645 if (mContext.checkCallingOrSelfPermission(
6646 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6647 != PackageManager.PERMISSION_GRANTED) {
6648 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6649 < Build.VERSION_CODES.FROYO) {
6650 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6651 + Binder.getCallingUid());
6652 return;
6653 }
6654 mContext.enforceCallingOrSelfPermission(
6655 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6656 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006657 }
6658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006660 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
6662 }
6663 }
6664
6665 boolean clearPackagePreferredActivitiesLP(String packageName) {
6666 boolean changed = false;
6667 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6668 while (it.hasNext()) {
6669 PreferredActivity pa = it.next();
6670 if (pa.mActivity.getPackageName().equals(packageName)) {
6671 it.remove();
6672 changed = true;
6673 }
6674 }
6675 return changed;
6676 }
6677
6678 public int getPreferredActivities(List<IntentFilter> outFilters,
6679 List<ComponentName> outActivities, String packageName) {
6680
6681 int num = 0;
6682 synchronized (mPackages) {
6683 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6684 while (it.hasNext()) {
6685 PreferredActivity pa = it.next();
6686 if (packageName == null
6687 || pa.mActivity.getPackageName().equals(packageName)) {
6688 if (outFilters != null) {
6689 outFilters.add(new IntentFilter(pa));
6690 }
6691 if (outActivities != null) {
6692 outActivities.add(pa.mActivity);
6693 }
6694 }
6695 }
6696 }
6697
6698 return num;
6699 }
6700
6701 public void setApplicationEnabledSetting(String appPackageName,
6702 int newState, int flags) {
6703 setEnabledSetting(appPackageName, null, newState, flags);
6704 }
6705
6706 public void setComponentEnabledSetting(ComponentName componentName,
6707 int newState, int flags) {
6708 setEnabledSetting(componentName.getPackageName(),
6709 componentName.getClassName(), newState, flags);
6710 }
6711
6712 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006713 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6715 || newState == COMPONENT_ENABLED_STATE_ENABLED
6716 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6717 throw new IllegalArgumentException("Invalid new component state: "
6718 + newState);
6719 }
6720 PackageSetting pkgSetting;
6721 final int uid = Binder.getCallingUid();
6722 final int permission = mContext.checkCallingPermission(
6723 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6724 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006725 boolean sendNow = false;
6726 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006727 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006729 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006731 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006733 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006735 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 }
6737 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006738 "Unknown component: " + packageName
6739 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 }
6741 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6742 throw new SecurityException(
6743 "Permission Denial: attempt to change component state from pid="
6744 + Binder.getCallingPid()
6745 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6746 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006747 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006749 if (pkgSetting.enabled == newState) {
6750 // Nothing to do
6751 return;
6752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 pkgSetting.enabled = newState;
6754 } else {
6755 // We're dealing with a component level state change
6756 switch (newState) {
6757 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006758 if (!pkgSetting.enableComponentLP(className)) {
6759 return;
6760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 break;
6762 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006763 if (!pkgSetting.disableComponentLP(className)) {
6764 return;
6765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 break;
6767 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006768 if (!pkgSetting.restoreComponentLP(className)) {
6769 return;
6770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006771 break;
6772 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006773 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006774 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 }
6776 }
6777 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006778 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006779 components = mPendingBroadcasts.get(packageName);
6780 boolean newPackage = components == null;
6781 if (newPackage) {
6782 components = new ArrayList<String>();
6783 }
6784 if (!components.contains(componentName)) {
6785 components.add(componentName);
6786 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006787 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6788 sendNow = true;
6789 // Purge entry from pending broadcast list if another one exists already
6790 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006791 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006792 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006793 if (newPackage) {
6794 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006795 }
6796 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6797 // Schedule a message
6798 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6799 }
6800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 long callingId = Binder.clearCallingIdentity();
6804 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006805 if (sendNow) {
6806 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006807 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 } finally {
6810 Binder.restoreCallingIdentity(callingId);
6811 }
6812 }
6813
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006814 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006815 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6816 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6817 + " components=" + componentNames);
6818 Bundle extras = new Bundle(4);
6819 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6820 String nameList[] = new String[componentNames.size()];
6821 componentNames.toArray(nameList);
6822 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006823 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6824 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006825 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006826 }
6827
Jacek Surazski65e13172009-04-28 15:26:38 +02006828 public String getInstallerPackageName(String packageName) {
6829 synchronized (mPackages) {
6830 PackageSetting pkg = mSettings.mPackages.get(packageName);
6831 if (pkg == null) {
6832 throw new IllegalArgumentException("Unknown package: " + packageName);
6833 }
6834 return pkg.installerPackageName;
6835 }
6836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 public int getApplicationEnabledSetting(String appPackageName) {
6839 synchronized (mPackages) {
6840 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6841 if (pkg == null) {
6842 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6843 }
6844 return pkg.enabled;
6845 }
6846 }
6847
6848 public int getComponentEnabledSetting(ComponentName componentName) {
6849 synchronized (mPackages) {
6850 final String packageNameStr = componentName.getPackageName();
6851 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6852 if (pkg == null) {
6853 throw new IllegalArgumentException("Unknown component: " + componentName);
6854 }
6855 final String classNameStr = componentName.getClassName();
6856 return pkg.currentEnabledStateLP(classNameStr);
6857 }
6858 }
6859
6860 public void enterSafeMode() {
6861 if (!mSystemReady) {
6862 mSafeMode = true;
6863 }
6864 }
6865
6866 public void systemReady() {
6867 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006868
6869 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006870 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006871 mContext.getContentResolver(),
6872 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006873 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006874 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006875 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877 }
6878
6879 public boolean isSafeMode() {
6880 return mSafeMode;
6881 }
6882
6883 public boolean hasSystemUidErrors() {
6884 return mHasSystemUidErrors;
6885 }
6886
6887 static String arrayToString(int[] array) {
6888 StringBuffer buf = new StringBuffer(128);
6889 buf.append('[');
6890 if (array != null) {
6891 for (int i=0; i<array.length; i++) {
6892 if (i > 0) buf.append(", ");
6893 buf.append(array[i]);
6894 }
6895 }
6896 buf.append(']');
6897 return buf.toString();
6898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 @Override
6901 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6902 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6903 != PackageManager.PERMISSION_GRANTED) {
6904 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6905 + Binder.getCallingPid()
6906 + ", uid=" + Binder.getCallingUid()
6907 + " without permission "
6908 + android.Manifest.permission.DUMP);
6909 return;
6910 }
6911
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006912 String packageName = null;
6913
6914 int opti = 0;
6915 while (opti < args.length) {
6916 String opt = args[opti];
6917 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6918 break;
6919 }
6920 opti++;
6921 if ("-a".equals(opt)) {
6922 // Right now we only know how to print all.
6923 } else if ("-h".equals(opt)) {
6924 pw.println("Package manager dump options:");
6925 pw.println(" [-h] [cmd] ...");
6926 pw.println(" cmd may be one of:");
6927 pw.println(" [package.name]: info about given package");
6928 return;
6929 } else {
6930 pw.println("Unknown argument: " + opt + "; use -h for help");
6931 }
6932 }
6933
6934 // Is the caller requesting to dump a particular piece of data?
6935 if (opti < args.length) {
6936 String cmd = args[opti];
6937 opti++;
6938 // Is this a package name?
6939 if ("android".equals(cmd) || cmd.contains(".")) {
6940 packageName = cmd;
6941 }
6942 }
6943
6944 boolean printedTitle = false;
6945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006947 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6948 printedTitle = true;
6949 }
6950 if (mReceivers.dump(pw, printedTitle
6951 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6952 " ", packageName)) {
6953 printedTitle = true;
6954 }
6955 if (mServices.dump(pw, printedTitle
6956 ? "\nService Resolver Table:" : "Service Resolver Table:",
6957 " ", packageName)) {
6958 printedTitle = true;
6959 }
6960 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6961 ? "\nPreferred Activities:" : "Preferred Activities:",
6962 " ", packageName)) {
6963 printedTitle = true;
6964 }
6965 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 {
6967 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006968 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6969 continue;
6970 }
6971 if (!printedSomething) {
6972 if (printedTitle) pw.println(" ");
6973 pw.println("Permissions:");
6974 printedSomething = true;
6975 printedTitle = true;
6976 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006977 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6978 pw.print(Integer.toHexString(System.identityHashCode(p)));
6979 pw.println("):");
6980 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6981 pw.print(" uid="); pw.print(p.uid);
6982 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006983 pw.print(" type="); pw.print(p.type);
6984 pw.print(" prot="); pw.println(p.protectionLevel);
6985 if (p.packageSetting != null) {
6986 pw.print(" packageSetting="); pw.println(p.packageSetting);
6987 }
6988 if (p.perm != null) {
6989 pw.print(" perm="); pw.println(p.perm);
6990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 }
6992 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006993 printedSomething = false;
6994 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 {
6996 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006997 if (packageName != null && !packageName.equals(ps.realName)
6998 && !packageName.equals(ps.name)) {
6999 continue;
7000 }
7001 if (!printedSomething) {
7002 if (printedTitle) pw.println(" ");
7003 pw.println("Packages:");
7004 printedSomething = true;
7005 printedTitle = true;
7006 }
7007 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007008 pw.print(" Package [");
7009 pw.print(ps.realName != null ? ps.realName : ps.name);
7010 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007011 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7012 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007013 if (ps.realName != null) {
7014 pw.print(" compat name="); pw.println(ps.name);
7015 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007016 pw.print(" userId="); pw.print(ps.userId);
7017 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7018 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7019 pw.print(" pkg="); pw.println(ps.pkg);
7020 pw.print(" codePath="); pw.println(ps.codePathString);
7021 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007023 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007024 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007025 pw.print(" supportsScreens=[");
7026 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007027 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007028 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007029 if (!first) pw.print(", ");
7030 first = false;
7031 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007032 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007033 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007034 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007035 if (!first) pw.print(", ");
7036 first = false;
7037 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007038 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007039 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007040 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007041 if (!first) pw.print(", ");
7042 first = false;
7043 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007045 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007046 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007047 if (!first) pw.print(", ");
7048 first = false;
7049 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007050 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007051 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007052 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7053 if (!first) pw.print(", ");
7054 first = false;
7055 pw.print("anyDensity");
7056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007057 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007058 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007059 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7060 pw.print(" signatures="); pw.println(ps.signatures);
7061 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007062 pw.print(" haveGids="); pw.println(ps.haveGids);
7063 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007064 pw.print(" installStatus="); pw.print(ps.installStatus);
7065 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 if (ps.disabledComponents.size() > 0) {
7067 pw.println(" disabledComponents:");
7068 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007069 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007070 }
7071 }
7072 if (ps.enabledComponents.size() > 0) {
7073 pw.println(" enabledComponents:");
7074 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007075 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 }
7077 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007078 if (ps.grantedPermissions.size() > 0) {
7079 pw.println(" grantedPermissions:");
7080 for (String s : ps.grantedPermissions) {
7081 pw.print(" "); pw.println(s);
7082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007084 }
7085 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007086 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007087 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007088 for (HashMap.Entry<String, String> e
7089 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007090 if (packageName != null && !packageName.equals(e.getKey())
7091 && !packageName.equals(e.getValue())) {
7092 continue;
7093 }
7094 if (!printedSomething) {
7095 if (printedTitle) pw.println(" ");
7096 pw.println("Renamed packages:");
7097 printedSomething = true;
7098 printedTitle = true;
7099 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007100 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7101 pw.println(e.getValue());
7102 }
7103 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007104 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007105 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007106 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007107 if (packageName != null && !packageName.equals(ps.realName)
7108 && !packageName.equals(ps.name)) {
7109 continue;
7110 }
7111 if (!printedSomething) {
7112 if (printedTitle) pw.println(" ");
7113 pw.println("Hidden system packages:");
7114 printedSomething = true;
7115 printedTitle = true;
7116 }
7117 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007118 pw.print(ps.realName != null ? ps.realName : ps.name);
7119 pw.print("] (");
7120 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7121 pw.println("):");
7122 if (ps.realName != null) {
7123 pw.print(" compat name="); pw.println(ps.name);
7124 }
7125 pw.print(" userId="); pw.println(ps.userId);
7126 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7127 pw.print(" codePath="); pw.println(ps.codePathString);
7128 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7129 }
7130 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007131 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 {
7133 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007134 if (packageName != null && su != packageSharedUser) {
7135 continue;
7136 }
7137 if (!printedSomething) {
7138 if (printedTitle) pw.println(" ");
7139 pw.println("Shared users:");
7140 printedSomething = true;
7141 printedTitle = true;
7142 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007143 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7144 pw.print(Integer.toHexString(System.identityHashCode(su)));
7145 pw.println("):");
7146 pw.print(" userId="); pw.print(su.userId);
7147 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 pw.println(" grantedPermissions:");
7149 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007150 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 }
7153 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007154
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007155 if (packageName == null) {
7156 if (printedTitle) pw.println(" ");
7157 printedTitle = true;
7158 pw.println("Settings parse messages:");
7159 pw.println(mSettings.mReadMessages.toString());
7160
7161 pw.println(" ");
7162 pw.println("Package warning messages:");
7163 File fname = getSettingsProblemFile();
7164 FileInputStream in;
7165 try {
7166 in = new FileInputStream(fname);
7167 int avail = in.available();
7168 byte[] data = new byte[avail];
7169 in.read(data);
7170 pw.println(new String(data));
7171 } catch (FileNotFoundException e) {
7172 } catch (IOException e) {
7173 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007176
7177 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007178 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007179 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007180 if (packageName != null && !packageName.equals(p.info.packageName)) {
7181 continue;
7182 }
7183 if (!printedSomething) {
7184 if (printedTitle) pw.println(" ");
7185 pw.println("Registered ContentProviders:");
7186 printedSomething = true;
7187 printedTitle = true;
7188 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007189 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007190 pw.println(p.toString());
7191 }
7192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 }
7194
7195 static final class BasePermission {
7196 final static int TYPE_NORMAL = 0;
7197 final static int TYPE_BUILTIN = 1;
7198 final static int TYPE_DYNAMIC = 2;
7199
7200 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007201 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007202 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007204 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 PackageParser.Permission perm;
7206 PermissionInfo pendingInfo;
7207 int uid;
7208 int[] gids;
7209
7210 BasePermission(String _name, String _sourcePackage, int _type) {
7211 name = _name;
7212 sourcePackage = _sourcePackage;
7213 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007214 // Default to most conservative protection level.
7215 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7216 }
7217
7218 public String toString() {
7219 return "BasePermission{"
7220 + Integer.toHexString(System.identityHashCode(this))
7221 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 }
7223 }
7224
7225 static class PackageSignatures {
7226 private Signature[] mSignatures;
7227
7228 PackageSignatures(Signature[] sigs) {
7229 assignSignatures(sigs);
7230 }
7231
7232 PackageSignatures() {
7233 }
7234
7235 void writeXml(XmlSerializer serializer, String tagName,
7236 ArrayList<Signature> pastSignatures) throws IOException {
7237 if (mSignatures == null) {
7238 return;
7239 }
7240 serializer.startTag(null, tagName);
7241 serializer.attribute(null, "count",
7242 Integer.toString(mSignatures.length));
7243 for (int i=0; i<mSignatures.length; i++) {
7244 serializer.startTag(null, "cert");
7245 final Signature sig = mSignatures[i];
7246 final int sigHash = sig.hashCode();
7247 final int numPast = pastSignatures.size();
7248 int j;
7249 for (j=0; j<numPast; j++) {
7250 Signature pastSig = pastSignatures.get(j);
7251 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7252 serializer.attribute(null, "index", Integer.toString(j));
7253 break;
7254 }
7255 }
7256 if (j >= numPast) {
7257 pastSignatures.add(sig);
7258 serializer.attribute(null, "index", Integer.toString(numPast));
7259 serializer.attribute(null, "key", sig.toCharsString());
7260 }
7261 serializer.endTag(null, "cert");
7262 }
7263 serializer.endTag(null, tagName);
7264 }
7265
7266 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7267 throws IOException, XmlPullParserException {
7268 String countStr = parser.getAttributeValue(null, "count");
7269 if (countStr == null) {
7270 reportSettingsProblem(Log.WARN,
7271 "Error in package manager settings: <signatures> has"
7272 + " no count at " + parser.getPositionDescription());
7273 XmlUtils.skipCurrentTag(parser);
7274 }
7275 final int count = Integer.parseInt(countStr);
7276 mSignatures = new Signature[count];
7277 int pos = 0;
7278
7279 int outerDepth = parser.getDepth();
7280 int type;
7281 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7282 && (type != XmlPullParser.END_TAG
7283 || parser.getDepth() > outerDepth)) {
7284 if (type == XmlPullParser.END_TAG
7285 || type == XmlPullParser.TEXT) {
7286 continue;
7287 }
7288
7289 String tagName = parser.getName();
7290 if (tagName.equals("cert")) {
7291 if (pos < count) {
7292 String index = parser.getAttributeValue(null, "index");
7293 if (index != null) {
7294 try {
7295 int idx = Integer.parseInt(index);
7296 String key = parser.getAttributeValue(null, "key");
7297 if (key == null) {
7298 if (idx >= 0 && idx < pastSignatures.size()) {
7299 Signature sig = pastSignatures.get(idx);
7300 if (sig != null) {
7301 mSignatures[pos] = pastSignatures.get(idx);
7302 pos++;
7303 } else {
7304 reportSettingsProblem(Log.WARN,
7305 "Error in package manager settings: <cert> "
7306 + "index " + index + " is not defined at "
7307 + parser.getPositionDescription());
7308 }
7309 } else {
7310 reportSettingsProblem(Log.WARN,
7311 "Error in package manager settings: <cert> "
7312 + "index " + index + " is out of bounds at "
7313 + parser.getPositionDescription());
7314 }
7315 } else {
7316 while (pastSignatures.size() <= idx) {
7317 pastSignatures.add(null);
7318 }
7319 Signature sig = new Signature(key);
7320 pastSignatures.set(idx, sig);
7321 mSignatures[pos] = sig;
7322 pos++;
7323 }
7324 } catch (NumberFormatException e) {
7325 reportSettingsProblem(Log.WARN,
7326 "Error in package manager settings: <cert> "
7327 + "index " + index + " is not a number at "
7328 + parser.getPositionDescription());
7329 }
7330 } else {
7331 reportSettingsProblem(Log.WARN,
7332 "Error in package manager settings: <cert> has"
7333 + " no index at " + parser.getPositionDescription());
7334 }
7335 } else {
7336 reportSettingsProblem(Log.WARN,
7337 "Error in package manager settings: too "
7338 + "many <cert> tags, expected " + count
7339 + " at " + parser.getPositionDescription());
7340 }
7341 } else {
7342 reportSettingsProblem(Log.WARN,
7343 "Unknown element under <cert>: "
7344 + parser.getName());
7345 }
7346 XmlUtils.skipCurrentTag(parser);
7347 }
7348
7349 if (pos < count) {
7350 // Should never happen -- there is an error in the written
7351 // settings -- but if it does we don't want to generate
7352 // a bad array.
7353 Signature[] newSigs = new Signature[pos];
7354 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7355 mSignatures = newSigs;
7356 }
7357 }
7358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007359 private void assignSignatures(Signature[] sigs) {
7360 if (sigs == null) {
7361 mSignatures = null;
7362 return;
7363 }
7364 mSignatures = new Signature[sigs.length];
7365 for (int i=0; i<sigs.length; i++) {
7366 mSignatures[i] = sigs[i];
7367 }
7368 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370 @Override
7371 public String toString() {
7372 StringBuffer buf = new StringBuffer(128);
7373 buf.append("PackageSignatures{");
7374 buf.append(Integer.toHexString(System.identityHashCode(this)));
7375 buf.append(" [");
7376 if (mSignatures != null) {
7377 for (int i=0; i<mSignatures.length; i++) {
7378 if (i > 0) buf.append(", ");
7379 buf.append(Integer.toHexString(
7380 System.identityHashCode(mSignatures[i])));
7381 }
7382 }
7383 buf.append("]}");
7384 return buf.toString();
7385 }
7386 }
7387
7388 static class PreferredActivity extends IntentFilter {
7389 final int mMatch;
7390 final String[] mSetPackages;
7391 final String[] mSetClasses;
7392 final String[] mSetComponents;
7393 final ComponentName mActivity;
7394 final String mShortActivity;
7395 String mParseError;
7396
7397 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7398 ComponentName activity) {
7399 super(filter);
7400 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7401 mActivity = activity;
7402 mShortActivity = activity.flattenToShortString();
7403 mParseError = null;
7404 if (set != null) {
7405 final int N = set.length;
7406 String[] myPackages = new String[N];
7407 String[] myClasses = new String[N];
7408 String[] myComponents = new String[N];
7409 for (int i=0; i<N; i++) {
7410 ComponentName cn = set[i];
7411 if (cn == null) {
7412 mSetPackages = null;
7413 mSetClasses = null;
7414 mSetComponents = null;
7415 return;
7416 }
7417 myPackages[i] = cn.getPackageName().intern();
7418 myClasses[i] = cn.getClassName().intern();
7419 myComponents[i] = cn.flattenToShortString().intern();
7420 }
7421 mSetPackages = myPackages;
7422 mSetClasses = myClasses;
7423 mSetComponents = myComponents;
7424 } else {
7425 mSetPackages = null;
7426 mSetClasses = null;
7427 mSetComponents = null;
7428 }
7429 }
7430
7431 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7432 IOException {
7433 mShortActivity = parser.getAttributeValue(null, "name");
7434 mActivity = ComponentName.unflattenFromString(mShortActivity);
7435 if (mActivity == null) {
7436 mParseError = "Bad activity name " + mShortActivity;
7437 }
7438 String matchStr = parser.getAttributeValue(null, "match");
7439 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7440 String setCountStr = parser.getAttributeValue(null, "set");
7441 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7442
7443 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7444 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7445 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7446
7447 int setPos = 0;
7448
7449 int outerDepth = parser.getDepth();
7450 int type;
7451 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7452 && (type != XmlPullParser.END_TAG
7453 || parser.getDepth() > outerDepth)) {
7454 if (type == XmlPullParser.END_TAG
7455 || type == XmlPullParser.TEXT) {
7456 continue;
7457 }
7458
7459 String tagName = parser.getName();
7460 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7461 // + parser.getDepth() + " tag=" + tagName);
7462 if (tagName.equals("set")) {
7463 String name = parser.getAttributeValue(null, "name");
7464 if (name == null) {
7465 if (mParseError == null) {
7466 mParseError = "No name in set tag in preferred activity "
7467 + mShortActivity;
7468 }
7469 } else if (setPos >= setCount) {
7470 if (mParseError == null) {
7471 mParseError = "Too many set tags in preferred activity "
7472 + mShortActivity;
7473 }
7474 } else {
7475 ComponentName cn = ComponentName.unflattenFromString(name);
7476 if (cn == null) {
7477 if (mParseError == null) {
7478 mParseError = "Bad set name " + name + " in preferred activity "
7479 + mShortActivity;
7480 }
7481 } else {
7482 myPackages[setPos] = cn.getPackageName();
7483 myClasses[setPos] = cn.getClassName();
7484 myComponents[setPos] = name;
7485 setPos++;
7486 }
7487 }
7488 XmlUtils.skipCurrentTag(parser);
7489 } else if (tagName.equals("filter")) {
7490 //Log.i(TAG, "Starting to parse filter...");
7491 readFromXml(parser);
7492 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7493 // + parser.getDepth() + " tag=" + parser.getName());
7494 } else {
7495 reportSettingsProblem(Log.WARN,
7496 "Unknown element under <preferred-activities>: "
7497 + parser.getName());
7498 XmlUtils.skipCurrentTag(parser);
7499 }
7500 }
7501
7502 if (setPos != setCount) {
7503 if (mParseError == null) {
7504 mParseError = "Not enough set tags (expected " + setCount
7505 + " but found " + setPos + ") in " + mShortActivity;
7506 }
7507 }
7508
7509 mSetPackages = myPackages;
7510 mSetClasses = myClasses;
7511 mSetComponents = myComponents;
7512 }
7513
7514 public void writeToXml(XmlSerializer serializer) throws IOException {
7515 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7516 serializer.attribute(null, "name", mShortActivity);
7517 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7518 serializer.attribute(null, "set", Integer.toString(NS));
7519 for (int s=0; s<NS; s++) {
7520 serializer.startTag(null, "set");
7521 serializer.attribute(null, "name", mSetComponents[s]);
7522 serializer.endTag(null, "set");
7523 }
7524 serializer.startTag(null, "filter");
7525 super.writeToXml(serializer);
7526 serializer.endTag(null, "filter");
7527 }
7528
7529 boolean sameSet(List<ResolveInfo> query, int priority) {
7530 if (mSetPackages == null) return false;
7531 final int NQ = query.size();
7532 final int NS = mSetPackages.length;
7533 int numMatch = 0;
7534 for (int i=0; i<NQ; i++) {
7535 ResolveInfo ri = query.get(i);
7536 if (ri.priority != priority) continue;
7537 ActivityInfo ai = ri.activityInfo;
7538 boolean good = false;
7539 for (int j=0; j<NS; j++) {
7540 if (mSetPackages[j].equals(ai.packageName)
7541 && mSetClasses[j].equals(ai.name)) {
7542 numMatch++;
7543 good = true;
7544 break;
7545 }
7546 }
7547 if (!good) return false;
7548 }
7549 return numMatch == NS;
7550 }
7551 }
7552
7553 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007554 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 HashSet<String> grantedPermissions = new HashSet<String>();
7557 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007559 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007560 setFlags(pkgFlags);
7561 }
7562
7563 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007564 this.pkgFlags = pkgFlags & (
7565 ApplicationInfo.FLAG_SYSTEM |
7566 ApplicationInfo.FLAG_FORWARD_LOCK |
7567 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 }
7569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571 /**
7572 * Settings base class for pending and resolved classes.
7573 */
7574 static class PackageSettingBase extends GrantedPermissions {
7575 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007576 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007577 File codePath;
7578 String codePathString;
7579 File resourcePath;
7580 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 private long timeStamp;
7582 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007583 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007585 boolean uidError;
7586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 PackageSignatures signatures = new PackageSignatures();
7588
7589 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007590 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 /* Explicitly disabled components */
7593 HashSet<String> disabledComponents = new HashSet<String>(0);
7594 /* Explicitly enabled components */
7595 HashSet<String> enabledComponents = new HashSet<String>(0);
7596 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7597 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007598
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007599 PackageSettingBase origPackage;
7600
Jacek Surazski65e13172009-04-28 15:26:38 +02007601 /* package name of the app that installed this package */
7602 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007604 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007605 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 super(pkgFlags);
7607 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007608 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007609 init(codePath, resourcePath, pVersionCode);
7610 }
7611
7612 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 this.codePath = codePath;
7614 this.codePathString = codePath.toString();
7615 this.resourcePath = resourcePath;
7616 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007617 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007618 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007619
Jacek Surazski65e13172009-04-28 15:26:38 +02007620 public void setInstallerPackageName(String packageName) {
7621 installerPackageName = packageName;
7622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007623
Jacek Surazski65e13172009-04-28 15:26:38 +02007624 String getInstallerPackageName() {
7625 return installerPackageName;
7626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 public void setInstallStatus(int newStatus) {
7629 installStatus = newStatus;
7630 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 public int getInstallStatus() {
7633 return installStatus;
7634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 public void setTimeStamp(long newStamp) {
7637 if (newStamp != timeStamp) {
7638 timeStamp = newStamp;
7639 timeStampString = Long.toString(newStamp);
7640 }
7641 }
7642
7643 public void setTimeStamp(long newStamp, String newStampStr) {
7644 timeStamp = newStamp;
7645 timeStampString = newStampStr;
7646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007648 public long getTimeStamp() {
7649 return timeStamp;
7650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 public String getTimeStampStr() {
7653 return timeStampString;
7654 }
7655
7656 public void copyFrom(PackageSettingBase base) {
7657 grantedPermissions = base.grantedPermissions;
7658 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 timeStamp = base.timeStamp;
7661 timeStampString = base.timeStampString;
7662 signatures = base.signatures;
7663 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007664 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 disabledComponents = base.disabledComponents;
7666 enabledComponents = base.enabledComponents;
7667 enabled = base.enabled;
7668 installStatus = base.installStatus;
7669 }
7670
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007671 boolean enableComponentLP(String componentClassName) {
7672 boolean changed = disabledComponents.remove(componentClassName);
7673 changed |= enabledComponents.add(componentClassName);
7674 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 }
7676
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007677 boolean disableComponentLP(String componentClassName) {
7678 boolean changed = enabledComponents.remove(componentClassName);
7679 changed |= disabledComponents.add(componentClassName);
7680 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 }
7682
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007683 boolean restoreComponentLP(String componentClassName) {
7684 boolean changed = enabledComponents.remove(componentClassName);
7685 changed |= disabledComponents.remove(componentClassName);
7686 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 }
7688
7689 int currentEnabledStateLP(String componentName) {
7690 if (enabledComponents.contains(componentName)) {
7691 return COMPONENT_ENABLED_STATE_ENABLED;
7692 } else if (disabledComponents.contains(componentName)) {
7693 return COMPONENT_ENABLED_STATE_DISABLED;
7694 } else {
7695 return COMPONENT_ENABLED_STATE_DEFAULT;
7696 }
7697 }
7698 }
7699
7700 /**
7701 * Settings data for a particular package we know about.
7702 */
7703 static final class PackageSetting extends PackageSettingBase {
7704 int userId;
7705 PackageParser.Package pkg;
7706 SharedUserSetting sharedUser;
7707
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007708 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007709 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007710 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 @Override
7714 public String toString() {
7715 return "PackageSetting{"
7716 + Integer.toHexString(System.identityHashCode(this))
7717 + " " + name + "/" + userId + "}";
7718 }
7719 }
7720
7721 /**
7722 * Settings data for a particular shared user ID we know about.
7723 */
7724 static final class SharedUserSetting extends GrantedPermissions {
7725 final String name;
7726 int userId;
7727 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7728 final PackageSignatures signatures = new PackageSignatures();
7729
7730 SharedUserSetting(String _name, int _pkgFlags) {
7731 super(_pkgFlags);
7732 name = _name;
7733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 @Override
7736 public String toString() {
7737 return "SharedUserSetting{"
7738 + Integer.toHexString(System.identityHashCode(this))
7739 + " " + name + "/" + userId + "}";
7740 }
7741 }
7742
7743 /**
7744 * Holds information about dynamic settings.
7745 */
7746 private static final class Settings {
7747 private final File mSettingsFilename;
7748 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007749 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 private final HashMap<String, PackageSetting> mPackages =
7751 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 // List of replaced system applications
7753 final HashMap<String, PackageSetting> mDisabledSysPackages =
7754 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007755
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007756 // These are the last platform API version we were using for
7757 // the apps installed on internal and external storage. It is
7758 // used to grant newer permissions one time during a system upgrade.
7759 int mInternalSdkPlatform;
7760 int mExternalSdkPlatform;
7761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 // The user's preferred activities associated with particular intent
7763 // filters.
7764 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7765 new IntentResolver<PreferredActivity, PreferredActivity>() {
7766 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007767 protected String packageForFilter(PreferredActivity filter) {
7768 return filter.mActivity.getPackageName();
7769 }
7770 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007771 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007773 out.print(prefix); out.print(
7774 Integer.toHexString(System.identityHashCode(filter)));
7775 out.print(' ');
7776 out.print(filter.mActivity.flattenToShortString());
7777 out.print(" match=0x");
7778 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007780 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007782 out.print(prefix); out.print(" ");
7783 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 }
7785 }
7786 }
7787 };
7788 private final HashMap<String, SharedUserSetting> mSharedUsers =
7789 new HashMap<String, SharedUserSetting>();
7790 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7791 private final SparseArray<Object> mOtherUserIds =
7792 new SparseArray<Object>();
7793
7794 // For reading/writing settings file.
7795 private final ArrayList<Signature> mPastSignatures =
7796 new ArrayList<Signature>();
7797
7798 // Mapping from permission names to info about them.
7799 final HashMap<String, BasePermission> mPermissions =
7800 new HashMap<String, BasePermission>();
7801
7802 // Mapping from permission tree names to info about them.
7803 final HashMap<String, BasePermission> mPermissionTrees =
7804 new HashMap<String, BasePermission>();
7805
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007806 // Packages that have been uninstalled and still need their external
7807 // storage data deleted.
7808 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7809
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007810 // Packages that have been renamed since they were first installed.
7811 // Keys are the new names of the packages, values are the original
7812 // names. The packages appear everwhere else under their original
7813 // names.
7814 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 private final StringBuilder mReadMessages = new StringBuilder();
7817
7818 private static final class PendingPackage extends PackageSettingBase {
7819 final int sharedId;
7820
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007821 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007822 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007823 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 this.sharedId = sharedId;
7825 }
7826 }
7827 private final ArrayList<PendingPackage> mPendingPackages
7828 = new ArrayList<PendingPackage>();
7829
7830 Settings() {
7831 File dataDir = Environment.getDataDirectory();
7832 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007833 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 systemDir.mkdirs();
7835 FileUtils.setPermissions(systemDir.toString(),
7836 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7837 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7838 -1, -1);
7839 mSettingsFilename = new File(systemDir, "packages.xml");
7840 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007841 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
7843
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007844 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007845 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 int pkgFlags, boolean create, boolean add) {
7847 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007848 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007849 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 return p;
7851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007852
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007853 PackageSetting peekPackageLP(String name) {
7854 return mPackages.get(name);
7855 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 PackageSetting p = mPackages.get(name);
7857 if (p != null && p.codePath.getPath().equals(codePath)) {
7858 return p;
7859 }
7860 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007861 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 void setInstallStatus(String pkgName, int status) {
7865 PackageSetting p = mPackages.get(pkgName);
7866 if(p != null) {
7867 if(p.getInstallStatus() != status) {
7868 p.setInstallStatus(status);
7869 }
7870 }
7871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007872
Jacek Surazski65e13172009-04-28 15:26:38 +02007873 void setInstallerPackageName(String pkgName,
7874 String installerPkgName) {
7875 PackageSetting p = mPackages.get(pkgName);
7876 if(p != null) {
7877 p.setInstallerPackageName(installerPkgName);
7878 }
7879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007880
Jacek Surazski65e13172009-04-28 15:26:38 +02007881 String getInstallerPackageName(String pkgName) {
7882 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007883 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007884 }
7885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 int getInstallStatus(String pkgName) {
7887 PackageSetting p = mPackages.get(pkgName);
7888 if(p != null) {
7889 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 return -1;
7892 }
7893
7894 SharedUserSetting getSharedUserLP(String name,
7895 int pkgFlags, boolean create) {
7896 SharedUserSetting s = mSharedUsers.get(name);
7897 if (s == null) {
7898 if (!create) {
7899 return null;
7900 }
7901 s = new SharedUserSetting(name, pkgFlags);
7902 if (MULTIPLE_APPLICATION_UIDS) {
7903 s.userId = newUserIdLP(s);
7904 } else {
7905 s.userId = FIRST_APPLICATION_UID;
7906 }
7907 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7908 // < 0 means we couldn't assign a userid; fall out and return
7909 // s, which is currently null
7910 if (s.userId >= 0) {
7911 mSharedUsers.put(name, s);
7912 }
7913 }
7914
7915 return s;
7916 }
7917
7918 int disableSystemPackageLP(String name) {
7919 PackageSetting p = mPackages.get(name);
7920 if(p == null) {
7921 Log.w(TAG, "Package:"+name+" is not an installed package");
7922 return -1;
7923 }
7924 PackageSetting dp = mDisabledSysPackages.get(name);
7925 // always make sure the system package code and resource paths dont change
7926 if(dp == null) {
7927 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7928 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7929 }
7930 mDisabledSysPackages.put(name, p);
7931 }
7932 return removePackageLP(name);
7933 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 PackageSetting enableSystemPackageLP(String name) {
7936 PackageSetting p = mDisabledSysPackages.get(name);
7937 if(p == null) {
7938 Log.w(TAG, "Package:"+name+" is not disabled");
7939 return null;
7940 }
7941 // Reset flag in ApplicationInfo object
7942 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7943 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7944 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007945 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007946 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 mDisabledSysPackages.remove(name);
7948 return ret;
7949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007950
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007951 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007952 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 PackageSetting p = mPackages.get(name);
7954 if (p != null) {
7955 if (p.userId == uid) {
7956 return p;
7957 }
7958 reportSettingsProblem(Log.ERROR,
7959 "Adding duplicate package, keeping first: " + name);
7960 return null;
7961 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007962 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 p.userId = uid;
7964 if (addUserIdLP(uid, p, name)) {
7965 mPackages.put(name, p);
7966 return p;
7967 }
7968 return null;
7969 }
7970
7971 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7972 SharedUserSetting s = mSharedUsers.get(name);
7973 if (s != null) {
7974 if (s.userId == uid) {
7975 return s;
7976 }
7977 reportSettingsProblem(Log.ERROR,
7978 "Adding duplicate shared user, keeping first: " + name);
7979 return null;
7980 }
7981 s = new SharedUserSetting(name, pkgFlags);
7982 s.userId = uid;
7983 if (addUserIdLP(uid, s, name)) {
7984 mSharedUsers.put(name, s);
7985 return s;
7986 }
7987 return null;
7988 }
7989
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007990 // Transfer ownership of permissions from one package to another.
7991 private void transferPermissions(String origPkg, String newPkg) {
7992 // Transfer ownership of permissions to the new package.
7993 for (int i=0; i<2; i++) {
7994 HashMap<String, BasePermission> permissions =
7995 i == 0 ? mPermissionTrees : mPermissions;
7996 for (BasePermission bp : permissions.values()) {
7997 if (origPkg.equals(bp.sourcePackage)) {
7998 if (DEBUG_UPGRADE) Log.v(TAG,
7999 "Moving permission " + bp.name
8000 + " from pkg " + bp.sourcePackage
8001 + " to " + newPkg);
8002 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008003 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008004 bp.perm = null;
8005 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008006 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008007 }
8008 bp.uid = 0;
8009 bp.gids = null;
8010 }
8011 }
8012 }
8013 }
8014
8015 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008016 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008017 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 PackageSetting p = mPackages.get(name);
8019 if (p != null) {
8020 if (!p.codePath.equals(codePath)) {
8021 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008022 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008023 // This is an updated system app with versions in both system
8024 // and data partition. Just let the most recent version
8025 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008026 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008027 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008028 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008029 // Just a change in the code path is not an issue, but
8030 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008031 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008032 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008034 }
8035 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 reportSettingsProblem(Log.WARN,
8037 "Package " + name + " shared user changed from "
8038 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8039 + " to "
8040 + (sharedUser != null ? sharedUser.name : "<nothing>")
8041 + "; replacing with new");
8042 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008043 } else {
8044 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8045 // If what we are scanning is a system package, then
8046 // make it so, regardless of whether it was previously
8047 // installed only in the data partition.
8048 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 }
8051 }
8052 if (p == null) {
8053 // Create a new PackageSettings entry. this can end up here because
8054 // of code path mismatch or user id mismatch of an updated system partition
8055 if (!create) {
8056 return null;
8057 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008058 if (origPackage != null) {
8059 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008060 p = new PackageSetting(origPackage.name, name, codePath,
8061 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008062 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8063 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008064 // Note that we will retain the new package's signature so
8065 // that we can keep its data.
8066 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008067 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008068 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008069 p.sharedUser = origPackage.sharedUser;
8070 p.userId = origPackage.userId;
8071 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008072 mRenamedPackages.put(name, origPackage.name);
8073 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008074 // Update new package state.
8075 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008077 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008078 p.setTimeStamp(codePath.lastModified());
8079 p.sharedUser = sharedUser;
8080 if (sharedUser != null) {
8081 p.userId = sharedUser.userId;
8082 } else if (MULTIPLE_APPLICATION_UIDS) {
8083 // Clone the setting here for disabled system packages
8084 PackageSetting dis = mDisabledSysPackages.get(name);
8085 if (dis != null) {
8086 // For disabled packages a new setting is created
8087 // from the existing user id. This still has to be
8088 // added to list of user id's
8089 // Copy signatures from previous setting
8090 if (dis.signatures.mSignatures != null) {
8091 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8092 }
8093 p.userId = dis.userId;
8094 // Clone permissions
8095 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008096 // Clone component info
8097 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8098 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8099 // Add new setting to list of user ids
8100 addUserIdLP(p.userId, p, name);
8101 } else {
8102 // Assign new user id
8103 p.userId = newUserIdLP(p);
8104 }
8105 } else {
8106 p.userId = FIRST_APPLICATION_UID;
8107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 }
8109 if (p.userId < 0) {
8110 reportSettingsProblem(Log.WARN,
8111 "Package " + name + " could not be assigned a valid uid");
8112 return null;
8113 }
8114 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008115 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008116 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008117 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 }
8119 }
8120 return p;
8121 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008122
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008123 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008124 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008125 String codePath = pkg.applicationInfo.sourceDir;
8126 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008127 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008128 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008129 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008130 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008131 p.codePath = new File(codePath);
8132 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008133 }
8134 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008135 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008136 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008137 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008138 p.resourcePath = new File(resourcePath);
8139 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008140 }
8141 // Update version code if needed
8142 if (pkg.mVersionCode != p.versionCode) {
8143 p.versionCode = pkg.mVersionCode;
8144 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008145 // Update signatures if needed.
8146 if (p.signatures.mSignatures == null) {
8147 p.signatures.assignSignatures(pkg.mSignatures);
8148 }
8149 // If this app defines a shared user id initialize
8150 // the shared user signatures as well.
8151 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8152 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8153 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008154 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8155 }
8156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 // Utility method that adds a PackageSetting to mPackages and
8158 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008159 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 SharedUserSetting sharedUser) {
8161 mPackages.put(name, p);
8162 if (sharedUser != null) {
8163 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8164 reportSettingsProblem(Log.ERROR,
8165 "Package " + p.name + " was user "
8166 + p.sharedUser + " but is now " + sharedUser
8167 + "; I am not changing its files so it will probably fail!");
8168 p.sharedUser.packages.remove(p);
8169 } else if (p.userId != sharedUser.userId) {
8170 reportSettingsProblem(Log.ERROR,
8171 "Package " + p.name + " was user id " + p.userId
8172 + " but is now user " + sharedUser
8173 + " with id " + sharedUser.userId
8174 + "; I am not changing its files so it will probably fail!");
8175 }
8176
8177 sharedUser.packages.add(p);
8178 p.sharedUser = sharedUser;
8179 p.userId = sharedUser.userId;
8180 }
8181 }
8182
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008183 /*
8184 * Update the shared user setting when a package using
8185 * specifying the shared user id is removed. The gids
8186 * associated with each permission of the deleted package
8187 * are removed from the shared user's gid list only if its
8188 * not in use by other permissions of packages in the
8189 * shared user setting.
8190 */
8191 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008193 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 return;
8195 }
8196 // No sharedUserId
8197 if (deletedPs.sharedUser == null) {
8198 return;
8199 }
8200 SharedUserSetting sus = deletedPs.sharedUser;
8201 // Update permissions
8202 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8203 boolean used = false;
8204 if (!sus.grantedPermissions.contains (eachPerm)) {
8205 continue;
8206 }
8207 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008208 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008209 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008210 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 used = true;
8212 break;
8213 }
8214 }
8215 if (!used) {
8216 // can safely delete this permission from list
8217 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 }
8219 }
8220 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008221 int newGids[] = globalGids;
8222 for (String eachPerm : sus.grantedPermissions) {
8223 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008224 if (bp != null) {
8225 newGids = appendInts(newGids, bp.gids);
8226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 }
8228 sus.gids = newGids;
8229 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008231 private int removePackageLP(String name) {
8232 PackageSetting p = mPackages.get(name);
8233 if (p != null) {
8234 mPackages.remove(name);
8235 if (p.sharedUser != null) {
8236 p.sharedUser.packages.remove(p);
8237 if (p.sharedUser.packages.size() == 0) {
8238 mSharedUsers.remove(p.sharedUser.name);
8239 removeUserIdLP(p.sharedUser.userId);
8240 return p.sharedUser.userId;
8241 }
8242 } else {
8243 removeUserIdLP(p.userId);
8244 return p.userId;
8245 }
8246 }
8247 return -1;
8248 }
8249
8250 private boolean addUserIdLP(int uid, Object obj, Object name) {
8251 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8252 return false;
8253 }
8254
8255 if (uid >= FIRST_APPLICATION_UID) {
8256 int N = mUserIds.size();
8257 final int index = uid - FIRST_APPLICATION_UID;
8258 while (index >= N) {
8259 mUserIds.add(null);
8260 N++;
8261 }
8262 if (mUserIds.get(index) != null) {
8263 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008264 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 + " name=" + name);
8266 return false;
8267 }
8268 mUserIds.set(index, obj);
8269 } else {
8270 if (mOtherUserIds.get(uid) != null) {
8271 reportSettingsProblem(Log.ERROR,
8272 "Adding duplicate shared id: " + uid
8273 + " name=" + name);
8274 return false;
8275 }
8276 mOtherUserIds.put(uid, obj);
8277 }
8278 return true;
8279 }
8280
8281 public Object getUserIdLP(int uid) {
8282 if (uid >= FIRST_APPLICATION_UID) {
8283 int N = mUserIds.size();
8284 final int index = uid - FIRST_APPLICATION_UID;
8285 return index < N ? mUserIds.get(index) : null;
8286 } else {
8287 return mOtherUserIds.get(uid);
8288 }
8289 }
8290
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008291 private Set<String> findPackagesWithFlag(int flag) {
8292 Set<String> ret = new HashSet<String>();
8293 for (PackageSetting ps : mPackages.values()) {
8294 // Has to match atleast all the flag bits set on flag
8295 if ((ps.pkgFlags & flag) == flag) {
8296 ret.add(ps.name);
8297 }
8298 }
8299 return ret;
8300 }
8301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 private void removeUserIdLP(int uid) {
8303 if (uid >= FIRST_APPLICATION_UID) {
8304 int N = mUserIds.size();
8305 final int index = uid - FIRST_APPLICATION_UID;
8306 if (index < N) mUserIds.set(index, null);
8307 } else {
8308 mOtherUserIds.remove(uid);
8309 }
8310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 void writeLP() {
8313 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8314
8315 // Keep the old settings around until we know the new ones have
8316 // been successfully written.
8317 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008318 // Presence of backup settings file indicates that we failed
8319 // to persist settings earlier. So preserve the older
8320 // backup for future reference since the current settings
8321 // might have been corrupted.
8322 if (!mBackupSettingsFilename.exists()) {
8323 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008324 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008325 return;
8326 }
8327 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008328 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008329 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 }
8332
8333 mPastSignatures.clear();
8334
8335 try {
8336 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8337
8338 //XmlSerializer serializer = XmlUtils.serializerInstance();
8339 XmlSerializer serializer = new FastXmlSerializer();
8340 serializer.setOutput(str, "utf-8");
8341 serializer.startDocument(null, true);
8342 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8343
8344 serializer.startTag(null, "packages");
8345
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008346 serializer.startTag(null, "last-platform-version");
8347 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8348 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8349 serializer.endTag(null, "last-platform-version");
8350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 serializer.startTag(null, "permission-trees");
8352 for (BasePermission bp : mPermissionTrees.values()) {
8353 writePermission(serializer, bp);
8354 }
8355 serializer.endTag(null, "permission-trees");
8356
8357 serializer.startTag(null, "permissions");
8358 for (BasePermission bp : mPermissions.values()) {
8359 writePermission(serializer, bp);
8360 }
8361 serializer.endTag(null, "permissions");
8362
8363 for (PackageSetting pkg : mPackages.values()) {
8364 writePackage(serializer, pkg);
8365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8368 writeDisabledSysPackage(serializer, pkg);
8369 }
8370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 serializer.startTag(null, "preferred-activities");
8372 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8373 serializer.startTag(null, "item");
8374 pa.writeToXml(serializer);
8375 serializer.endTag(null, "item");
8376 }
8377 serializer.endTag(null, "preferred-activities");
8378
8379 for (SharedUserSetting usr : mSharedUsers.values()) {
8380 serializer.startTag(null, "shared-user");
8381 serializer.attribute(null, "name", usr.name);
8382 serializer.attribute(null, "userId",
8383 Integer.toString(usr.userId));
8384 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8385 serializer.startTag(null, "perms");
8386 for (String name : usr.grantedPermissions) {
8387 serializer.startTag(null, "item");
8388 serializer.attribute(null, "name", name);
8389 serializer.endTag(null, "item");
8390 }
8391 serializer.endTag(null, "perms");
8392 serializer.endTag(null, "shared-user");
8393 }
8394
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008395 if (mPackagesToBeCleaned.size() > 0) {
8396 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8397 serializer.startTag(null, "cleaning-package");
8398 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8399 serializer.endTag(null, "cleaning-package");
8400 }
8401 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008402
8403 if (mRenamedPackages.size() > 0) {
8404 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8405 serializer.startTag(null, "renamed-package");
8406 serializer.attribute(null, "new", e.getKey());
8407 serializer.attribute(null, "old", e.getValue());
8408 serializer.endTag(null, "renamed-package");
8409 }
8410 }
8411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 serializer.endTag(null, "packages");
8413
8414 serializer.endDocument();
8415
8416 str.flush();
8417 str.close();
8418
8419 // New settings successfully written, old ones are no longer
8420 // needed.
8421 mBackupSettingsFilename.delete();
8422 FileUtils.setPermissions(mSettingsFilename.toString(),
8423 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8424 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8425 |FileUtils.S_IROTH,
8426 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008427
8428 // Write package list file now, use a JournaledFile.
8429 //
8430 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8431 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8432
8433 str = new FileOutputStream(journal.chooseForWrite());
8434 try {
8435 StringBuilder sb = new StringBuilder();
8436 for (PackageSetting pkg : mPackages.values()) {
8437 ApplicationInfo ai = pkg.pkg.applicationInfo;
8438 String dataPath = ai.dataDir;
8439 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8440
8441 // Avoid any application that has a space in its path
8442 // or that is handled by the system.
8443 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8444 continue;
8445
8446 // we store on each line the following information for now:
8447 //
8448 // pkgName - package name
8449 // userId - application-specific user id
8450 // debugFlag - 0 or 1 if the package is debuggable.
8451 // dataPath - path to package's data path
8452 //
8453 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8454 //
8455 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8456 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8457 // system/core/run-as/run-as.c
8458 //
8459 sb.setLength(0);
8460 sb.append(ai.packageName);
8461 sb.append(" ");
8462 sb.append((int)ai.uid);
8463 sb.append(isDebug ? " 1 " : " 0 ");
8464 sb.append(dataPath);
8465 sb.append("\n");
8466 str.write(sb.toString().getBytes());
8467 }
8468 str.flush();
8469 str.close();
8470 journal.commit();
8471 }
8472 catch (Exception e) {
8473 journal.rollback();
8474 }
8475
8476 FileUtils.setPermissions(mPackageListFilename.toString(),
8477 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8478 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8479 |FileUtils.S_IROTH,
8480 -1, -1);
8481
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008482 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483
8484 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008485 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 -08008486 } catch(java.io.IOException 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 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008489 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008490 if (mSettingsFilename.exists()) {
8491 if (!mSettingsFilename.delete()) {
8492 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8493 }
8494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 //Debug.stopMethodTracing();
8496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008497
8498 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008499 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008500 serializer.startTag(null, "updated-package");
8501 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008502 if (pkg.realName != null) {
8503 serializer.attribute(null, "realName", pkg.realName);
8504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 serializer.attribute(null, "codePath", pkg.codePathString);
8506 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008507 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8509 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8510 }
8511 if (pkg.sharedUser == null) {
8512 serializer.attribute(null, "userId",
8513 Integer.toString(pkg.userId));
8514 } else {
8515 serializer.attribute(null, "sharedUserId",
8516 Integer.toString(pkg.userId));
8517 }
8518 serializer.startTag(null, "perms");
8519 if (pkg.sharedUser == null) {
8520 // If this is a shared user, the permissions will
8521 // be written there. We still need to write an
8522 // empty permissions list so permissionsFixed will
8523 // be set.
8524 for (final String name : pkg.grantedPermissions) {
8525 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008526 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008527 // We only need to write signature or system permissions but this wont
8528 // match the semantics of grantedPermissions. So write all permissions.
8529 serializer.startTag(null, "item");
8530 serializer.attribute(null, "name", name);
8531 serializer.endTag(null, "item");
8532 }
8533 }
8534 }
8535 serializer.endTag(null, "perms");
8536 serializer.endTag(null, "updated-package");
8537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008538
8539 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008540 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 serializer.startTag(null, "package");
8542 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008543 if (pkg.realName != null) {
8544 serializer.attribute(null, "realName", pkg.realName);
8545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 serializer.attribute(null, "codePath", pkg.codePathString);
8547 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8548 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8549 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008550 serializer.attribute(null, "flags",
8551 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008553 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 if (pkg.sharedUser == null) {
8555 serializer.attribute(null, "userId",
8556 Integer.toString(pkg.userId));
8557 } else {
8558 serializer.attribute(null, "sharedUserId",
8559 Integer.toString(pkg.userId));
8560 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008561 if (pkg.uidError) {
8562 serializer.attribute(null, "uidError", "true");
8563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8565 serializer.attribute(null, "enabled",
8566 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8567 ? "true" : "false");
8568 }
8569 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8570 serializer.attribute(null, "installStatus", "false");
8571 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008572 if (pkg.installerPackageName != null) {
8573 serializer.attribute(null, "installer", pkg.installerPackageName);
8574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8576 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8577 serializer.startTag(null, "perms");
8578 if (pkg.sharedUser == null) {
8579 // If this is a shared user, the permissions will
8580 // be written there. We still need to write an
8581 // empty permissions list so permissionsFixed will
8582 // be set.
8583 for (final String name : pkg.grantedPermissions) {
8584 serializer.startTag(null, "item");
8585 serializer.attribute(null, "name", name);
8586 serializer.endTag(null, "item");
8587 }
8588 }
8589 serializer.endTag(null, "perms");
8590 }
8591 if (pkg.disabledComponents.size() > 0) {
8592 serializer.startTag(null, "disabled-components");
8593 for (final String name : pkg.disabledComponents) {
8594 serializer.startTag(null, "item");
8595 serializer.attribute(null, "name", name);
8596 serializer.endTag(null, "item");
8597 }
8598 serializer.endTag(null, "disabled-components");
8599 }
8600 if (pkg.enabledComponents.size() > 0) {
8601 serializer.startTag(null, "enabled-components");
8602 for (final String name : pkg.enabledComponents) {
8603 serializer.startTag(null, "item");
8604 serializer.attribute(null, "name", name);
8605 serializer.endTag(null, "item");
8606 }
8607 serializer.endTag(null, "enabled-components");
8608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 serializer.endTag(null, "package");
8611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 void writePermission(XmlSerializer serializer, BasePermission bp)
8614 throws XmlPullParserException, java.io.IOException {
8615 if (bp.type != BasePermission.TYPE_BUILTIN
8616 && bp.sourcePackage != null) {
8617 serializer.startTag(null, "item");
8618 serializer.attribute(null, "name", bp.name);
8619 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008620 if (bp.protectionLevel !=
8621 PermissionInfo.PROTECTION_NORMAL) {
8622 serializer.attribute(null, "protection",
8623 Integer.toString(bp.protectionLevel));
8624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 if (DEBUG_SETTINGS) Log.v(TAG,
8626 "Writing perm: name=" + bp.name + " type=" + bp.type);
8627 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8628 PermissionInfo pi = bp.perm != null ? bp.perm.info
8629 : bp.pendingInfo;
8630 if (pi != null) {
8631 serializer.attribute(null, "type", "dynamic");
8632 if (pi.icon != 0) {
8633 serializer.attribute(null, "icon",
8634 Integer.toString(pi.icon));
8635 }
8636 if (pi.nonLocalizedLabel != null) {
8637 serializer.attribute(null, "label",
8638 pi.nonLocalizedLabel.toString());
8639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 }
8641 }
8642 serializer.endTag(null, "item");
8643 }
8644 }
8645
8646 String getReadMessagesLP() {
8647 return mReadMessages.toString();
8648 }
8649
Oscar Montemayora8529f62009-11-18 10:14:20 -08008650 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8652 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008653 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 while(its.hasNext()) {
8655 String key = its.next();
8656 PackageSetting ps = mPackages.get(key);
8657 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008658 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 }
8660 }
8661 return ret;
8662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 boolean readLP() {
8665 FileInputStream str = null;
8666 if (mBackupSettingsFilename.exists()) {
8667 try {
8668 str = new FileInputStream(mBackupSettingsFilename);
8669 mReadMessages.append("Reading from backup settings file\n");
8670 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008671 if (mSettingsFilename.exists()) {
8672 // If both the backup and settings file exist, we
8673 // ignore the settings since it might have been
8674 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008675 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008676 mSettingsFilename.delete();
8677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 } catch (java.io.IOException e) {
8679 // We'll try for the normal settings file.
8680 }
8681 }
8682
8683 mPastSignatures.clear();
8684
8685 try {
8686 if (str == null) {
8687 if (!mSettingsFilename.exists()) {
8688 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008689 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 return false;
8691 }
8692 str = new FileInputStream(mSettingsFilename);
8693 }
8694 XmlPullParser parser = Xml.newPullParser();
8695 parser.setInput(str, null);
8696
8697 int type;
8698 while ((type=parser.next()) != XmlPullParser.START_TAG
8699 && type != XmlPullParser.END_DOCUMENT) {
8700 ;
8701 }
8702
8703 if (type != XmlPullParser.START_TAG) {
8704 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008705 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 return false;
8707 }
8708
8709 int outerDepth = parser.getDepth();
8710 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8711 && (type != XmlPullParser.END_TAG
8712 || parser.getDepth() > outerDepth)) {
8713 if (type == XmlPullParser.END_TAG
8714 || type == XmlPullParser.TEXT) {
8715 continue;
8716 }
8717
8718 String tagName = parser.getName();
8719 if (tagName.equals("package")) {
8720 readPackageLP(parser);
8721 } else if (tagName.equals("permissions")) {
8722 readPermissionsLP(mPermissions, parser);
8723 } else if (tagName.equals("permission-trees")) {
8724 readPermissionsLP(mPermissionTrees, parser);
8725 } else if (tagName.equals("shared-user")) {
8726 readSharedUserLP(parser);
8727 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008728 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 } else if (tagName.equals("preferred-activities")) {
8730 readPreferredActivitiesLP(parser);
8731 } else if(tagName.equals("updated-package")) {
8732 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008733 } else if (tagName.equals("cleaning-package")) {
8734 String name = parser.getAttributeValue(null, "name");
8735 if (name != null) {
8736 mPackagesToBeCleaned.add(name);
8737 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008738 } else if (tagName.equals("renamed-package")) {
8739 String nname = parser.getAttributeValue(null, "new");
8740 String oname = parser.getAttributeValue(null, "old");
8741 if (nname != null && oname != null) {
8742 mRenamedPackages.put(nname, oname);
8743 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008744 } else if (tagName.equals("last-platform-version")) {
8745 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8746 try {
8747 String internal = parser.getAttributeValue(null, "internal");
8748 if (internal != null) {
8749 mInternalSdkPlatform = Integer.parseInt(internal);
8750 }
8751 String external = parser.getAttributeValue(null, "external");
8752 if (external != null) {
8753 mInternalSdkPlatform = Integer.parseInt(external);
8754 }
8755 } catch (NumberFormatException e) {
8756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008758 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 + parser.getName());
8760 XmlUtils.skipCurrentTag(parser);
8761 }
8762 }
8763
8764 str.close();
8765
8766 } catch(XmlPullParserException e) {
8767 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008768 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769
8770 } catch(java.io.IOException e) {
8771 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008772 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773
8774 }
8775
8776 int N = mPendingPackages.size();
8777 for (int i=0; i<N; i++) {
8778 final PendingPackage pp = mPendingPackages.get(i);
8779 Object idObj = getUserIdLP(pp.sharedId);
8780 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008781 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008783 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008785 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 + pp.name);
8787 continue;
8788 }
8789 p.copyFrom(pp);
8790 } else if (idObj != null) {
8791 String msg = "Bad package setting: package " + pp.name
8792 + " has shared uid " + pp.sharedId
8793 + " that is not a shared uid\n";
8794 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008795 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 } else {
8797 String msg = "Bad package setting: package " + pp.name
8798 + " has shared uid " + pp.sharedId
8799 + " that is not defined\n";
8800 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008801 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 }
8803 }
8804 mPendingPackages.clear();
8805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 mReadMessages.append("Read completed successfully: "
8807 + mPackages.size() + " packages, "
8808 + mSharedUsers.size() + " shared uids\n");
8809
8810 return true;
8811 }
8812
8813 private int readInt(XmlPullParser parser, String ns, String name,
8814 int defValue) {
8815 String v = parser.getAttributeValue(ns, name);
8816 try {
8817 if (v == null) {
8818 return defValue;
8819 }
8820 return Integer.parseInt(v);
8821 } catch (NumberFormatException e) {
8822 reportSettingsProblem(Log.WARN,
8823 "Error in package manager settings: attribute " +
8824 name + " has bad integer value " + v + " at "
8825 + parser.getPositionDescription());
8826 }
8827 return defValue;
8828 }
8829
8830 private void readPermissionsLP(HashMap<String, BasePermission> out,
8831 XmlPullParser parser)
8832 throws IOException, XmlPullParserException {
8833 int outerDepth = parser.getDepth();
8834 int type;
8835 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8836 && (type != XmlPullParser.END_TAG
8837 || parser.getDepth() > outerDepth)) {
8838 if (type == XmlPullParser.END_TAG
8839 || type == XmlPullParser.TEXT) {
8840 continue;
8841 }
8842
8843 String tagName = parser.getName();
8844 if (tagName.equals("item")) {
8845 String name = parser.getAttributeValue(null, "name");
8846 String sourcePackage = parser.getAttributeValue(null, "package");
8847 String ptype = parser.getAttributeValue(null, "type");
8848 if (name != null && sourcePackage != null) {
8849 boolean dynamic = "dynamic".equals(ptype);
8850 BasePermission bp = new BasePermission(name, sourcePackage,
8851 dynamic
8852 ? BasePermission.TYPE_DYNAMIC
8853 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008854 bp.protectionLevel = readInt(parser, null, "protection",
8855 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 if (dynamic) {
8857 PermissionInfo pi = new PermissionInfo();
8858 pi.packageName = sourcePackage.intern();
8859 pi.name = name.intern();
8860 pi.icon = readInt(parser, null, "icon", 0);
8861 pi.nonLocalizedLabel = parser.getAttributeValue(
8862 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008863 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 bp.pendingInfo = pi;
8865 }
8866 out.put(bp.name, bp);
8867 } else {
8868 reportSettingsProblem(Log.WARN,
8869 "Error in package manager settings: permissions has"
8870 + " no name at " + parser.getPositionDescription());
8871 }
8872 } else {
8873 reportSettingsProblem(Log.WARN,
8874 "Unknown element reading permissions: "
8875 + parser.getName() + " at "
8876 + parser.getPositionDescription());
8877 }
8878 XmlUtils.skipCurrentTag(parser);
8879 }
8880 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008883 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008885 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 String codePathStr = parser.getAttributeValue(null, "codePath");
8887 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008888 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 resourcePathStr = codePathStr;
8890 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008891 String version = parser.getAttributeValue(null, "version");
8892 int versionCode = 0;
8893 if (version != null) {
8894 try {
8895 versionCode = Integer.parseInt(version);
8896 } catch (NumberFormatException e) {
8897 }
8898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900 int pkgFlags = 0;
8901 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008902 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008903 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008904 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 String timeStampStr = parser.getAttributeValue(null, "ts");
8906 if (timeStampStr != null) {
8907 try {
8908 long timeStamp = Long.parseLong(timeStampStr);
8909 ps.setTimeStamp(timeStamp, timeStampStr);
8910 } catch (NumberFormatException e) {
8911 }
8912 }
8913 String idStr = parser.getAttributeValue(null, "userId");
8914 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8915 if(ps.userId <= 0) {
8916 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8917 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8918 }
8919 int outerDepth = parser.getDepth();
8920 int type;
8921 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8922 && (type != XmlPullParser.END_TAG
8923 || parser.getDepth() > outerDepth)) {
8924 if (type == XmlPullParser.END_TAG
8925 || type == XmlPullParser.TEXT) {
8926 continue;
8927 }
8928
8929 String tagName = parser.getName();
8930 if (tagName.equals("perms")) {
8931 readGrantedPermissionsLP(parser,
8932 ps.grantedPermissions);
8933 } else {
8934 reportSettingsProblem(Log.WARN,
8935 "Unknown element under <updated-package>: "
8936 + parser.getName());
8937 XmlUtils.skipCurrentTag(parser);
8938 }
8939 }
8940 mDisabledSysPackages.put(name, ps);
8941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 private void readPackageLP(XmlPullParser parser)
8944 throws XmlPullParserException, IOException {
8945 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008946 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 String idStr = null;
8948 String sharedIdStr = null;
8949 String codePathStr = null;
8950 String resourcePathStr = null;
8951 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008952 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008953 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 int pkgFlags = 0;
8955 String timeStampStr;
8956 long timeStamp = 0;
8957 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008958 String version = null;
8959 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 try {
8961 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008962 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008964 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8966 codePathStr = parser.getAttributeValue(null, "codePath");
8967 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008968 version = parser.getAttributeValue(null, "version");
8969 if (version != null) {
8970 try {
8971 versionCode = Integer.parseInt(version);
8972 } catch (NumberFormatException e) {
8973 }
8974 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008975 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008976
8977 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008979 try {
8980 pkgFlags = Integer.parseInt(systemStr);
8981 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008982 }
8983 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008984 // For backward compatibility
8985 systemStr = parser.getAttributeValue(null, "system");
8986 if (systemStr != null) {
8987 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8988 } else {
8989 // Old settings that don't specify system... just treat
8990 // them as system, good enough.
8991 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 }
8994 timeStampStr = parser.getAttributeValue(null, "ts");
8995 if (timeStampStr != null) {
8996 try {
8997 timeStamp = Long.parseLong(timeStampStr);
8998 } catch (NumberFormatException e) {
8999 }
9000 }
9001 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9002 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9003 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9004 if (resourcePathStr == null) {
9005 resourcePathStr = codePathStr;
9006 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009007 if (realName != null) {
9008 realName = realName.intern();
9009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 if (name == null) {
9011 reportSettingsProblem(Log.WARN,
9012 "Error in package manager settings: <package> has no name at "
9013 + parser.getPositionDescription());
9014 } else if (codePathStr == null) {
9015 reportSettingsProblem(Log.WARN,
9016 "Error in package manager settings: <package> has no codePath at "
9017 + parser.getPositionDescription());
9018 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009019 packageSetting = addPackageLP(name.intern(), realName,
9020 new File(codePathStr), new File(resourcePathStr),
9021 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009022 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9023 + ": userId=" + userId + " pkg=" + packageSetting);
9024 if (packageSetting == null) {
9025 reportSettingsProblem(Log.ERROR,
9026 "Failure adding uid " + userId
9027 + " while parsing settings at "
9028 + parser.getPositionDescription());
9029 } else {
9030 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9031 }
9032 } else if (sharedIdStr != null) {
9033 userId = sharedIdStr != null
9034 ? Integer.parseInt(sharedIdStr) : 0;
9035 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009036 packageSetting = new PendingPackage(name.intern(), realName,
9037 new File(codePathStr), new File(resourcePathStr),
9038 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9040 mPendingPackages.add((PendingPackage) packageSetting);
9041 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9042 + ": sharedUserId=" + userId + " pkg="
9043 + packageSetting);
9044 } else {
9045 reportSettingsProblem(Log.WARN,
9046 "Error in package manager settings: package "
9047 + name + " has bad sharedId " + sharedIdStr
9048 + " at " + parser.getPositionDescription());
9049 }
9050 } else {
9051 reportSettingsProblem(Log.WARN,
9052 "Error in package manager settings: package "
9053 + name + " has bad userId " + idStr + " at "
9054 + parser.getPositionDescription());
9055 }
9056 } catch (NumberFormatException e) {
9057 reportSettingsProblem(Log.WARN,
9058 "Error in package manager settings: package "
9059 + name + " has bad userId " + idStr + " at "
9060 + parser.getPositionDescription());
9061 }
9062 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009063 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009064 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 final String enabledStr = parser.getAttributeValue(null, "enabled");
9066 if (enabledStr != null) {
9067 if (enabledStr.equalsIgnoreCase("true")) {
9068 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9069 } else if (enabledStr.equalsIgnoreCase("false")) {
9070 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9071 } else if (enabledStr.equalsIgnoreCase("default")) {
9072 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9073 } else {
9074 reportSettingsProblem(Log.WARN,
9075 "Error in package manager settings: package "
9076 + name + " has bad enabled value: " + idStr
9077 + " at " + parser.getPositionDescription());
9078 }
9079 } else {
9080 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9081 }
9082 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9083 if (installStatusStr != null) {
9084 if (installStatusStr.equalsIgnoreCase("false")) {
9085 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9086 } else {
9087 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9088 }
9089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 int outerDepth = parser.getDepth();
9092 int type;
9093 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9094 && (type != XmlPullParser.END_TAG
9095 || parser.getDepth() > outerDepth)) {
9096 if (type == XmlPullParser.END_TAG
9097 || type == XmlPullParser.TEXT) {
9098 continue;
9099 }
9100
9101 String tagName = parser.getName();
9102 if (tagName.equals("disabled-components")) {
9103 readDisabledComponentsLP(packageSetting, parser);
9104 } else if (tagName.equals("enabled-components")) {
9105 readEnabledComponentsLP(packageSetting, parser);
9106 } else if (tagName.equals("sigs")) {
9107 packageSetting.signatures.readXml(parser, mPastSignatures);
9108 } else if (tagName.equals("perms")) {
9109 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009110 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 packageSetting.permissionsFixed = true;
9112 } else {
9113 reportSettingsProblem(Log.WARN,
9114 "Unknown element under <package>: "
9115 + parser.getName());
9116 XmlUtils.skipCurrentTag(parser);
9117 }
9118 }
9119 } else {
9120 XmlUtils.skipCurrentTag(parser);
9121 }
9122 }
9123
9124 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9125 XmlPullParser parser)
9126 throws IOException, XmlPullParserException {
9127 int outerDepth = parser.getDepth();
9128 int type;
9129 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9130 && (type != XmlPullParser.END_TAG
9131 || parser.getDepth() > outerDepth)) {
9132 if (type == XmlPullParser.END_TAG
9133 || type == XmlPullParser.TEXT) {
9134 continue;
9135 }
9136
9137 String tagName = parser.getName();
9138 if (tagName.equals("item")) {
9139 String name = parser.getAttributeValue(null, "name");
9140 if (name != null) {
9141 packageSetting.disabledComponents.add(name.intern());
9142 } else {
9143 reportSettingsProblem(Log.WARN,
9144 "Error in package manager settings: <disabled-components> has"
9145 + " no name at " + parser.getPositionDescription());
9146 }
9147 } else {
9148 reportSettingsProblem(Log.WARN,
9149 "Unknown element under <disabled-components>: "
9150 + parser.getName());
9151 }
9152 XmlUtils.skipCurrentTag(parser);
9153 }
9154 }
9155
9156 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9157 XmlPullParser parser)
9158 throws IOException, XmlPullParserException {
9159 int outerDepth = parser.getDepth();
9160 int type;
9161 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9162 && (type != XmlPullParser.END_TAG
9163 || parser.getDepth() > outerDepth)) {
9164 if (type == XmlPullParser.END_TAG
9165 || type == XmlPullParser.TEXT) {
9166 continue;
9167 }
9168
9169 String tagName = parser.getName();
9170 if (tagName.equals("item")) {
9171 String name = parser.getAttributeValue(null, "name");
9172 if (name != null) {
9173 packageSetting.enabledComponents.add(name.intern());
9174 } else {
9175 reportSettingsProblem(Log.WARN,
9176 "Error in package manager settings: <enabled-components> has"
9177 + " no name at " + parser.getPositionDescription());
9178 }
9179 } else {
9180 reportSettingsProblem(Log.WARN,
9181 "Unknown element under <enabled-components>: "
9182 + parser.getName());
9183 }
9184 XmlUtils.skipCurrentTag(parser);
9185 }
9186 }
9187
9188 private void readSharedUserLP(XmlPullParser parser)
9189 throws XmlPullParserException, IOException {
9190 String name = null;
9191 String idStr = null;
9192 int pkgFlags = 0;
9193 SharedUserSetting su = null;
9194 try {
9195 name = parser.getAttributeValue(null, "name");
9196 idStr = parser.getAttributeValue(null, "userId");
9197 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9198 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9199 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9200 }
9201 if (name == null) {
9202 reportSettingsProblem(Log.WARN,
9203 "Error in package manager settings: <shared-user> has no name at "
9204 + parser.getPositionDescription());
9205 } else if (userId == 0) {
9206 reportSettingsProblem(Log.WARN,
9207 "Error in package manager settings: shared-user "
9208 + name + " has bad userId " + idStr + " at "
9209 + parser.getPositionDescription());
9210 } else {
9211 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9212 reportSettingsProblem(Log.ERROR,
9213 "Occurred while parsing settings at "
9214 + parser.getPositionDescription());
9215 }
9216 }
9217 } catch (NumberFormatException e) {
9218 reportSettingsProblem(Log.WARN,
9219 "Error in package manager settings: package "
9220 + name + " has bad userId " + idStr + " at "
9221 + parser.getPositionDescription());
9222 };
9223
9224 if (su != null) {
9225 int outerDepth = parser.getDepth();
9226 int type;
9227 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9228 && (type != XmlPullParser.END_TAG
9229 || parser.getDepth() > outerDepth)) {
9230 if (type == XmlPullParser.END_TAG
9231 || type == XmlPullParser.TEXT) {
9232 continue;
9233 }
9234
9235 String tagName = parser.getName();
9236 if (tagName.equals("sigs")) {
9237 su.signatures.readXml(parser, mPastSignatures);
9238 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009239 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009240 } else {
9241 reportSettingsProblem(Log.WARN,
9242 "Unknown element under <shared-user>: "
9243 + parser.getName());
9244 XmlUtils.skipCurrentTag(parser);
9245 }
9246 }
9247
9248 } else {
9249 XmlUtils.skipCurrentTag(parser);
9250 }
9251 }
9252
9253 private void readGrantedPermissionsLP(XmlPullParser parser,
9254 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9255 int outerDepth = parser.getDepth();
9256 int type;
9257 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9258 && (type != XmlPullParser.END_TAG
9259 || parser.getDepth() > outerDepth)) {
9260 if (type == XmlPullParser.END_TAG
9261 || type == XmlPullParser.TEXT) {
9262 continue;
9263 }
9264
9265 String tagName = parser.getName();
9266 if (tagName.equals("item")) {
9267 String name = parser.getAttributeValue(null, "name");
9268 if (name != null) {
9269 outPerms.add(name.intern());
9270 } else {
9271 reportSettingsProblem(Log.WARN,
9272 "Error in package manager settings: <perms> has"
9273 + " no name at " + parser.getPositionDescription());
9274 }
9275 } else {
9276 reportSettingsProblem(Log.WARN,
9277 "Unknown element under <perms>: "
9278 + parser.getName());
9279 }
9280 XmlUtils.skipCurrentTag(parser);
9281 }
9282 }
9283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284 private void readPreferredActivitiesLP(XmlPullParser parser)
9285 throws XmlPullParserException, IOException {
9286 int outerDepth = parser.getDepth();
9287 int type;
9288 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9289 && (type != XmlPullParser.END_TAG
9290 || parser.getDepth() > outerDepth)) {
9291 if (type == XmlPullParser.END_TAG
9292 || type == XmlPullParser.TEXT) {
9293 continue;
9294 }
9295
9296 String tagName = parser.getName();
9297 if (tagName.equals("item")) {
9298 PreferredActivity pa = new PreferredActivity(parser);
9299 if (pa.mParseError == null) {
9300 mPreferredActivities.addFilter(pa);
9301 } else {
9302 reportSettingsProblem(Log.WARN,
9303 "Error in package manager settings: <preferred-activity> "
9304 + pa.mParseError + " at "
9305 + parser.getPositionDescription());
9306 }
9307 } else {
9308 reportSettingsProblem(Log.WARN,
9309 "Unknown element under <preferred-activities>: "
9310 + parser.getName());
9311 XmlUtils.skipCurrentTag(parser);
9312 }
9313 }
9314 }
9315
9316 // Returns -1 if we could not find an available UserId to assign
9317 private int newUserIdLP(Object obj) {
9318 // Let's be stupidly inefficient for now...
9319 final int N = mUserIds.size();
9320 for (int i=0; i<N; i++) {
9321 if (mUserIds.get(i) == null) {
9322 mUserIds.set(i, obj);
9323 return FIRST_APPLICATION_UID + i;
9324 }
9325 }
9326
9327 // None left?
9328 if (N >= MAX_APPLICATION_UIDS) {
9329 return -1;
9330 }
9331
9332 mUserIds.add(obj);
9333 return FIRST_APPLICATION_UID + N;
9334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 public PackageSetting getDisabledSystemPkg(String name) {
9337 synchronized(mPackages) {
9338 PackageSetting ps = mDisabledSysPackages.get(name);
9339 return ps;
9340 }
9341 }
9342
9343 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9344 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9345 if (Config.LOGV) {
9346 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9347 + " componentName = " + componentInfo.name);
9348 Log.v(TAG, "enabledComponents: "
9349 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9350 Log.v(TAG, "disabledComponents: "
9351 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9352 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009353 if (packageSettings == null) {
9354 if (false) {
9355 Log.w(TAG, "WAITING FOR DEBUGGER");
9356 Debug.waitForDebugger();
9357 Log.i(TAG, "We will crash!");
9358 }
9359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9361 || ((componentInfo.enabled
9362 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9363 || (componentInfo.applicationInfo.enabled
9364 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9365 && !packageSettings.disabledComponents.contains(componentInfo.name))
9366 || packageSettings.enabledComponents.contains(componentInfo.name));
9367 }
9368 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009369
9370 // ------- apps on sdcard specific code -------
9371 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009372 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009373 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009374 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009375 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009376
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009377 private String getEncryptKey() {
9378 try {
9379 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9380 if (sdEncKey == null) {
9381 sdEncKey = SystemKeyStore.getInstance().
9382 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9383 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009384 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009385 return null;
9386 }
9387 }
9388 return sdEncKey;
9389 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009390 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009391 return null;
9392 }
9393 }
9394
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009395 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009396 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009397 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009398 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009399 if (list != null) {
9400 int idx = 0;
9401 int idList[] = new int[MAX_CONTAINERS];
9402 boolean neverFound = true;
9403 for (String name : list) {
9404 // Ignore null entries
9405 if (name == null) {
9406 continue;
9407 }
9408 int sidx = name.indexOf(prefix);
9409 if (sidx == -1) {
9410 // Not a temp file. just ignore
9411 continue;
9412 }
9413 String subStr = name.substring(sidx + prefix.length());
9414 idList[idx] = -1;
9415 if (subStr != null) {
9416 try {
9417 int cid = Integer.parseInt(subStr);
9418 idList[idx++] = cid;
9419 neverFound = false;
9420 } catch (NumberFormatException e) {
9421 }
9422 }
9423 }
9424 if (!neverFound) {
9425 // Sort idList
9426 Arrays.sort(idList);
9427 for (int j = 1; j <= idList.length; j++) {
9428 if (idList[j-1] != j) {
9429 tmpIdx = j;
9430 break;
9431 }
9432 }
9433 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009434 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009435 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009436 }
9437
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009438 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009439 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009440 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009441 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9442 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9443 throw new SecurityException("Media status can only be updated by the system");
9444 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009445 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009446 Log.i(TAG, "Updating external media status from " +
9447 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9448 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009449 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9450 mediaStatus+", mMediaMounted=" + mMediaMounted);
9451 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009452 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9453 reportStatus ? 1 : 0, -1);
9454 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009455 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009456 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009457 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009458 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009459 // Queue up an async operation since the package installation may take a little while.
9460 mHandler.post(new Runnable() {
9461 public void run() {
9462 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009463 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009464 }
9465 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009466 }
9467
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009468 /*
9469 * Collect information of applications on external media, map them
9470 * against existing containers and update information based on current
9471 * mount status. Please note that we always have to report status
9472 * if reportStatus has been set to true especially when unloading packages.
9473 */
9474 private void updateExternalMediaStatusInner(boolean mediaStatus,
9475 boolean reportStatus) {
9476 // Collection of uids
9477 int uidArr[] = null;
9478 // Collection of stale containers
9479 HashSet<String> removeCids = new HashSet<String>();
9480 // Collection of packages on external media with valid containers.
9481 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9482 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009483 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009484 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009485 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009486 } else {
9487 // Process list of secure containers and categorize them
9488 // as active or stale based on their package internal state.
9489 int uidList[] = new int[list.length];
9490 int num = 0;
9491 synchronized (mPackages) {
9492 for (String cid : list) {
9493 SdInstallArgs args = new SdInstallArgs(cid);
9494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009495 String pkgName = args.getPackageName();
9496 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009497 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9498 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009499 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009500 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009501 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9502 PackageSetting ps = mSettings.mPackages.get(pkgName);
9503 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009504 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9506 " corresponds to pkg : " + pkgName +
9507 " at code path: " + ps.codePathString);
9508 // We do have a valid package installed on sdcard
9509 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009510 int uid = ps.userId;
9511 if (uid != -1) {
9512 uidList[num++] = uid;
9513 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009514 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009515 // Stale container on sdcard. Just delete
9516 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9517 removeCids.add(cid);
9518 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009519 }
9520 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009521
9522 if (num > 0) {
9523 // Sort uid list
9524 Arrays.sort(uidList, 0, num);
9525 // Throw away duplicates
9526 uidArr = new int[num];
9527 uidArr[0] = uidList[0];
9528 int di = 0;
9529 for (int i = 1; i < num; i++) {
9530 if (uidList[i-1] != uidList[i]) {
9531 uidArr[di++] = uidList[i];
9532 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009533 }
9534 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009535 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009536 // Process packages with valid entries.
9537 if (mediaStatus) {
9538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009539 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009540 startCleaningPackages();
9541 } else {
9542 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009543 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009544 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 }
9546
9547 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009548 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009549 int size = pkgList.size();
9550 if (size > 0) {
9551 // Send broadcasts here
9552 Bundle extras = new Bundle();
9553 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9554 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009555 if (uidArr != null) {
9556 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9557 }
9558 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9559 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009560 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009561 }
9562 }
9563
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 /*
9565 * Look at potentially valid container ids from processCids
9566 * If package information doesn't match the one on record
9567 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009568 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009569 */
9570 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009571 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 ArrayList<String> pkgList = new ArrayList<String>();
9573 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009575 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009576 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009577 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9578 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009579 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009580 try {
9581 // Make sure there are no container errors first.
9582 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9583 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009584 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009585 " when installing from sdcard");
9586 continue;
9587 }
9588 // Check code path here.
9589 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009590 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009591 " does not match one in settings " + codePath);
9592 continue;
9593 }
9594 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009595 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009598 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9599 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009600 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009601 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009602 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009603 retCode = PackageManager.INSTALL_SUCCEEDED;
9604 pkgList.add(pkg.packageName);
9605 // Post process args
9606 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9607 }
9608 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009609 Slog.i(TAG, "Failed to install pkg from " +
9610 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009611 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009612 }
9613
9614 } finally {
9615 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9616 // Don't destroy container here. Wait till gc clears things up.
9617 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009618 }
9619 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009620 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009621 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009622 // If the platform SDK has changed since the last time we booted,
9623 // we need to re-grant app permission to catch any new ones that
9624 // appear. This is really a hack, and means that apps can in some
9625 // cases get permissions that the user didn't initially explicitly
9626 // allow... it would be nice to have some better way to handle
9627 // this situation.
9628 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9629 != mSdkVersion;
9630 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9631 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9632 + "; regranting permissions for external storage");
9633 mSettings.mExternalSdkPlatform = mSdkVersion;
9634
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009635 // Make sure group IDs have been assigned, and any permission
9636 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009637 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009638 // Persist settings
9639 mSettings.writeLP();
9640 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009641 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009642 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009643 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009644 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009645 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009647 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009648 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009649 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009650 if (removeCids != null) {
9651 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009652 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009653 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009654 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009655 }
9656
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009657 /*
9658 * Utility method to unload a list of specified containers
9659 */
9660 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9661 // Just unmount all valid containers.
9662 for (SdInstallArgs arg : cidArgs) {
9663 synchronized (mInstallLock) {
9664 arg.doPostDeleteLI(false);
9665 }
9666 }
9667 }
9668
9669 /*
9670 * Unload packages mounted on external media. This involves deleting
9671 * package data from internal structures, sending broadcasts about
9672 * diabled packages, gc'ing to free up references, unmounting all
9673 * secure containers corresponding to packages on external media, and
9674 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9675 * Please note that we always have to post this message if status has
9676 * been requested no matter what.
9677 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009678 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009679 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009680 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009681 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009682 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009683 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009684 for (SdInstallArgs args : keys) {
9685 String cid = args.cid;
9686 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009687 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009688 // Delete package internally
9689 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9690 synchronized (mInstallLock) {
9691 boolean res = deletePackageLI(pkgName, false,
9692 PackageManager.DONT_DELETE_DATA, outInfo);
9693 if (res) {
9694 pkgList.add(pkgName);
9695 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009696 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009697 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009698 }
9699 }
9700 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009701 // We have to absolutely send UPDATED_MEDIA_STATUS only
9702 // after confirming that all the receivers processed the ordered
9703 // broadcast when packages get disabled, force a gc to clean things up.
9704 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009705 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009706 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9707 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9708 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009709 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9710 reportStatus ? 1 : 0, 1, keys);
9711 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009712 }
9713 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009714 } else {
9715 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9716 reportStatus ? 1 : 0, -1, keys);
9717 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009718 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009719 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009720
9721 public void movePackage(final String packageName,
9722 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009723 mContext.enforceCallingOrSelfPermission(
9724 android.Manifest.permission.MOVE_PACKAGE, null);
9725 int returnCode = PackageManager.MOVE_SUCCEEDED;
9726 int currFlags = 0;
9727 int newFlags = 0;
9728 synchronized (mPackages) {
9729 PackageParser.Package pkg = mPackages.get(packageName);
9730 if (pkg == null) {
9731 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009732 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009733 // Disable moving fwd locked apps and system packages
9734 if (pkg.applicationInfo != null &&
9735 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9736 Slog.w(TAG, "Cannot move system application");
9737 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9738 } else if (pkg.applicationInfo != null &&
9739 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9740 Slog.w(TAG, "Cannot move forward locked app.");
9741 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009742 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009743 // Find install location first
9744 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9745 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9746 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009747 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009748 } else {
9749 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9750 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9751 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9752 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9753 if (newFlags == currFlags) {
9754 Slog.w(TAG, "No move required. Trying to move to same location");
9755 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9756 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009757 }
9758 }
9759 }
9760 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9761 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9762 } else {
9763 Message msg = mHandler.obtainMessage(INIT_COPY);
9764 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9765 pkg.applicationInfo.publicSourceDir);
9766 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9767 packageName);
9768 msg.obj = mp;
9769 mHandler.sendMessage(msg);
9770 }
9771 }
9772 }
9773
9774 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9775 // Queue up an async operation since the package deletion may take a little while.
9776 mHandler.post(new Runnable() {
9777 public void run() {
9778 mHandler.removeCallbacks(this);
9779 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009780 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9781 int uidArr[] = null;
9782 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009783 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009784 PackageParser.Package pkg = mPackages.get(mp.packageName);
9785 if (pkg == null ) {
9786 Slog.w(TAG, " Package " + mp.packageName +
9787 " doesn't exist. Aborting move");
9788 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9789 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9790 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9791 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9792 " Aborting move and returning error");
9793 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9794 } else {
9795 uidArr = new int[] { pkg.applicationInfo.uid };
9796 pkgList = new ArrayList<String>();
9797 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009798 }
9799 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009800 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9801 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009802 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009803 // Update package code and resource paths
9804 synchronized (mInstallLock) {
9805 synchronized (mPackages) {
9806 PackageParser.Package pkg = mPackages.get(mp.packageName);
9807 // Recheck for package again.
9808 if (pkg == null ) {
9809 Slog.w(TAG, " Package " + mp.packageName +
9810 " doesn't exist. Aborting move");
9811 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9812 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9813 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9814 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9815 " Aborting move and returning error");
9816 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9817 } else {
9818 String oldCodePath = pkg.mPath;
9819 String newCodePath = mp.targetArgs.getCodePath();
9820 String newResPath = mp.targetArgs.getResourcePath();
9821 pkg.mPath = newCodePath;
9822 // Move dex files around
9823 if (moveDexFilesLI(pkg)
9824 != PackageManager.INSTALL_SUCCEEDED) {
9825 // Moving of dex files failed. Set
9826 // error code and abort move.
9827 pkg.mPath = pkg.mScanPath;
9828 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9829 } else {
9830 pkg.mScanPath = newCodePath;
9831 pkg.applicationInfo.sourceDir = newCodePath;
9832 pkg.applicationInfo.publicSourceDir = newResPath;
9833 PackageSetting ps = (PackageSetting) pkg.mExtras;
9834 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9835 ps.codePathString = ps.codePath.getPath();
9836 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9837 ps.resourcePathString = ps.resourcePath.getPath();
9838 // Set the application info flag correctly.
9839 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9840 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9841 } else {
9842 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9843 }
9844 ps.setFlags(pkg.applicationInfo.flags);
9845 mAppDirs.remove(oldCodePath);
9846 mAppDirs.put(newCodePath, pkg);
9847 // Persist settings
9848 mSettings.writeLP();
9849 }
9850 }
9851 }
9852 // Send resources available broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009853 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009854 }
9855 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009856 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009857 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009858 // Clean up failed installation
9859 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009860 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009861 }
9862 } else {
9863 // Force a gc to clear things up.
9864 Runtime.getRuntime().gc();
9865 // Delete older code
9866 synchronized (mInstallLock) {
9867 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009868 }
9869 }
9870 IPackageMoveObserver observer = mp.observer;
9871 if (observer != null) {
9872 try {
9873 observer.packageMoved(mp.packageName, returnCode);
9874 } catch (RemoteException e) {
9875 Log.i(TAG, "Observer no longer exists.");
9876 }
9877 }
9878 }
9879 });
9880 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009881
9882 public boolean setInstallLocation(int loc) {
9883 mContext.enforceCallingOrSelfPermission(
9884 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9885 if (getInstallLocation() == loc) {
9886 return true;
9887 }
9888 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9889 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9890 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9891 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9892 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9893 return true;
9894 }
9895 return false;
9896 }
9897
9898 public int getInstallLocation() {
9899 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9900 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009902}
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009903