blob: b1b4028e5cd24b418243191ee693c16d6766f77e [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.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080039import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070044import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.IPackageDataObserver;
46import android.content.pm.IPackageDeleteObserver;
47import android.content.pm.IPackageInstallObserver;
48import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080049import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.IPackageStatsObserver;
51import android.content.pm.InstrumentationInfo;
52import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080053import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
81import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700121/**
122 * Keep track of all those .apks everywhere.
123 *
124 * This is very central to the platform's security; please run the unit
125 * tests whenever making modifications here:
126 *
127mmm frameworks/base/tests/AndroidTests
128adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
129adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
130 *
131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132class PackageManagerService extends IPackageManager.Stub {
133 private static final String TAG = "PackageManager";
134 private static final boolean DEBUG_SETTINGS = false;
135 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800136 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
140 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400141 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int FIRST_APPLICATION_UID =
143 Process.FIRST_APPLICATION_UID;
144 private static final int MAX_APPLICATION_UIDS = 1000;
145
146 private static final boolean SHOW_INFO = false;
147
148 private static final boolean GET_CERTIFICATES = true;
149
150 private static final int REMOVE_EVENTS =
151 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
152 private static final int ADD_EVENTS =
153 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
154
155 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800156 // Suffix used during package installation when copying/moving
157 // package apks to install directory.
158 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800160 /**
161 * Indicates the state of installation. Used by PackageManager to
162 * figure out incomplete installations. Say a package is being installed
163 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
164 * the package installation is successful or unsuccesful lin which case
165 * the PackageManager will no longer maintain state information associated
166 * with the package. If some exception(like device freeze or battery being
167 * pulled out) occurs during installation of a package, the PackageManager
168 * needs this information to clean up the previously failed installation.
169 */
170 private static final int PKG_INSTALL_INCOMPLETE = 0;
171 private static final int PKG_INSTALL_COMPLETE = 1;
172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final int SCAN_MONITOR = 1<<0;
174 static final int SCAN_NO_DEX = 1<<1;
175 static final int SCAN_FORCE_DEX = 1<<2;
176 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800177 static final int SCAN_NEW_INSTALL = 1<<4;
178 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800180 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
181 "com.android.defcontainer",
182 "com.android.defcontainer.DefaultContainerService");
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
185 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700186 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn851a5412009-05-08 12:06:44 -0700188 final int mSdkVersion = Build.VERSION.SDK_INT;
189 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
190 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 final Context mContext;
193 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700194 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 final DisplayMetrics mMetrics;
196 final int mDefParseFlags;
197 final String[] mSeparateProcesses;
198
199 // This is where all application persistent data goes.
200 final File mAppDataDir;
201
202 // This is the object monitoring the framework dir.
203 final FileObserver mFrameworkInstallObserver;
204
205 // This is the object monitoring the system app dir.
206 final FileObserver mSystemInstallObserver;
207
208 // This is the object monitoring mAppInstallDir.
209 final FileObserver mAppInstallObserver;
210
211 // This is the object monitoring mDrmAppPrivateInstallDir.
212 final FileObserver mDrmAppInstallObserver;
213
214 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
215 // LOCK HELD. Can be called with mInstallLock held.
216 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 final File mFrameworkDir;
219 final File mSystemAppDir;
220 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700221 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
223 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
224 // apps.
225 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // Lock for state used when installing and doing other long running
230 // operations. Methods that must be called with this lock held have
231 // the prefix "LI".
232 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // These are the directories in the 3rd party applications installed dir
235 // that we have currently loaded packages from. Keys are the application's
236 // installed zip file (absolute codePath), and values are Package.
237 final HashMap<String, PackageParser.Package> mAppDirs =
238 new HashMap<String, PackageParser.Package>();
239
240 // Information for the parser to write more useful error messages.
241 File mScanningPath;
242 int mLastScanError;
243
244 final int[] mOutPermissions = new int[3];
245
246 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // Keys are String (package name), values are Package. This also serves
249 // as the lock for the global state. Methods that must be called with
250 // this lock held have the prefix "LP".
251 final HashMap<String, PackageParser.Package> mPackages =
252 new HashMap<String, PackageParser.Package>();
253
254 final Settings mSettings;
255 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
257 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
258 int[] mGlobalGids;
259
260 // These are the built-in uid -> permission mappings that were read from the
261 // etc/permissions.xml file.
262 final SparseArray<HashSet<String>> mSystemPermissions =
263 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // These are the built-in shared libraries that were read from the
266 // etc/permissions.xml file.
267 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
Dianne Hackborn49237342009-08-27 20:08:01 -0700269 // Temporary for building the final shared libraries for an .apk.
270 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800271
Dianne Hackborn49237342009-08-27 20:08:01 -0700272 // These are the features this devices supports that were read from the
273 // etc/permissions.xml file.
274 final HashMap<String, FeatureInfo> mAvailableFeatures =
275 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 // All available activities, for your resolving pleasure.
278 final ActivityIntentResolver mActivities =
279 new ActivityIntentResolver();
280
281 // All available receivers, for your resolving pleasure.
282 final ActivityIntentResolver mReceivers =
283 new ActivityIntentResolver();
284
285 // All available services, for your resolving pleasure.
286 final ServiceIntentResolver mServices = new ServiceIntentResolver();
287
288 // Keys are String (provider class name), values are Provider.
289 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
290 new HashMap<ComponentName, PackageParser.Provider>();
291
292 // Mapping from provider base names (first directory in content URI codePath)
293 // to the provider information.
294 final HashMap<String, PackageParser.Provider> mProviders =
295 new HashMap<String, PackageParser.Provider>();
296
297 // Mapping from instrumentation class names to info about them.
298 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
299 new HashMap<ComponentName, PackageParser.Instrumentation>();
300
301 // Mapping from permission names to info about them.
302 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
303 new HashMap<String, PackageParser.PermissionGroup>();
304
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800305 // Packages whose data we have transfered into another package, thus
306 // should no longer exist.
307 final HashSet<String> mTransferedPackages = new HashSet<String>();
308
Dianne Hackborn854060af2009-07-09 18:14:31 -0700309 // Broadcast actions that are only available to the system.
310 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 boolean mSystemReady;
313 boolean mSafeMode;
314 boolean mHasSystemUidErrors;
315
316 ApplicationInfo mAndroidApplication;
317 final ActivityInfo mResolveActivity = new ActivityInfo();
318 final ResolveInfo mResolveInfo = new ResolveInfo();
319 ComponentName mResolveComponentName;
320 PackageParser.Package mPlatformPackage;
321
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700322 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800323 final HashMap<String, ArrayList<String>> mPendingBroadcasts
324 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800325 // Service Connection to remote media container service to copy
326 // package uri's from external media onto secure containers
327 // or internal storage.
328 private IMediaContainerService mContainerService = null;
329
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700330 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800331 static final int MCS_BOUND = 3;
332 static final int END_COPY = 4;
333 static final int INIT_COPY = 5;
334 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800335 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800336 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800337 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800338 static final int MCS_RECONNECT = 10;
339 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700340 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700341 static final int WRITE_SETTINGS = 13;
342
343 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700345 // Delay time in millisecs
346 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347 final private DefaultContainerConnection mDefContainerConn =
348 new DefaultContainerConnection();
349 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800350 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 IMediaContainerService imcs =
353 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800354 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800355 }
356
357 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800358 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800359 }
360 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700361
Christopher Tate1bb69062010-02-19 17:02:12 -0800362 // Recordkeeping of restore-after-install operations that are currently in flight
363 // between the Package Manager and the Backup Manager
364 class PostInstallData {
365 public InstallArgs args;
366 public PackageInstalledInfo res;
367
368 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
369 args = _a;
370 res = _r;
371 }
372 };
373 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
374 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
375
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700376 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800377 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800378 final ArrayList<HandlerParams> mPendingInstalls =
379 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380
381 private boolean connectToService() {
382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
383 " DefaultContainerService");
384 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700385 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800386 if (mContext.bindService(service, mDefContainerConn,
387 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700388 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800389 mBound = true;
390 return true;
391 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700392 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800393 return false;
394 }
395
396 private void disconnectService() {
397 mContainerService = null;
398 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700401 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800403
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700404 PackageHandler(Looper looper) {
405 super(looper);
406 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700408 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 try {
410 doHandleMessage(msg);
411 } finally {
412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
413 }
414 }
415
416 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700417 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800418 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800420 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800421 int idx = mPendingInstalls.size();
422 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
423 // If a bind was already initiated we dont really
424 // need to do anything. The pending install
425 // will be processed later on.
426 if (!mBound) {
427 // If this is the only one pending we might
428 // have to bind to the service again.
429 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800430 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800431 params.serviceError();
432 return;
433 } else {
434 // Once we bind to the service, the first
435 // pending request will be processed.
436 mPendingInstalls.add(idx, params);
437 }
438 } else {
439 mPendingInstalls.add(idx, params);
440 // Already bound to the service. Just make
441 // sure we trigger off processing the first request.
442 if (idx == 0) {
443 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800444 }
445 }
446 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800447 }
448 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800449 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800450 if (msg.obj != null) {
451 mContainerService = (IMediaContainerService) msg.obj;
452 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 if (mContainerService == null) {
454 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800455 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 for (HandlerParams params : mPendingInstalls) {
457 mPendingInstalls.remove(0);
458 // Indicate service bind error
459 params.serviceError();
460 }
461 mPendingInstalls.clear();
462 } else if (mPendingInstalls.size() > 0) {
463 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800464 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800465 params.startCopy();
466 }
467 } else {
468 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800469 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 }
471 break;
472 }
473 case MCS_RECONNECT : {
474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
475 if (mPendingInstalls.size() > 0) {
476 if (mBound) {
477 disconnectService();
478 }
479 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 for (HandlerParams params : mPendingInstalls) {
482 mPendingInstalls.remove(0);
483 // Indicate service bind error
484 params.serviceError();
485 }
486 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800487 }
488 }
489 break;
490 }
491 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
493 // Delete pending install
494 if (mPendingInstalls.size() > 0) {
495 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800496 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800497 if (mPendingInstalls.size() == 0) {
498 if (mBound) {
499 disconnectService();
500 }
501 } else {
502 // There are more pending requests in queue.
503 // Just post MCS_BOUND message to trigger processing
504 // of next pending install.
505 mHandler.sendEmptyMessage(MCS_BOUND);
506 }
507 break;
508 }
509 case MCS_GIVE_UP: {
510 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
511 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 break;
513 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700514 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800515 String packages[];
516 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700517 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700518 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800521 if (mPendingBroadcasts == null) {
522 return;
523 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 size = mPendingBroadcasts.size();
525 if (size <= 0) {
526 // Nothing to be done. Just return
527 return;
528 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800529 packages = new String[size];
530 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 Iterator<HashMap.Entry<String, ArrayList<String>>>
533 it = mPendingBroadcasts.entrySet().iterator();
534 int i = 0;
535 while (it.hasNext() && i < size) {
536 HashMap.Entry<String, ArrayList<String>> ent = it.next();
537 packages[i] = ent.getKey();
538 components[i] = ent.getValue();
539 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800541 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 mPendingBroadcasts.clear();
545 }
546 // Send broadcasts
547 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800548 sendPackageChangedBroadcast(packages[i], true,
549 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700550 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700551 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 break;
553 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800554 case START_CLEANING_PACKAGE: {
555 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700556 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800557 synchronized (mPackages) {
558 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
559 mSettings.mPackagesToBeCleaned.add(packageName);
560 }
561 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700562 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800563 startCleaningPackages();
564 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800565 case POST_INSTALL: {
566 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
567 PostInstallData data = mRunningInstalls.get(msg.arg1);
568 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800569 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800570
571 if (data != null) {
572 InstallArgs args = data.args;
573 PackageInstalledInfo res = data.res;
574
575 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
576 res.removedInfo.sendBroadcast(false, true);
577 Bundle extras = new Bundle(1);
578 extras.putInt(Intent.EXTRA_UID, res.uid);
579 final boolean update = res.removedInfo.removedPackage != null;
580 if (update) {
581 extras.putBoolean(Intent.EXTRA_REPLACING, true);
582 }
583 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
584 res.pkg.applicationInfo.packageName,
585 extras);
586 if (update) {
587 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
588 res.pkg.applicationInfo.packageName,
589 extras);
590 }
591 if (res.removedInfo.args != null) {
592 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800593 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 }
595 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800596 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800598 // We delete after a gc for applications on sdcard.
599 if (deleteOld) {
600 synchronized (mInstallLock) {
601 res.removedInfo.args.doPostDeleteLI(true);
602 }
603 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800604 if (args.observer != null) {
605 try {
606 args.observer.packageInstalled(res.name, res.returnCode);
607 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800608 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800609 }
610 }
611 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800612 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800613 }
614 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700615 case UPDATED_MEDIA_STATUS: {
616 try {
617 PackageHelper.getMountService().finishMediaUpdate();
618 } catch (RemoteException e) {
619 Log.e(TAG, "MountService not running?");
620 }
621 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700622 case WRITE_SETTINGS: {
623 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
624 synchronized (mPackages) {
625 removeMessages(WRITE_SETTINGS);
626 mSettings.writeLP();
627 }
628 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
629 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700630 }
631 }
632 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800633
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700634 void scheduleWriteSettingsLocked() {
635 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
636 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
637 }
638 }
639
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800640 static boolean installOnSd(int flags) {
641 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700642 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800643 return false;
644 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700645 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
646 return true;
647 }
648 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800649 }
650
651 static boolean isFwdLocked(int flags) {
652 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
653 return true;
654 }
655 return false;
656 }
657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 public static final IPackageManager main(Context context, boolean factoryTest) {
659 PackageManagerService m = new PackageManagerService(context, factoryTest);
660 ServiceManager.addService("package", m);
661 return m;
662 }
663
664 static String[] splitString(String str, char sep) {
665 int count = 1;
666 int i = 0;
667 while ((i=str.indexOf(sep, i)) >= 0) {
668 count++;
669 i++;
670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 String[] res = new String[count];
673 i=0;
674 count = 0;
675 int lastI=0;
676 while ((i=str.indexOf(sep, i)) >= 0) {
677 res[count] = str.substring(lastI, i);
678 count++;
679 i++;
680 lastI = i;
681 }
682 res[count] = str.substring(lastI, str.length());
683 return res;
684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800687 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800691 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 mContext = context;
695 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700696 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 mMetrics = new DisplayMetrics();
698 mSettings = new Settings();
699 mSettings.addSharedUserLP("android.uid.system",
700 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
701 mSettings.addSharedUserLP("android.uid.phone",
702 MULTIPLE_APPLICATION_UIDS
703 ? RADIO_UID : FIRST_APPLICATION_UID,
704 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400705 mSettings.addSharedUserLP("android.uid.log",
706 MULTIPLE_APPLICATION_UIDS
707 ? LOG_UID : FIRST_APPLICATION_UID,
708 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
710 String separateProcesses = SystemProperties.get("debug.separate_processes");
711 if (separateProcesses != null && separateProcesses.length() > 0) {
712 if ("*".equals(separateProcesses)) {
713 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
714 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800715 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 } else {
717 mDefParseFlags = 0;
718 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800719 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 + separateProcesses);
721 }
722 } else {
723 mDefParseFlags = 0;
724 mSeparateProcesses = null;
725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 Installer installer = new Installer();
728 // Little hacky thing to check if installd is here, to determine
729 // whether we are running on the simulator and thus need to take
730 // care of building the /data file structure ourself.
731 // (apparently the sim now has a working installer)
732 if (installer.ping() && Process.supportsProcesses()) {
733 mInstaller = installer;
734 } else {
735 mInstaller = null;
736 }
737
738 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
739 Display d = wm.getDefaultDisplay();
740 d.getMetrics(mMetrics);
741
742 synchronized (mInstallLock) {
743 synchronized (mPackages) {
744 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700745 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 File dataDir = Environment.getDataDirectory();
748 mAppDataDir = new File(dataDir, "data");
749 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
750
751 if (mInstaller == null) {
752 // Make sure these dirs exist, when we are running in
753 // the simulator.
754 // Make a wide-open directory for random misc stuff.
755 File miscDir = new File(dataDir, "misc");
756 miscDir.mkdirs();
757 mAppDataDir.mkdirs();
758 mDrmAppPrivateInstallDir.mkdirs();
759 }
760
761 readPermissions();
762
763 mRestoredSettings = mSettings.readLP();
764 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
766 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800768
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800769 // Set flag to monitor and not change apk file paths when
770 // scanning install directories.
771 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700772 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800773 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800774 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700780 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700783 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 /**
786 * Out of paranoia, ensure that everything in the boot class
787 * path has been dexed.
788 */
789 String bootClassPath = System.getProperty("java.boot.class.path");
790 if (bootClassPath != null) {
791 String[] paths = splitString(bootClassPath, ':');
792 for (int i=0; i<paths.length; i++) {
793 try {
794 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
795 libFiles.add(paths[i]);
796 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700797 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 }
799 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800800 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 }
804 }
805 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800806 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 /**
810 * Also ensure all external libraries have had dexopt run on them.
811 */
812 if (mSharedLibraries.size() > 0) {
813 Iterator<String> libs = mSharedLibraries.values().iterator();
814 while (libs.hasNext()) {
815 String lib = libs.next();
816 try {
817 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
818 libFiles.add(lib);
819 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700820 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800823 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800825 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 // Gross hack for now: we know this file doesn't contain any
831 // code, so don't dexopt it to avoid the resulting log spew.
832 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 /**
835 * And there are a number of commands implemented in Java, which
836 * we currently need to do the dexopt on so that they can be
837 * run from a non-root shell.
838 */
839 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700840 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 for (int i=0; i<frameworkFiles.length; i++) {
842 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
843 String path = libPath.getPath();
844 // Skip the file if we alrady did it.
845 if (libFiles.contains(path)) {
846 continue;
847 }
848 // Skip the file if it is not a type we want to dexopt.
849 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
850 continue;
851 }
852 try {
853 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
854 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700855 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800858 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800860 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862 }
863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700865 if (didDexOpt) {
866 // If we had to do a dexopt of one of the previous
867 // things, then something on the system has changed.
868 // Consider this significant, and wipe away all other
869 // existing dexopt files to ensure we don't leave any
870 // dangling around.
871 String[] files = mDalvikCacheDir.list();
872 if (files != null) {
873 for (int i=0; i<files.length; i++) {
874 String fn = files[i];
875 if (fn.startsWith("data@app@")
876 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800877 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700878 (new File(mDalvikCacheDir, fn)).delete();
879 }
880 }
881 }
882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800884
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800885 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 mFrameworkInstallObserver = new AppDirObserver(
887 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
888 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700889 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
890 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800891 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800892
893 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
895 mSystemInstallObserver = new AppDirObserver(
896 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
897 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700898 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
899 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800900
901 if (mInstaller != null) {
902 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
903 mInstaller.moveFiles();
904 }
905
906 // Prune any system packages that no longer exist.
907 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
908 while (psit.hasNext()) {
909 PackageSetting ps = psit.next();
910 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800911 && !mPackages.containsKey(ps.name)
912 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800913 psit.remove();
914 String msg = "System package " + ps.name
915 + " no longer exists; wiping its data";
916 reportSettingsProblem(Log.WARN, msg);
917 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700918 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919 }
920 }
921 }
922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mAppInstallDir = new File(dataDir, "app");
924 if (mInstaller == null) {
925 // Make sure these dirs exist, when we are running in
926 // the simulator.
927 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
928 }
929 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800930 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 //clean up list
932 for(int i = 0; i < deletePkgsList.size(); i++) {
933 //clean up here
934 cleanupInstallFailedPackage(deletePkgsList.get(i));
935 }
936 //delete tmp files
937 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800938
939 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 SystemClock.uptimeMillis());
941 mAppInstallObserver = new AppDirObserver(
942 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
943 mAppInstallObserver.startWatching();
944 scanDirLI(mAppInstallDir, 0, scanMode);
945
946 mDrmAppInstallObserver = new AppDirObserver(
947 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
948 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800949 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800951 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800953 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 + ((SystemClock.uptimeMillis()-startTime)/1000f)
955 + " seconds");
956
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700957 // If the platform SDK has changed since the last time we booted,
958 // we need to re-grant app permission to catch any new ones that
959 // appear. This is really a hack, and means that apps can in some
960 // cases get permissions that the user didn't initially explicitly
961 // allow... it would be nice to have some better way to handle
962 // this situation.
963 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
964 != mSdkVersion;
965 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
966 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
967 + "; regranting permissions for internal storage");
968 mSettings.mInternalSdkPlatform = mSdkVersion;
969
970 updatePermissionsLP(null, null, true, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
972 mSettings.writeLP();
973
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800974 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 // Now after opening every single application zip, make sure they
978 // are all flushed. Not really needed, but keeps things nice and
979 // tidy.
980 Runtime.getRuntime().gc();
981 } // synchronized (mPackages)
982 } // synchronized (mInstallLock)
983 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 @Override
986 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
987 throws RemoteException {
988 try {
989 return super.onTransact(code, data, reply, flags);
990 } catch (RuntimeException e) {
991 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800992 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994 throw e;
995 }
996 }
997
Dianne Hackborne6620b22010-01-22 14:46:21 -0800998 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800999 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07001001 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001003 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001004 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
1006 } else {
1007 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001008 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 File dataDir = new File(pkg.applicationInfo.dataDir);
1010 dataDir.delete();
1011 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001012 if (ps.codePath != null) {
1013 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001014 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001015 }
1016 }
1017 if (ps.resourcePath != null) {
1018 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001019 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001020 }
1021 }
1022 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
1024
1025 void readPermissions() {
1026 // Read permissions from .../etc/permission directory.
1027 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1028 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001029 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 return;
1031 }
1032 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001033 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 return;
1035 }
1036
1037 // Iterate over the files in the directory and scan .xml files
1038 for (File f : libraryDir.listFiles()) {
1039 // We'll read platform.xml last
1040 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1041 continue;
1042 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001045 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 continue;
1047 }
1048 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001049 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 continue;
1051 }
1052
1053 readPermissionsFromXml(f);
1054 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1057 final File permFile = new File(Environment.getRootDirectory(),
1058 "etc/permissions/platform.xml");
1059 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001060
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001061 StringBuilder sb = new StringBuilder(128);
1062 sb.append("Libs:");
1063 Iterator<String> it = mSharedLibraries.keySet().iterator();
1064 while (it.hasNext()) {
1065 sb.append(' ');
1066 String name = it.next();
1067 sb.append(name);
1068 sb.append(':');
1069 sb.append(mSharedLibraries.get(name));
1070 }
1071 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001072
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001073 sb.setLength(0);
1074 sb.append("Features:");
1075 it = mAvailableFeatures.keySet().iterator();
1076 while (it.hasNext()) {
1077 sb.append(' ');
1078 sb.append(it.next());
1079 }
1080 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001082
1083 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 FileReader permReader = null;
1085 try {
1086 permReader = new FileReader(permFile);
1087 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001088 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 return;
1090 }
1091
1092 try {
1093 XmlPullParser parser = Xml.newPullParser();
1094 parser.setInput(permReader);
1095
1096 XmlUtils.beginDocument(parser, "permissions");
1097
1098 while (true) {
1099 XmlUtils.nextElement(parser);
1100 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1101 break;
1102 }
1103
1104 String name = parser.getName();
1105 if ("group".equals(name)) {
1106 String gidStr = parser.getAttributeValue(null, "gid");
1107 if (gidStr != null) {
1108 int gid = Integer.parseInt(gidStr);
1109 mGlobalGids = appendInt(mGlobalGids, gid);
1110 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001111 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 + parser.getPositionDescription());
1113 }
1114
1115 XmlUtils.skipCurrentTag(parser);
1116 continue;
1117 } else if ("permission".equals(name)) {
1118 String perm = parser.getAttributeValue(null, "name");
1119 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 + parser.getPositionDescription());
1122 XmlUtils.skipCurrentTag(parser);
1123 continue;
1124 }
1125 perm = perm.intern();
1126 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 } else if ("assign-permission".equals(name)) {
1129 String perm = parser.getAttributeValue(null, "name");
1130 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001131 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 + parser.getPositionDescription());
1133 XmlUtils.skipCurrentTag(parser);
1134 continue;
1135 }
1136 String uidStr = parser.getAttributeValue(null, "uid");
1137 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001138 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 + parser.getPositionDescription());
1140 XmlUtils.skipCurrentTag(parser);
1141 continue;
1142 }
1143 int uid = Process.getUidForName(uidStr);
1144 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001145 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 + uidStr + "\" at "
1147 + parser.getPositionDescription());
1148 XmlUtils.skipCurrentTag(parser);
1149 continue;
1150 }
1151 perm = perm.intern();
1152 HashSet<String> perms = mSystemPermissions.get(uid);
1153 if (perms == null) {
1154 perms = new HashSet<String>();
1155 mSystemPermissions.put(uid, perms);
1156 }
1157 perms.add(perm);
1158 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("library".equals(name)) {
1161 String lname = parser.getAttributeValue(null, "name");
1162 String lfile = parser.getAttributeValue(null, "file");
1163 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001164 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 + parser.getPositionDescription());
1166 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001167 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 + parser.getPositionDescription());
1169 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001170 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001171 mSharedLibraries.put(lname, lfile);
1172 }
1173 XmlUtils.skipCurrentTag(parser);
1174 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001175
Dianne Hackborn49237342009-08-27 20:08:01 -07001176 } else if ("feature".equals(name)) {
1177 String fname = parser.getAttributeValue(null, "name");
1178 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001179 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001180 + parser.getPositionDescription());
1181 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001182 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001183 FeatureInfo fi = new FeatureInfo();
1184 fi.name = fname;
1185 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
1187 XmlUtils.skipCurrentTag(parser);
1188 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 } else {
1191 XmlUtils.skipCurrentTag(parser);
1192 continue;
1193 }
1194
1195 }
1196 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001197 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 }
1201 }
1202
1203 void readPermission(XmlPullParser parser, String name)
1204 throws IOException, XmlPullParserException {
1205
1206 name = name.intern();
1207
1208 BasePermission bp = mSettings.mPermissions.get(name);
1209 if (bp == null) {
1210 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1211 mSettings.mPermissions.put(name, bp);
1212 }
1213 int outerDepth = parser.getDepth();
1214 int type;
1215 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1216 && (type != XmlPullParser.END_TAG
1217 || parser.getDepth() > outerDepth)) {
1218 if (type == XmlPullParser.END_TAG
1219 || type == XmlPullParser.TEXT) {
1220 continue;
1221 }
1222
1223 String tagName = parser.getName();
1224 if ("group".equals(tagName)) {
1225 String gidStr = parser.getAttributeValue(null, "gid");
1226 if (gidStr != null) {
1227 int gid = Process.getGidForName(gidStr);
1228 bp.gids = appendInt(bp.gids, gid);
1229 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001230 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 + parser.getPositionDescription());
1232 }
1233 }
1234 XmlUtils.skipCurrentTag(parser);
1235 }
1236 }
1237
1238 static int[] appendInt(int[] cur, int val) {
1239 if (cur == null) {
1240 return new int[] { val };
1241 }
1242 final int N = cur.length;
1243 for (int i=0; i<N; i++) {
1244 if (cur[i] == val) {
1245 return cur;
1246 }
1247 }
1248 int[] ret = new int[N+1];
1249 System.arraycopy(cur, 0, ret, 0, N);
1250 ret[N] = val;
1251 return ret;
1252 }
1253
1254 static int[] appendInts(int[] cur, int[] add) {
1255 if (add == null) return cur;
1256 if (cur == null) return add;
1257 final int N = add.length;
1258 for (int i=0; i<N; i++) {
1259 cur = appendInt(cur, add[i]);
1260 }
1261 return cur;
1262 }
1263
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001264 static int[] removeInt(int[] cur, int val) {
1265 if (cur == null) {
1266 return null;
1267 }
1268 final int N = cur.length;
1269 for (int i=0; i<N; i++) {
1270 if (cur[i] == val) {
1271 int[] ret = new int[N-1];
1272 if (i > 0) {
1273 System.arraycopy(cur, 0, ret, 0, i);
1274 }
1275 if (i < (N-1)) {
1276 System.arraycopy(cur, i, ret, i+1, N-i-1);
1277 }
1278 return ret;
1279 }
1280 }
1281 return cur;
1282 }
1283
1284 static int[] removeInts(int[] cur, int[] rem) {
1285 if (rem == null) return cur;
1286 if (cur == null) return cur;
1287 final int N = rem.length;
1288 for (int i=0; i<N; i++) {
1289 cur = removeInt(cur, rem[i]);
1290 }
1291 return cur;
1292 }
1293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001295 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1296 // The package has been uninstalled but has retained data and resources.
1297 return PackageParser.generatePackageInfo(p, null, flags);
1298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 final PackageSetting ps = (PackageSetting)p.mExtras;
1300 if (ps == null) {
1301 return null;
1302 }
1303 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1304 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1305 }
1306
1307 public PackageInfo getPackageInfo(String packageName, int flags) {
1308 synchronized (mPackages) {
1309 PackageParser.Package p = mPackages.get(packageName);
1310 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001311 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 + ": " + p);
1313 if (p != null) {
1314 return generatePackageInfo(p, flags);
1315 }
1316 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1317 return generatePackageInfoFromSettingsLP(packageName, flags);
1318 }
1319 }
1320 return null;
1321 }
1322
Dianne Hackborn47096932010-02-11 15:57:09 -08001323 public String[] currentToCanonicalPackageNames(String[] names) {
1324 String[] out = new String[names.length];
1325 synchronized (mPackages) {
1326 for (int i=names.length-1; i>=0; i--) {
1327 PackageSetting ps = mSettings.mPackages.get(names[i]);
1328 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1329 }
1330 }
1331 return out;
1332 }
1333
1334 public String[] canonicalToCurrentPackageNames(String[] names) {
1335 String[] out = new String[names.length];
1336 synchronized (mPackages) {
1337 for (int i=names.length-1; i>=0; i--) {
1338 String cur = mSettings.mRenamedPackages.get(names[i]);
1339 out[i] = cur != null ? cur : names[i];
1340 }
1341 }
1342 return out;
1343 }
1344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 public int getPackageUid(String packageName) {
1346 synchronized (mPackages) {
1347 PackageParser.Package p = mPackages.get(packageName);
1348 if(p != null) {
1349 return p.applicationInfo.uid;
1350 }
1351 PackageSetting ps = mSettings.mPackages.get(packageName);
1352 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1353 return -1;
1354 }
1355 p = ps.pkg;
1356 return p != null ? p.applicationInfo.uid : -1;
1357 }
1358 }
1359
1360 public int[] getPackageGids(String packageName) {
1361 synchronized (mPackages) {
1362 PackageParser.Package p = mPackages.get(packageName);
1363 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001364 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 + ": " + p);
1366 if (p != null) {
1367 final PackageSetting ps = (PackageSetting)p.mExtras;
1368 final SharedUserSetting suid = ps.sharedUser;
1369 return suid != null ? suid.gids : ps.gids;
1370 }
1371 }
1372 // stupid thing to indicate an error.
1373 return new int[0];
1374 }
1375
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001376 static final PermissionInfo generatePermissionInfo(
1377 BasePermission bp, int flags) {
1378 if (bp.perm != null) {
1379 return PackageParser.generatePermissionInfo(bp.perm, flags);
1380 }
1381 PermissionInfo pi = new PermissionInfo();
1382 pi.name = bp.name;
1383 pi.packageName = bp.sourcePackage;
1384 pi.nonLocalizedLabel = bp.name;
1385 pi.protectionLevel = bp.protectionLevel;
1386 return pi;
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 public PermissionInfo getPermissionInfo(String name, int flags) {
1390 synchronized (mPackages) {
1391 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001392 if (p != null) {
1393 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
1395 return null;
1396 }
1397 }
1398
1399 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1400 synchronized (mPackages) {
1401 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1402 for (BasePermission p : mSettings.mPermissions.values()) {
1403 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001404 if (p.perm == null || p.perm.info.group == null) {
1405 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 }
1407 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001408 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1410 }
1411 }
1412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 if (out.size() > 0) {
1415 return out;
1416 }
1417 return mPermissionGroups.containsKey(group) ? out : null;
1418 }
1419 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1422 synchronized (mPackages) {
1423 return PackageParser.generatePermissionGroupInfo(
1424 mPermissionGroups.get(name), flags);
1425 }
1426 }
1427
1428 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1429 synchronized (mPackages) {
1430 final int N = mPermissionGroups.size();
1431 ArrayList<PermissionGroupInfo> out
1432 = new ArrayList<PermissionGroupInfo>(N);
1433 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1434 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1435 }
1436 return out;
1437 }
1438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1441 PackageSetting ps = mSettings.mPackages.get(packageName);
1442 if(ps != null) {
1443 if(ps.pkg == null) {
1444 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1445 if(pInfo != null) {
1446 return pInfo.applicationInfo;
1447 }
1448 return null;
1449 }
1450 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1451 }
1452 return null;
1453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1456 PackageSetting ps = mSettings.mPackages.get(packageName);
1457 if(ps != null) {
1458 if(ps.pkg == null) {
1459 ps.pkg = new PackageParser.Package(packageName);
1460 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001461 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1462 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1463 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1464 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
1466 return generatePackageInfo(ps.pkg, flags);
1467 }
1468 return null;
1469 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1472 synchronized (mPackages) {
1473 PackageParser.Package p = mPackages.get(packageName);
1474 if (Config.LOGV) Log.v(
1475 TAG, "getApplicationInfo " + packageName
1476 + ": " + p);
1477 if (p != null) {
1478 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001479 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481 if ("android".equals(packageName)||"system".equals(packageName)) {
1482 return mAndroidApplication;
1483 }
1484 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1485 return generateApplicationInfoFromSettingsLP(packageName, flags);
1486 }
1487 }
1488 return null;
1489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001490
1491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1493 mContext.enforceCallingOrSelfPermission(
1494 android.Manifest.permission.CLEAR_APP_CACHE, null);
1495 // Queue up an async operation since clearing cache may take a little while.
1496 mHandler.post(new Runnable() {
1497 public void run() {
1498 mHandler.removeCallbacks(this);
1499 int retCode = -1;
1500 if (mInstaller != null) {
1501 retCode = mInstaller.freeCache(freeStorageSize);
1502 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001503 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505 } //end if mInstaller
1506 if (observer != null) {
1507 try {
1508 observer.onRemoveCompleted(null, (retCode >= 0));
1509 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001510 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
1513 }
1514 });
1515 }
1516
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001517 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001518 mContext.enforceCallingOrSelfPermission(
1519 android.Manifest.permission.CLEAR_APP_CACHE, null);
1520 // Queue up an async operation since clearing cache may take a little while.
1521 mHandler.post(new Runnable() {
1522 public void run() {
1523 mHandler.removeCallbacks(this);
1524 int retCode = -1;
1525 if (mInstaller != null) {
1526 retCode = mInstaller.freeCache(freeStorageSize);
1527 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001528 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001529 }
1530 }
1531 if(pi != null) {
1532 try {
1533 // Callback via pending intent
1534 int code = (retCode >= 0) ? 1 : 0;
1535 pi.sendIntent(null, code, null,
1536 null, null);
1537 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001538 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001539 }
1540 }
1541 }
1542 });
1543 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1546 synchronized (mPackages) {
1547 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001548
1549 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001551 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
1553 if (mResolveComponentName.equals(component)) {
1554 return mResolveActivity;
1555 }
1556 }
1557 return null;
1558 }
1559
1560 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1561 synchronized (mPackages) {
1562 PackageParser.Activity a = mReceivers.mActivities.get(component);
1563 if (Config.LOGV) Log.v(
1564 TAG, "getReceiverInfo " + component + ": " + a);
1565 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1566 return PackageParser.generateActivityInfo(a, flags);
1567 }
1568 }
1569 return null;
1570 }
1571
1572 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1573 synchronized (mPackages) {
1574 PackageParser.Service s = mServices.mServices.get(component);
1575 if (Config.LOGV) Log.v(
1576 TAG, "getServiceInfo " + component + ": " + s);
1577 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1578 return PackageParser.generateServiceInfo(s, flags);
1579 }
1580 }
1581 return null;
1582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 public String[] getSystemSharedLibraryNames() {
1585 Set<String> libSet;
1586 synchronized (mPackages) {
1587 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001588 int size = libSet.size();
1589 if (size > 0) {
1590 String[] libs = new String[size];
1591 libSet.toArray(libs);
1592 return libs;
1593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001595 return null;
1596 }
1597
1598 public FeatureInfo[] getSystemAvailableFeatures() {
1599 Collection<FeatureInfo> featSet;
1600 synchronized (mPackages) {
1601 featSet = mAvailableFeatures.values();
1602 int size = featSet.size();
1603 if (size > 0) {
1604 FeatureInfo[] features = new FeatureInfo[size+1];
1605 featSet.toArray(features);
1606 FeatureInfo fi = new FeatureInfo();
1607 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1608 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1609 features[size] = fi;
1610 return features;
1611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
1613 return null;
1614 }
1615
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001616 public boolean hasSystemFeature(String name) {
1617 synchronized (mPackages) {
1618 return mAvailableFeatures.containsKey(name);
1619 }
1620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 public int checkPermission(String permName, String pkgName) {
1623 synchronized (mPackages) {
1624 PackageParser.Package p = mPackages.get(pkgName);
1625 if (p != null && p.mExtras != null) {
1626 PackageSetting ps = (PackageSetting)p.mExtras;
1627 if (ps.sharedUser != null) {
1628 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1629 return PackageManager.PERMISSION_GRANTED;
1630 }
1631 } else if (ps.grantedPermissions.contains(permName)) {
1632 return PackageManager.PERMISSION_GRANTED;
1633 }
1634 }
1635 }
1636 return PackageManager.PERMISSION_DENIED;
1637 }
1638
1639 public int checkUidPermission(String permName, int uid) {
1640 synchronized (mPackages) {
1641 Object obj = mSettings.getUserIdLP(uid);
1642 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001643 GrantedPermissions gp = (GrantedPermissions)obj;
1644 if (gp.grantedPermissions.contains(permName)) {
1645 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 } else {
1648 HashSet<String> perms = mSystemPermissions.get(uid);
1649 if (perms != null && perms.contains(permName)) {
1650 return PackageManager.PERMISSION_GRANTED;
1651 }
1652 }
1653 }
1654 return PackageManager.PERMISSION_DENIED;
1655 }
1656
1657 private BasePermission findPermissionTreeLP(String permName) {
1658 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1659 if (permName.startsWith(bp.name) &&
1660 permName.length() > bp.name.length() &&
1661 permName.charAt(bp.name.length()) == '.') {
1662 return bp;
1663 }
1664 }
1665 return null;
1666 }
1667
1668 private BasePermission checkPermissionTreeLP(String permName) {
1669 if (permName != null) {
1670 BasePermission bp = findPermissionTreeLP(permName);
1671 if (bp != null) {
1672 if (bp.uid == Binder.getCallingUid()) {
1673 return bp;
1674 }
1675 throw new SecurityException("Calling uid "
1676 + Binder.getCallingUid()
1677 + " is not allowed to add to permission tree "
1678 + bp.name + " owned by uid " + bp.uid);
1679 }
1680 }
1681 throw new SecurityException("No permission tree found for " + permName);
1682 }
1683
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001684 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1685 if (s1 == null) {
1686 return s2 == null;
1687 }
1688 if (s2 == null) {
1689 return false;
1690 }
1691 if (s1.getClass() != s2.getClass()) {
1692 return false;
1693 }
1694 return s1.equals(s2);
1695 }
1696
1697 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1698 if (pi1.icon != pi2.icon) return false;
1699 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1700 if (!compareStrings(pi1.name, pi2.name)) return false;
1701 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1702 // We'll take care of setting this one.
1703 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1704 // These are not currently stored in settings.
1705 //if (!compareStrings(pi1.group, pi2.group)) return false;
1706 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1707 //if (pi1.labelRes != pi2.labelRes) return false;
1708 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1709 return true;
1710 }
1711
1712 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1713 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1714 throw new SecurityException("Label must be specified in permission");
1715 }
1716 BasePermission tree = checkPermissionTreeLP(info.name);
1717 BasePermission bp = mSettings.mPermissions.get(info.name);
1718 boolean added = bp == null;
1719 boolean changed = true;
1720 if (added) {
1721 bp = new BasePermission(info.name, tree.sourcePackage,
1722 BasePermission.TYPE_DYNAMIC);
1723 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1724 throw new SecurityException(
1725 "Not allowed to modify non-dynamic permission "
1726 + info.name);
1727 } else {
1728 if (bp.protectionLevel == info.protectionLevel
1729 && bp.perm.owner.equals(tree.perm.owner)
1730 && bp.uid == tree.uid
1731 && comparePermissionInfos(bp.perm.info, info)) {
1732 changed = false;
1733 }
1734 }
1735 bp.protectionLevel = info.protectionLevel;
1736 bp.perm = new PackageParser.Permission(tree.perm.owner,
1737 new PermissionInfo(info));
1738 bp.perm.info.packageName = tree.perm.info.packageName;
1739 bp.uid = tree.uid;
1740 if (added) {
1741 mSettings.mPermissions.put(info.name, bp);
1742 }
1743 if (changed) {
1744 if (!async) {
1745 mSettings.writeLP();
1746 } else {
1747 scheduleWriteSettingsLocked();
1748 }
1749 }
1750 return added;
1751 }
1752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 public boolean addPermission(PermissionInfo info) {
1754 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001755 return addPermissionLocked(info, false);
1756 }
1757 }
1758
1759 public boolean addPermissionAsync(PermissionInfo info) {
1760 synchronized (mPackages) {
1761 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
1763 }
1764
1765 public void removePermission(String name) {
1766 synchronized (mPackages) {
1767 checkPermissionTreeLP(name);
1768 BasePermission bp = mSettings.mPermissions.get(name);
1769 if (bp != null) {
1770 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1771 throw new SecurityException(
1772 "Not allowed to modify non-dynamic permission "
1773 + name);
1774 }
1775 mSettings.mPermissions.remove(name);
1776 mSettings.writeLP();
1777 }
1778 }
1779 }
1780
Dianne Hackborn854060af2009-07-09 18:14:31 -07001781 public boolean isProtectedBroadcast(String actionName) {
1782 synchronized (mPackages) {
1783 return mProtectedBroadcasts.contains(actionName);
1784 }
1785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 public int checkSignatures(String pkg1, String pkg2) {
1788 synchronized (mPackages) {
1789 PackageParser.Package p1 = mPackages.get(pkg1);
1790 PackageParser.Package p2 = mPackages.get(pkg2);
1791 if (p1 == null || p1.mExtras == null
1792 || p2 == null || p2.mExtras == null) {
1793 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1794 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001795 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
1797 }
1798
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001799 public int checkUidSignatures(int uid1, int uid2) {
1800 synchronized (mPackages) {
1801 Signature[] s1;
1802 Signature[] s2;
1803 Object obj = mSettings.getUserIdLP(uid1);
1804 if (obj != null) {
1805 if (obj instanceof SharedUserSetting) {
1806 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1807 } else if (obj instanceof PackageSetting) {
1808 s1 = ((PackageSetting)obj).signatures.mSignatures;
1809 } else {
1810 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1811 }
1812 } else {
1813 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1814 }
1815 obj = mSettings.getUserIdLP(uid2);
1816 if (obj != null) {
1817 if (obj instanceof SharedUserSetting) {
1818 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1819 } else if (obj instanceof PackageSetting) {
1820 s2 = ((PackageSetting)obj).signatures.mSignatures;
1821 } else {
1822 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1823 }
1824 } else {
1825 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1826 }
1827 return checkSignaturesLP(s1, s2);
1828 }
1829 }
1830
1831 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1832 if (s1 == null) {
1833 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1835 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1836 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001837 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1839 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001840 HashSet<Signature> set1 = new HashSet<Signature>();
1841 for (Signature sig : s1) {
1842 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001844 HashSet<Signature> set2 = new HashSet<Signature>();
1845 for (Signature sig : s2) {
1846 set2.add(sig);
1847 }
1848 // Make sure s2 contains all signatures in s1.
1849 if (set1.equals(set2)) {
1850 return PackageManager.SIGNATURE_MATCH;
1851 }
1852 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854
1855 public String[] getPackagesForUid(int uid) {
1856 synchronized (mPackages) {
1857 Object obj = mSettings.getUserIdLP(uid);
1858 if (obj instanceof SharedUserSetting) {
1859 SharedUserSetting sus = (SharedUserSetting)obj;
1860 final int N = sus.packages.size();
1861 String[] res = new String[N];
1862 Iterator<PackageSetting> it = sus.packages.iterator();
1863 int i=0;
1864 while (it.hasNext()) {
1865 res[i++] = it.next().name;
1866 }
1867 return res;
1868 } else if (obj instanceof PackageSetting) {
1869 PackageSetting ps = (PackageSetting)obj;
1870 return new String[] { ps.name };
1871 }
1872 }
1873 return null;
1874 }
1875
1876 public String getNameForUid(int uid) {
1877 synchronized (mPackages) {
1878 Object obj = mSettings.getUserIdLP(uid);
1879 if (obj instanceof SharedUserSetting) {
1880 SharedUserSetting sus = (SharedUserSetting)obj;
1881 return sus.name + ":" + sus.userId;
1882 } else if (obj instanceof PackageSetting) {
1883 PackageSetting ps = (PackageSetting)obj;
1884 return ps.name;
1885 }
1886 }
1887 return null;
1888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 public int getUidForSharedUser(String sharedUserName) {
1891 if(sharedUserName == null) {
1892 return -1;
1893 }
1894 synchronized (mPackages) {
1895 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1896 if(suid == null) {
1897 return -1;
1898 }
1899 return suid.userId;
1900 }
1901 }
1902
1903 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1904 int flags) {
1905 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001906 return chooseBestActivity(intent, resolvedType, flags, query);
1907 }
1908
Mihai Predaeae850c2009-05-13 10:13:48 +02001909 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1910 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 if (query != null) {
1912 final int N = query.size();
1913 if (N == 1) {
1914 return query.get(0);
1915 } else if (N > 1) {
1916 // If there is more than one activity with the same priority,
1917 // then let the user decide between them.
1918 ResolveInfo r0 = query.get(0);
1919 ResolveInfo r1 = query.get(1);
1920 if (false) {
1921 System.out.println(r0.activityInfo.name +
1922 "=" + r0.priority + " vs " +
1923 r1.activityInfo.name +
1924 "=" + r1.priority);
1925 }
1926 // If the first activity has a higher priority, or a different
1927 // default, then it is always desireable to pick it.
1928 if (r0.priority != r1.priority
1929 || r0.preferredOrder != r1.preferredOrder
1930 || r0.isDefault != r1.isDefault) {
1931 return query.get(0);
1932 }
1933 // If we have saved a preference for a preferred activity for
1934 // this Intent, use that.
1935 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1936 flags, query, r0.priority);
1937 if (ri != null) {
1938 return ri;
1939 }
1940 return mResolveInfo;
1941 }
1942 }
1943 return null;
1944 }
1945
1946 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1947 int flags, List<ResolveInfo> query, int priority) {
1948 synchronized (mPackages) {
1949 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1950 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001951 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1953 if (prefs != null && prefs.size() > 0) {
1954 // First figure out how good the original match set is.
1955 // We will only allow preferred activities that came
1956 // from the same match quality.
1957 int match = 0;
1958 final int N = query.size();
1959 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1960 for (int j=0; j<N; j++) {
1961 ResolveInfo ri = query.get(j);
1962 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1963 + ": 0x" + Integer.toHexString(match));
1964 if (ri.match > match) match = ri.match;
1965 }
1966 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1967 + Integer.toHexString(match));
1968 match &= IntentFilter.MATCH_CATEGORY_MASK;
1969 final int M = prefs.size();
1970 for (int i=0; i<M; i++) {
1971 PreferredActivity pa = prefs.get(i);
1972 if (pa.mMatch != match) {
1973 continue;
1974 }
1975 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1976 if (DEBUG_PREFERRED) {
1977 Log.v(TAG, "Got preferred activity:");
1978 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1979 }
1980 if (ai != null) {
1981 for (int j=0; j<N; j++) {
1982 ResolveInfo ri = query.get(j);
1983 if (!ri.activityInfo.applicationInfo.packageName
1984 .equals(ai.applicationInfo.packageName)) {
1985 continue;
1986 }
1987 if (!ri.activityInfo.name.equals(ai.name)) {
1988 continue;
1989 }
1990
1991 // Okay we found a previously set preferred app.
1992 // If the result set is different from when this
1993 // was created, we need to clear it and re-ask the
1994 // user their preference.
1995 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001996 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 + intent + " type " + resolvedType);
1998 mSettings.mPreferredActivities.removeFilter(pa);
1999 return null;
2000 }
2001
2002 // Yay!
2003 return ri;
2004 }
2005 }
2006 }
2007 }
2008 }
2009 return null;
2010 }
2011
2012 public List<ResolveInfo> queryIntentActivities(Intent intent,
2013 String resolvedType, int flags) {
2014 ComponentName comp = intent.getComponent();
2015 if (comp != null) {
2016 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2017 ActivityInfo ai = getActivityInfo(comp, flags);
2018 if (ai != null) {
2019 ResolveInfo ri = new ResolveInfo();
2020 ri.activityInfo = ai;
2021 list.add(ri);
2022 }
2023 return list;
2024 }
2025
2026 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002027 String pkgName = intent.getPackage();
2028 if (pkgName == null) {
2029 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2030 resolvedType, flags);
2031 }
2032 PackageParser.Package pkg = mPackages.get(pkgName);
2033 if (pkg != null) {
2034 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2035 resolvedType, flags, pkg.activities);
2036 }
2037 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 }
2039 }
2040
2041 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2042 Intent[] specifics, String[] specificTypes, Intent intent,
2043 String resolvedType, int flags) {
2044 final String resultsAction = intent.getAction();
2045
2046 List<ResolveInfo> results = queryIntentActivities(
2047 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2048 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2049
2050 int specificsPos = 0;
2051 int N;
2052
2053 // todo: note that the algorithm used here is O(N^2). This
2054 // isn't a problem in our current environment, but if we start running
2055 // into situations where we have more than 5 or 10 matches then this
2056 // should probably be changed to something smarter...
2057
2058 // First we go through and resolve each of the specific items
2059 // that were supplied, taking care of removing any corresponding
2060 // duplicate items in the generic resolve list.
2061 if (specifics != null) {
2062 for (int i=0; i<specifics.length; i++) {
2063 final Intent sintent = specifics[i];
2064 if (sintent == null) {
2065 continue;
2066 }
2067
2068 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2069 String action = sintent.getAction();
2070 if (resultsAction != null && resultsAction.equals(action)) {
2071 // If this action was explicitly requested, then don't
2072 // remove things that have it.
2073 action = null;
2074 }
2075 ComponentName comp = sintent.getComponent();
2076 ResolveInfo ri = null;
2077 ActivityInfo ai = null;
2078 if (comp == null) {
2079 ri = resolveIntent(
2080 sintent,
2081 specificTypes != null ? specificTypes[i] : null,
2082 flags);
2083 if (ri == null) {
2084 continue;
2085 }
2086 if (ri == mResolveInfo) {
2087 // ACK! Must do something better with this.
2088 }
2089 ai = ri.activityInfo;
2090 comp = new ComponentName(ai.applicationInfo.packageName,
2091 ai.name);
2092 } else {
2093 ai = getActivityInfo(comp, flags);
2094 if (ai == null) {
2095 continue;
2096 }
2097 }
2098
2099 // Look for any generic query activities that are duplicates
2100 // of this specific one, and remove them from the results.
2101 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2102 N = results.size();
2103 int j;
2104 for (j=specificsPos; j<N; j++) {
2105 ResolveInfo sri = results.get(j);
2106 if ((sri.activityInfo.name.equals(comp.getClassName())
2107 && sri.activityInfo.applicationInfo.packageName.equals(
2108 comp.getPackageName()))
2109 || (action != null && sri.filter.matchAction(action))) {
2110 results.remove(j);
2111 if (Config.LOGV) Log.v(
2112 TAG, "Removing duplicate item from " + j
2113 + " due to specific " + specificsPos);
2114 if (ri == null) {
2115 ri = sri;
2116 }
2117 j--;
2118 N--;
2119 }
2120 }
2121
2122 // Add this specific item to its proper place.
2123 if (ri == null) {
2124 ri = new ResolveInfo();
2125 ri.activityInfo = ai;
2126 }
2127 results.add(specificsPos, ri);
2128 ri.specificIndex = i;
2129 specificsPos++;
2130 }
2131 }
2132
2133 // Now we go through the remaining generic results and remove any
2134 // duplicate actions that are found here.
2135 N = results.size();
2136 for (int i=specificsPos; i<N-1; i++) {
2137 final ResolveInfo rii = results.get(i);
2138 if (rii.filter == null) {
2139 continue;
2140 }
2141
2142 // Iterate over all of the actions of this result's intent
2143 // filter... typically this should be just one.
2144 final Iterator<String> it = rii.filter.actionsIterator();
2145 if (it == null) {
2146 continue;
2147 }
2148 while (it.hasNext()) {
2149 final String action = it.next();
2150 if (resultsAction != null && resultsAction.equals(action)) {
2151 // If this action was explicitly requested, then don't
2152 // remove things that have it.
2153 continue;
2154 }
2155 for (int j=i+1; j<N; j++) {
2156 final ResolveInfo rij = results.get(j);
2157 if (rij.filter != null && rij.filter.hasAction(action)) {
2158 results.remove(j);
2159 if (Config.LOGV) Log.v(
2160 TAG, "Removing duplicate item from " + j
2161 + " due to action " + action + " at " + i);
2162 j--;
2163 N--;
2164 }
2165 }
2166 }
2167
2168 // If the caller didn't request filter information, drop it now
2169 // so we don't have to marshall/unmarshall it.
2170 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2171 rii.filter = null;
2172 }
2173 }
2174
2175 // Filter out the caller activity if so requested.
2176 if (caller != null) {
2177 N = results.size();
2178 for (int i=0; i<N; i++) {
2179 ActivityInfo ainfo = results.get(i).activityInfo;
2180 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2181 && caller.getClassName().equals(ainfo.name)) {
2182 results.remove(i);
2183 break;
2184 }
2185 }
2186 }
2187
2188 // If the caller didn't request filter information,
2189 // drop them now so we don't have to
2190 // marshall/unmarshall it.
2191 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2192 N = results.size();
2193 for (int i=0; i<N; i++) {
2194 results.get(i).filter = null;
2195 }
2196 }
2197
2198 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2199 return results;
2200 }
2201
2202 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2203 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002204 ComponentName comp = intent.getComponent();
2205 if (comp != null) {
2206 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2207 ActivityInfo ai = getReceiverInfo(comp, flags);
2208 if (ai != null) {
2209 ResolveInfo ri = new ResolveInfo();
2210 ri.activityInfo = ai;
2211 list.add(ri);
2212 }
2213 return list;
2214 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002217 String pkgName = intent.getPackage();
2218 if (pkgName == null) {
2219 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2220 resolvedType, flags);
2221 }
2222 PackageParser.Package pkg = mPackages.get(pkgName);
2223 if (pkg != null) {
2224 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2225 resolvedType, flags, pkg.receivers);
2226 }
2227 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229 }
2230
2231 public ResolveInfo resolveService(Intent intent, String resolvedType,
2232 int flags) {
2233 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2234 flags);
2235 if (query != null) {
2236 if (query.size() >= 1) {
2237 // If there is more than one service with the same priority,
2238 // just arbitrarily pick the first one.
2239 return query.get(0);
2240 }
2241 }
2242 return null;
2243 }
2244
2245 public List<ResolveInfo> queryIntentServices(Intent intent,
2246 String resolvedType, int flags) {
2247 ComponentName comp = intent.getComponent();
2248 if (comp != null) {
2249 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2250 ServiceInfo si = getServiceInfo(comp, flags);
2251 if (si != null) {
2252 ResolveInfo ri = new ResolveInfo();
2253 ri.serviceInfo = si;
2254 list.add(ri);
2255 }
2256 return list;
2257 }
2258
2259 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002260 String pkgName = intent.getPackage();
2261 if (pkgName == null) {
2262 return (List<ResolveInfo>)mServices.queryIntent(intent,
2263 resolvedType, flags);
2264 }
2265 PackageParser.Package pkg = mPackages.get(pkgName);
2266 if (pkg != null) {
2267 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2268 resolvedType, flags, pkg.services);
2269 }
2270 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
2272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 public List<PackageInfo> getInstalledPackages(int flags) {
2275 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2276
2277 synchronized (mPackages) {
2278 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2279 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2280 while (i.hasNext()) {
2281 final PackageSetting ps = i.next();
2282 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2283 if(psPkg != null) {
2284 finalList.add(psPkg);
2285 }
2286 }
2287 }
2288 else {
2289 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2290 while (i.hasNext()) {
2291 final PackageParser.Package p = i.next();
2292 if (p.applicationInfo != null) {
2293 PackageInfo pi = generatePackageInfo(p, flags);
2294 if(pi != null) {
2295 finalList.add(pi);
2296 }
2297 }
2298 }
2299 }
2300 }
2301 return finalList;
2302 }
2303
2304 public List<ApplicationInfo> getInstalledApplications(int flags) {
2305 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2306 synchronized(mPackages) {
2307 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2308 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2309 while (i.hasNext()) {
2310 final PackageSetting ps = i.next();
2311 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2312 if(ai != null) {
2313 finalList.add(ai);
2314 }
2315 }
2316 }
2317 else {
2318 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2319 while (i.hasNext()) {
2320 final PackageParser.Package p = i.next();
2321 if (p.applicationInfo != null) {
2322 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2323 if(ai != null) {
2324 finalList.add(ai);
2325 }
2326 }
2327 }
2328 }
2329 }
2330 return finalList;
2331 }
2332
2333 public List<ApplicationInfo> getPersistentApplications(int flags) {
2334 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2335
2336 synchronized (mPackages) {
2337 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2338 while (i.hasNext()) {
2339 PackageParser.Package p = i.next();
2340 if (p.applicationInfo != null
2341 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2342 && (!mSafeMode || (p.applicationInfo.flags
2343 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2344 finalList.add(p.applicationInfo);
2345 }
2346 }
2347 }
2348
2349 return finalList;
2350 }
2351
2352 public ProviderInfo resolveContentProvider(String name, int flags) {
2353 synchronized (mPackages) {
2354 final PackageParser.Provider provider = mProviders.get(name);
2355 return provider != null
2356 && mSettings.isEnabledLP(provider.info, flags)
2357 && (!mSafeMode || (provider.info.applicationInfo.flags
2358 &ApplicationInfo.FLAG_SYSTEM) != 0)
2359 ? PackageParser.generateProviderInfo(provider, flags)
2360 : null;
2361 }
2362 }
2363
Fred Quintana718d8a22009-04-29 17:53:20 -07002364 /**
2365 * @deprecated
2366 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 public void querySyncProviders(List outNames, List outInfo) {
2368 synchronized (mPackages) {
2369 Iterator<Map.Entry<String, PackageParser.Provider>> i
2370 = mProviders.entrySet().iterator();
2371
2372 while (i.hasNext()) {
2373 Map.Entry<String, PackageParser.Provider> entry = i.next();
2374 PackageParser.Provider p = entry.getValue();
2375
2376 if (p.syncable
2377 && (!mSafeMode || (p.info.applicationInfo.flags
2378 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2379 outNames.add(entry.getKey());
2380 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2381 }
2382 }
2383 }
2384 }
2385
2386 public List<ProviderInfo> queryContentProviders(String processName,
2387 int uid, int flags) {
2388 ArrayList<ProviderInfo> finalList = null;
2389
2390 synchronized (mPackages) {
2391 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2392 while (i.hasNext()) {
2393 PackageParser.Provider p = i.next();
2394 if (p.info.authority != null
2395 && (processName == null ||
2396 (p.info.processName.equals(processName)
2397 && p.info.applicationInfo.uid == uid))
2398 && mSettings.isEnabledLP(p.info, flags)
2399 && (!mSafeMode || (p.info.applicationInfo.flags
2400 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2401 if (finalList == null) {
2402 finalList = new ArrayList<ProviderInfo>(3);
2403 }
2404 finalList.add(PackageParser.generateProviderInfo(p,
2405 flags));
2406 }
2407 }
2408 }
2409
2410 if (finalList != null) {
2411 Collections.sort(finalList, mProviderInitOrderSorter);
2412 }
2413
2414 return finalList;
2415 }
2416
2417 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2418 int flags) {
2419 synchronized (mPackages) {
2420 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2421 return PackageParser.generateInstrumentationInfo(i, flags);
2422 }
2423 }
2424
2425 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2426 int flags) {
2427 ArrayList<InstrumentationInfo> finalList =
2428 new ArrayList<InstrumentationInfo>();
2429
2430 synchronized (mPackages) {
2431 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2432 while (i.hasNext()) {
2433 PackageParser.Instrumentation p = i.next();
2434 if (targetPackage == null
2435 || targetPackage.equals(p.info.targetPackage)) {
2436 finalList.add(PackageParser.generateInstrumentationInfo(p,
2437 flags));
2438 }
2439 }
2440 }
2441
2442 return finalList;
2443 }
2444
2445 private void scanDirLI(File dir, int flags, int scanMode) {
2446 Log.d(TAG, "Scanning app dir " + dir);
2447
2448 String[] files = dir.list();
2449
2450 int i;
2451 for (i=0; i<files.length; i++) {
2452 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002453 if (!isPackageFilename(files[i])) {
2454 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002455 continue;
2456 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002457 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002459 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002460 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2461 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002462 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002463 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002464 file.delete();
2465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 }
2467 }
2468
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002469 private static File getSettingsProblemFile() {
2470 File dataDir = Environment.getDataDirectory();
2471 File systemDir = new File(dataDir, "system");
2472 File fname = new File(systemDir, "uiderrors.txt");
2473 return fname;
2474 }
2475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 private static void reportSettingsProblem(int priority, String msg) {
2477 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002478 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 FileOutputStream out = new FileOutputStream(fname, true);
2480 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002481 SimpleDateFormat formatter = new SimpleDateFormat();
2482 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2483 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 pw.close();
2485 FileUtils.setPermissions(
2486 fname.toString(),
2487 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2488 -1, -1);
2489 } catch (java.io.IOException e) {
2490 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002491 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 }
2493
2494 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2495 PackageParser.Package pkg, File srcFile, int parseFlags) {
2496 if (GET_CERTIFICATES) {
2497 if (ps == null || !ps.codePath.equals(srcFile)
2498 || ps.getTimeStamp() != srcFile.lastModified()) {
2499 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2500 if (!pp.collectCertificates(pkg, parseFlags)) {
2501 mLastScanError = pp.getParseError();
2502 return false;
2503 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002504 } else {
2505 // Lets implicitly assign existing certificates.
2506 pkg.mSignatures = ps.signatures.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 }
2508 }
2509 return true;
2510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 /*
2513 * Scan a package and return the newly parsed package.
2514 * Returns null in case of errors and the error code is stored in mLastScanError
2515 */
2516 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002517 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002519 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002521 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002524 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 if (pkg == null) {
2526 mLastScanError = pp.getParseError();
2527 return null;
2528 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002529 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 PackageSetting updatedPkg;
2531 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002532 // Look to see if we already know about this package.
2533 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002534 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002535 // This package has been renamed to its original name. Let's
2536 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002537 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002538 }
2539 // If there was no original package, see one for the real package name.
2540 if (ps == null) {
2541 ps = mSettings.peekPackageLP(pkg.packageName);
2542 }
2543 // Check to see if this package could be hiding/updating a system
2544 // package. Must look for it either under the original or real
2545 // package name depending on our state.
2546 updatedPkg = mSettings.mDisabledSysPackages.get(
2547 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002549 // First check if this is a system package that may involve an update
2550 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2551 if (!ps.codePath.equals(scanFile)) {
2552 // The path has changed from what was last scanned... check the
2553 // version of the new path against what we have stored to determine
2554 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002555 if (pkg.mVersionCode < ps.versionCode) {
2556 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002557 // Ignore entry. Skip it.
2558 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2559 + "ignored: updated version " + ps.versionCode
2560 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002561 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2562 return null;
2563 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002564 // The current app on the system partion is better than
2565 // what we have updated to on the data partition; switch
2566 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002567 // At this point, its safely assumed that package installation for
2568 // apps in system partition will go through. If not there won't be a working
2569 // version of the app
2570 synchronized (mPackages) {
2571 // Just remove the loaded entries from package lists.
2572 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002573 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002574 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 + "reverting from " + ps.codePathString
2576 + ": new version " + pkg.mVersionCode
2577 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2579 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002580 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 }
2583 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 if (updatedPkg != null) {
2585 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2586 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2587 }
2588 // Verify certificates against what was last scanned
2589 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002590 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 return null;
2592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 // The apk is forward locked (not public) if its code and resources
2594 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002595 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002597 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002598 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002599
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002600 String codePath = null;
2601 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002602 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2603 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002604 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002605 } else {
2606 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002607 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002608 }
2609 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002610 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002611 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002612 codePath = pkg.mScanPath;
2613 // Set application objects path explicitly.
2614 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002616 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 }
2618
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002619 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2620 String destCodePath, String destResPath) {
2621 pkg.mPath = pkg.mScanPath = destCodePath;
2622 pkg.applicationInfo.sourceDir = destCodePath;
2623 pkg.applicationInfo.publicSourceDir = destResPath;
2624 }
2625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 private static String fixProcessName(String defProcessName,
2627 String processName, int uid) {
2628 if (processName == null) {
2629 return defProcessName;
2630 }
2631 return processName;
2632 }
2633
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002634 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002635 PackageParser.Package pkg) {
2636 if (pkgSetting.signatures.mSignatures != null) {
2637 // Already existing package. Make sure signatures match
2638 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2639 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002640 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002641 + " signatures do not match the previously installed version; ignoring!");
2642 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 return false;
2644 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002645 }
2646 // Check for shared user signatures
2647 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2648 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2649 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2650 Slog.e(TAG, "Package " + pkg.packageName
2651 + " has no signatures that match those in shared user "
2652 + pkgSetting.sharedUser.name + "; ignoring!");
2653 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2654 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 }
2657 return true;
2658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002659
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002660 public boolean performDexOpt(String packageName) {
2661 if (!mNoDexOpt) {
2662 return false;
2663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002664
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002665 PackageParser.Package p;
2666 synchronized (mPackages) {
2667 p = mPackages.get(packageName);
2668 if (p == null || p.mDidDexOpt) {
2669 return false;
2670 }
2671 }
2672 synchronized (mInstallLock) {
2673 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2674 }
2675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002676
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002677 static final int DEX_OPT_SKIPPED = 0;
2678 static final int DEX_OPT_PERFORMED = 1;
2679 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002680
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002681 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2682 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002683 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002684 String path = pkg.mScanPath;
2685 int ret = 0;
2686 try {
2687 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002688 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002689 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002690 pkg.mDidDexOpt = true;
2691 performed = true;
2692 }
2693 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002694 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002695 ret = -1;
2696 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002697 Slog.w(TAG, "IOException reading apk: " + path, e);
2698 ret = -1;
2699 } catch (dalvik.system.StaleDexCacheError e) {
2700 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2701 ret = -1;
2702 } catch (Exception e) {
2703 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002704 ret = -1;
2705 }
2706 if (ret < 0) {
2707 //error from installer
2708 return DEX_OPT_FAILED;
2709 }
2710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002711
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002712 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2713 }
2714
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002715 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2716 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002717 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002718 + " to " + newPkg.packageName
2719 + ": old package not in system partition");
2720 return false;
2721 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002722 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002723 + " to " + newPkg.packageName
2724 + ": old package still exists");
2725 return false;
2726 }
2727 return true;
2728 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002729
2730 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002731 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002732 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002733
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002734 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2735 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002736 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002737 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2738 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002739 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002740 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002741 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2742 return null;
2743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 mScanningPath = scanFile;
2745 if (pkg == null) {
2746 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2747 return null;
2748 }
2749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002750 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2751 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2752 }
2753
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002754 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 synchronized (mPackages) {
2756 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002757 Slog.w(TAG, "*************************************************");
2758 Slog.w(TAG, "Core android package being redefined. Skipping.");
2759 Slog.w(TAG, " file=" + mScanningPath);
2760 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2762 return null;
2763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 // Set up information for our fall-back user intent resolution
2766 // activity.
2767 mPlatformPackage = pkg;
2768 pkg.mVersionCode = mSdkVersion;
2769 mAndroidApplication = pkg.applicationInfo;
2770 mResolveActivity.applicationInfo = mAndroidApplication;
2771 mResolveActivity.name = ResolverActivity.class.getName();
2772 mResolveActivity.packageName = mAndroidApplication.packageName;
2773 mResolveActivity.processName = mAndroidApplication.processName;
2774 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2775 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2776 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2777 mResolveActivity.exported = true;
2778 mResolveActivity.enabled = true;
2779 mResolveInfo.activityInfo = mResolveActivity;
2780 mResolveInfo.priority = 0;
2781 mResolveInfo.preferredOrder = 0;
2782 mResolveInfo.match = 0;
2783 mResolveComponentName = new ComponentName(
2784 mAndroidApplication.packageName, mResolveActivity.name);
2785 }
2786 }
2787
2788 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002789 TAG, "Scanning package " + pkg.packageName);
2790 if (mPackages.containsKey(pkg.packageName)
2791 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002792 Slog.w(TAG, "*************************************************");
2793 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002795 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2797 return null;
2798 }
2799
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002800 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002801 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2802 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 SharedUserSetting suid = null;
2805 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002806
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002807 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2808 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002809 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002810 pkg.mRealPackage = null;
2811 pkg.mAdoptPermissions = null;
2812 }
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 synchronized (mPackages) {
2815 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002816 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2817 if (mTmpSharedLibraries == null ||
2818 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2819 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2820 }
2821 int num = 0;
2822 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2823 for (int i=0; i<N; i++) {
2824 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002826 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002828 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2830 return null;
2831 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002832 mTmpSharedLibraries[num] = file;
2833 num++;
2834 }
2835 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2836 for (int i=0; i<N; i++) {
2837 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2838 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002839 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002840 + " desires unavailable shared library "
2841 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2842 } else {
2843 mTmpSharedLibraries[num] = file;
2844 num++;
2845 }
2846 }
2847 if (num > 0) {
2848 pkg.usesLibraryFiles = new String[num];
2849 System.arraycopy(mTmpSharedLibraries, 0,
2850 pkg.usesLibraryFiles, 0, num);
2851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002852
Dianne Hackborn49237342009-08-27 20:08:01 -07002853 if (pkg.reqFeatures != null) {
2854 N = pkg.reqFeatures.size();
2855 for (int i=0; i<N; i++) {
2856 FeatureInfo fi = pkg.reqFeatures.get(i);
2857 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2858 // Don't care.
2859 continue;
2860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002861
Dianne Hackborn49237342009-08-27 20:08:01 -07002862 if (fi.name != null) {
2863 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002864 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002865 + " requires unavailable feature "
2866 + fi.name + "; failing!");
2867 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2868 return null;
2869 }
2870 }
2871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 }
2873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 if (pkg.mSharedUserId != null) {
2876 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2877 pkg.applicationInfo.flags, true);
2878 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002879 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 + " for shared user failed");
2881 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2882 return null;
2883 }
2884 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2885 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2886 + suid.userId + "): packages=" + suid.packages);
2887 }
2888 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002889
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002890 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002891 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002892 Log.w(TAG, "WAITING FOR DEBUGGER");
2893 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002894 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2895 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002896 }
2897 }
2898
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002899 // Check if we are renaming from an original package name.
2900 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002901 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002902 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002903 // This package may need to be renamed to a previously
2904 // installed name. Let's check on that...
2905 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002906 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002907 // This package had originally been installed as the
2908 // original name, and we have already taken care of
2909 // transitioning to the new one. Just update the new
2910 // one to continue using the old name.
2911 realName = pkg.mRealPackage;
2912 if (!pkg.packageName.equals(renamed)) {
2913 // Callers into this function may have already taken
2914 // care of renaming the package; only do it here if
2915 // it is not already done.
2916 pkg.setPackageName(renamed);
2917 }
2918
Dianne Hackbornc1552392010-03-03 16:19:01 -08002919 } else {
2920 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2921 if ((origPackage=mSettings.peekPackageLP(
2922 pkg.mOriginalPackages.get(i))) != null) {
2923 // We do have the package already installed under its
2924 // original name... should we use it?
2925 if (!verifyPackageUpdate(origPackage, pkg)) {
2926 // New package is not compatible with original.
2927 origPackage = null;
2928 continue;
2929 } else if (origPackage.sharedUser != null) {
2930 // Make sure uid is compatible between packages.
2931 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002932 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002933 + " to " + pkg.packageName + ": old uid "
2934 + origPackage.sharedUser.name
2935 + " differs from " + pkg.mSharedUserId);
2936 origPackage = null;
2937 continue;
2938 }
2939 } else {
2940 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2941 + pkg.packageName + " to old name " + origPackage.name);
2942 }
2943 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002944 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002945 }
2946 }
2947 }
2948
2949 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002950 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002951 + " was transferred to another, but its .apk remains");
2952 }
2953
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002954 // Just create the setting, don't add it yet. For already existing packages
2955 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002956 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 destResourceFile, pkg.applicationInfo.flags, true, false);
2958 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002959 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2961 return null;
2962 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002963
2964 if (pkgSetting.origPackage != null) {
2965 // If we are first transitioning from an original package,
2966 // fix up the new package's name now. We need to do this after
2967 // looking up the package under its new name, so getPackageLP
2968 // can take care of fiddling things correctly.
2969 pkg.setPackageName(origPackage.name);
2970
2971 // File a report about this.
2972 String msg = "New package " + pkgSetting.realName
2973 + " renamed to replace old package " + pkgSetting.name;
2974 reportSettingsProblem(Log.WARN, msg);
2975
2976 // Make a note of it.
2977 mTransferedPackages.add(origPackage.name);
2978
2979 // No longer need to retain this.
2980 pkgSetting.origPackage = null;
2981 }
2982
2983 if (realName != null) {
2984 // Make a note of it.
2985 mTransferedPackages.add(pkg.packageName);
2986 }
2987
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002988 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 pkg.applicationInfo.uid = pkgSetting.userId;
2993 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002994
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002995 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002996 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 return null;
2998 }
2999 // The signature has changed, but this package is in the system
3000 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003001 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 // However... if this package is part of a shared user, but it
3003 // doesn't match the signature of the shared user, let's fail.
3004 // What this means is that you can't change the signatures
3005 // associated with an overall shared user, which doesn't seem all
3006 // that unreasonable.
3007 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003008 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3009 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3010 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3012 return null;
3013 }
3014 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003015 // File a report about this.
3016 String msg = "System package " + pkg.packageName
3017 + " signature changed; retaining data.";
3018 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003020
The Android Open Source Project10592532009-03-18 17:39:46 -07003021 // Verify that this new package doesn't have any content providers
3022 // that conflict with existing packages. Only do this if the
3023 // package isn't already installed, since we don't want to break
3024 // things that are installed.
3025 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3026 int N = pkg.providers.size();
3027 int i;
3028 for (i=0; i<N; i++) {
3029 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003030 if (p.info.authority != null) {
3031 String names[] = p.info.authority.split(";");
3032 for (int j = 0; j < names.length; j++) {
3033 if (mProviders.containsKey(names[j])) {
3034 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003035 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003036 " (in package " + pkg.applicationInfo.packageName +
3037 ") is already used by "
3038 + ((other != null && other.getComponentName() != null)
3039 ? other.getComponentName().getPackageName() : "?"));
3040 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3041 return null;
3042 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003043 }
3044 }
3045 }
3046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
3048
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003049 final String pkgName = pkg.packageName;
3050
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003051 if (pkg.mAdoptPermissions != null) {
3052 // This package wants to adopt ownership of permissions from
3053 // another package.
3054 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3055 String origName = pkg.mAdoptPermissions.get(i);
3056 PackageSetting orig = mSettings.peekPackageLP(origName);
3057 if (orig != null) {
3058 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003059 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003060 + origName + " to " + pkg.packageName);
3061 mSettings.transferPermissions(origName, pkg.packageName);
3062 }
3063 }
3064 }
3065 }
3066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 long scanFileTime = scanFile.lastModified();
3068 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3069 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3070 pkg.applicationInfo.processName = fixProcessName(
3071 pkg.applicationInfo.packageName,
3072 pkg.applicationInfo.processName,
3073 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074
3075 File dataPath;
3076 if (mPlatformPackage == pkg) {
3077 // The system package is special.
3078 dataPath = new File (Environment.getDataDirectory(), "system");
3079 pkg.applicationInfo.dataDir = dataPath.getPath();
3080 } else {
3081 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003082 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003083
3084 boolean uidError = false;
3085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 if (dataPath.exists()) {
3087 mOutPermissions[1] = 0;
3088 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3089 if (mOutPermissions[1] == pkg.applicationInfo.uid
3090 || !Process.supportsProcesses()) {
3091 pkg.applicationInfo.dataDir = dataPath.getPath();
3092 } else {
3093 boolean recovered = false;
3094 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3095 // If this is a system app, we can at least delete its
3096 // current data so the application will still work.
3097 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003098 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003099 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 // Old data gone!
3101 String msg = "System package " + pkg.packageName
3102 + " has changed from uid: "
3103 + mOutPermissions[1] + " to "
3104 + pkg.applicationInfo.uid + "; old data erased";
3105 reportSettingsProblem(Log.WARN, msg);
3106 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003109 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 pkg.applicationInfo.uid);
3111 if (ret == -1) {
3112 // Ack should not happen!
3113 msg = "System package " + pkg.packageName
3114 + " could not have data directory re-created after delete.";
3115 reportSettingsProblem(Log.WARN, msg);
3116 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3117 return null;
3118 }
3119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 if (!recovered) {
3122 mHasSystemUidErrors = true;
3123 }
3124 }
3125 if (!recovered) {
3126 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3127 + pkg.applicationInfo.uid + "/fs_"
3128 + mOutPermissions[1];
3129 String msg = "Package " + pkg.packageName
3130 + " has mismatched uid: "
3131 + mOutPermissions[1] + " on disk, "
3132 + pkg.applicationInfo.uid + " in settings";
3133 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003134 mSettings.mReadMessages.append(msg);
3135 mSettings.mReadMessages.append('\n');
3136 uidError = true;
3137 if (!pkgSetting.uidError) {
3138 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 }
3141 }
3142 }
3143 pkg.applicationInfo.dataDir = dataPath.getPath();
3144 } else {
3145 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3146 Log.v(TAG, "Want this data dir: " + dataPath);
3147 //invoke installer to do the actual installation
3148 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003149 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 pkg.applicationInfo.uid);
3151 if(ret < 0) {
3152 // Error from installer
3153 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3154 return null;
3155 }
3156 } else {
3157 dataPath.mkdirs();
3158 if (dataPath.exists()) {
3159 FileUtils.setPermissions(
3160 dataPath.toString(),
3161 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3162 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3163 }
3164 }
3165 if (dataPath.exists()) {
3166 pkg.applicationInfo.dataDir = dataPath.getPath();
3167 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003168 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 pkg.applicationInfo.dataDir = null;
3170 }
3171 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003172
3173 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 }
3175
3176 // Perform shared library installation and dex validation and
3177 // optimization, if this is not a system app.
3178 if (mInstaller != null) {
3179 String path = scanFile.getPath();
3180 if (scanFileNewer) {
3181 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003182 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3183 if (err != PackageManager.INSTALL_SUCCEEDED) {
3184 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 return null;
3186 }
3187 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003188 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003190 if ((scanMode&SCAN_NO_DEX) == 0) {
3191 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3193 return null;
3194 }
3195 }
3196 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 if (mFactoryTest && pkg.requestedPermissions.contains(
3199 android.Manifest.permission.FACTORY_TEST)) {
3200 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3201 }
3202
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003203 // Request the ActivityManager to kill the process(only for existing packages)
3204 // so that we do not end up in a confused state while the user is still using the older
3205 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003206 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003207 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003208 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003209 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003212 // We don't expect installation to fail beyond this point,
3213 if ((scanMode&SCAN_MONITOR) != 0) {
3214 mAppDirs.put(pkg.mPath, pkg);
3215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003217 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003219 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003220 // Make sure we don't accidentally delete its data.
3221 mSettings.mPackagesToBeCleaned.remove(pkgName);
3222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 int N = pkg.providers.size();
3224 StringBuilder r = null;
3225 int i;
3226 for (i=0; i<N; i++) {
3227 PackageParser.Provider p = pkg.providers.get(i);
3228 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3229 p.info.processName, pkg.applicationInfo.uid);
3230 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3231 p.info.name), p);
3232 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003233 if (p.info.authority != null) {
3234 String names[] = p.info.authority.split(";");
3235 p.info.authority = null;
3236 for (int j = 0; j < names.length; j++) {
3237 if (j == 1 && p.syncable) {
3238 // We only want the first authority for a provider to possibly be
3239 // syncable, so if we already added this provider using a different
3240 // authority clear the syncable flag. We copy the provider before
3241 // changing it because the mProviders object contains a reference
3242 // to a provider that we don't want to change.
3243 // Only do this for the second authority since the resulting provider
3244 // object can be the same for all future authorities for this provider.
3245 p = new PackageParser.Provider(p);
3246 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003248 if (!mProviders.containsKey(names[j])) {
3249 mProviders.put(names[j], p);
3250 if (p.info.authority == null) {
3251 p.info.authority = names[j];
3252 } else {
3253 p.info.authority = p.info.authority + ";" + names[j];
3254 }
3255 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3256 Log.d(TAG, "Registered content provider: " + names[j] +
3257 ", className = " + p.info.name +
3258 ", isSyncable = " + p.info.isSyncable);
3259 } else {
3260 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003261 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003262 " (in package " + pkg.applicationInfo.packageName +
3263 "): name already used by "
3264 + ((other != null && other.getComponentName() != null)
3265 ? other.getComponentName().getPackageName() : "?"));
3266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 }
3268 }
3269 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3270 if (r == null) {
3271 r = new StringBuilder(256);
3272 } else {
3273 r.append(' ');
3274 }
3275 r.append(p.info.name);
3276 }
3277 }
3278 if (r != null) {
3279 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 N = pkg.services.size();
3283 r = null;
3284 for (i=0; i<N; i++) {
3285 PackageParser.Service s = pkg.services.get(i);
3286 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3287 s.info.processName, pkg.applicationInfo.uid);
3288 mServices.addService(s);
3289 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3290 if (r == null) {
3291 r = new StringBuilder(256);
3292 } else {
3293 r.append(' ');
3294 }
3295 r.append(s.info.name);
3296 }
3297 }
3298 if (r != null) {
3299 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 N = pkg.receivers.size();
3303 r = null;
3304 for (i=0; i<N; i++) {
3305 PackageParser.Activity a = pkg.receivers.get(i);
3306 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3307 a.info.processName, pkg.applicationInfo.uid);
3308 mReceivers.addActivity(a, "receiver");
3309 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3310 if (r == null) {
3311 r = new StringBuilder(256);
3312 } else {
3313 r.append(' ');
3314 }
3315 r.append(a.info.name);
3316 }
3317 }
3318 if (r != null) {
3319 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3320 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 N = pkg.activities.size();
3323 r = null;
3324 for (i=0; i<N; i++) {
3325 PackageParser.Activity a = pkg.activities.get(i);
3326 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3327 a.info.processName, pkg.applicationInfo.uid);
3328 mActivities.addActivity(a, "activity");
3329 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3330 if (r == null) {
3331 r = new StringBuilder(256);
3332 } else {
3333 r.append(' ');
3334 }
3335 r.append(a.info.name);
3336 }
3337 }
3338 if (r != null) {
3339 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 N = pkg.permissionGroups.size();
3343 r = null;
3344 for (i=0; i<N; i++) {
3345 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3346 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3347 if (cur == null) {
3348 mPermissionGroups.put(pg.info.name, pg);
3349 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3350 if (r == null) {
3351 r = new StringBuilder(256);
3352 } else {
3353 r.append(' ');
3354 }
3355 r.append(pg.info.name);
3356 }
3357 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003358 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 + pg.info.packageName + " ignored: original from "
3360 + cur.info.packageName);
3361 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3362 if (r == null) {
3363 r = new StringBuilder(256);
3364 } else {
3365 r.append(' ');
3366 }
3367 r.append("DUP:");
3368 r.append(pg.info.name);
3369 }
3370 }
3371 }
3372 if (r != null) {
3373 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3374 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 N = pkg.permissions.size();
3377 r = null;
3378 for (i=0; i<N; i++) {
3379 PackageParser.Permission p = pkg.permissions.get(i);
3380 HashMap<String, BasePermission> permissionMap =
3381 p.tree ? mSettings.mPermissionTrees
3382 : mSettings.mPermissions;
3383 p.group = mPermissionGroups.get(p.info.group);
3384 if (p.info.group == null || p.group != null) {
3385 BasePermission bp = permissionMap.get(p.info.name);
3386 if (bp == null) {
3387 bp = new BasePermission(p.info.name, p.info.packageName,
3388 BasePermission.TYPE_NORMAL);
3389 permissionMap.put(p.info.name, bp);
3390 }
3391 if (bp.perm == null) {
3392 if (bp.sourcePackage == null
3393 || bp.sourcePackage.equals(p.info.packageName)) {
3394 BasePermission tree = findPermissionTreeLP(p.info.name);
3395 if (tree == null
3396 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003397 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 bp.perm = p;
3399 bp.uid = pkg.applicationInfo.uid;
3400 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3401 if (r == null) {
3402 r = new StringBuilder(256);
3403 } else {
3404 r.append(' ');
3405 }
3406 r.append(p.info.name);
3407 }
3408 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003409 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 + p.info.packageName + " ignored: base tree "
3411 + tree.name + " is from package "
3412 + tree.sourcePackage);
3413 }
3414 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003415 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 + p.info.packageName + " ignored: original from "
3417 + bp.sourcePackage);
3418 }
3419 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3420 if (r == null) {
3421 r = new StringBuilder(256);
3422 } else {
3423 r.append(' ');
3424 }
3425 r.append("DUP:");
3426 r.append(p.info.name);
3427 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003428 if (bp.perm == p) {
3429 bp.protectionLevel = p.info.protectionLevel;
3430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003432 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 + p.info.packageName + " ignored: no group "
3434 + p.group);
3435 }
3436 }
3437 if (r != null) {
3438 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3439 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 N = pkg.instrumentation.size();
3442 r = null;
3443 for (i=0; i<N; i++) {
3444 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3445 a.info.packageName = pkg.applicationInfo.packageName;
3446 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3447 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3448 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003449 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3451 if (r == null) {
3452 r = new StringBuilder(256);
3453 } else {
3454 r.append(' ');
3455 }
3456 r.append(a.info.name);
3457 }
3458 }
3459 if (r != null) {
3460 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003462
Dianne Hackborn854060af2009-07-09 18:14:31 -07003463 if (pkg.protectedBroadcasts != null) {
3464 N = pkg.protectedBroadcasts.size();
3465 for (i=0; i<N; i++) {
3466 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3467 }
3468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 pkgSetting.setTimeStamp(scanFileTime);
3471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 return pkg;
3474 }
3475
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003476 private void killApplication(String pkgName, int uid) {
3477 // Request the ActivityManager to kill the process(only for existing packages)
3478 // so that we do not end up in a confused state while the user is still using the older
3479 // version of the application while the new one gets installed.
3480 IActivityManager am = ActivityManagerNative.getDefault();
3481 if (am != null) {
3482 try {
3483 am.killApplicationWithUid(pkgName, uid);
3484 } catch (RemoteException e) {
3485 }
3486 }
3487 }
3488
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003489 // The following constants are returned by cachePackageSharedLibsForAbiLI
3490 // to indicate if native shared libraries were found in the package.
3491 // Values are:
3492 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3493 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3494 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3495 // in package (and not installed)
3496 //
3497 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3498 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3499 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003501 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3502 // and automatically copy them to /data/data/<appname>/lib if present.
3503 //
3504 // NOTE: this method may throw an IOException if the library cannot
3505 // be copied to its final destination, e.g. if there isn't enough
3506 // room left on the data partition, or a ZipException if the package
3507 // file is malformed.
3508 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003509 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3510 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003511 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3512 final String apkLib = "lib/";
3513 final int apkLibLen = apkLib.length();
3514 final int cpuAbiLen = cpuAbi.length();
3515 final String libPrefix = "lib";
3516 final int libPrefixLen = libPrefix.length();
3517 final String libSuffix = ".so";
3518 final int libSuffixLen = libSuffix.length();
3519 boolean hasNativeLibraries = false;
3520 boolean installedNativeLibraries = false;
3521
3522 // the minimum length of a valid native shared library of the form
3523 // lib/<something>/lib<name>.so.
3524 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3525
3526 ZipFile zipFile = new ZipFile(scanFile);
3527 Enumeration<ZipEntry> entries =
3528 (Enumeration<ZipEntry>) zipFile.entries();
3529
3530 while (entries.hasMoreElements()) {
3531 ZipEntry entry = entries.nextElement();
3532 // skip directories
3533 if (entry.isDirectory()) {
3534 continue;
3535 }
3536 String entryName = entry.getName();
3537
3538 // check that the entry looks like lib/<something>/lib<name>.so
3539 // here, but don't check the ABI just yet.
3540 //
3541 // - must be sufficiently long
3542 // - must end with libSuffix, i.e. ".so"
3543 // - must start with apkLib, i.e. "lib/"
3544 if (entryName.length() < minEntryLen ||
3545 !entryName.endsWith(libSuffix) ||
3546 !entryName.startsWith(apkLib) ) {
3547 continue;
3548 }
3549
3550 // file name must start with libPrefix, i.e. "lib"
3551 int lastSlash = entryName.lastIndexOf('/');
3552
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003553 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003554 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3555 continue;
3556 }
3557
3558 hasNativeLibraries = true;
3559
3560 // check the cpuAbi now, between lib/ and /lib<name>.so
3561 //
3562 if (lastSlash != apkLibLen + cpuAbiLen ||
3563 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3564 continue;
3565
3566 // extract the library file name, ensure it doesn't contain
3567 // weird characters. we're guaranteed here that it doesn't contain
3568 // a directory separator though.
3569 String libFileName = entryName.substring(lastSlash+1);
3570 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3571 continue;
3572 }
3573
3574 installedNativeLibraries = true;
3575
3576 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3577 File.separator + libFileName;
3578 File sharedLibraryFile = new File(sharedLibraryFilePath);
3579 if (! sharedLibraryFile.exists() ||
3580 sharedLibraryFile.length() != entry.getSize() ||
3581 sharedLibraryFile.lastModified() != entry.getTime()) {
3582 if (Config.LOGD) {
3583 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003585 if (mInstaller == null) {
3586 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003587 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003588 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003589 sharedLibraryFile);
3590 }
3591 }
3592 if (!hasNativeLibraries)
3593 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3594
3595 if (!installedNativeLibraries)
3596 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3597
3598 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3599 }
3600
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003601 // Find the gdbserver executable program in a package at
3602 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3603 //
3604 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3605 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3606 //
3607 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3608 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3609 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3610 final String GDBSERVER = "gdbserver";
3611 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3612
3613 ZipFile zipFile = new ZipFile(scanFile);
3614 Enumeration<ZipEntry> entries =
3615 (Enumeration<ZipEntry>) zipFile.entries();
3616
3617 while (entries.hasMoreElements()) {
3618 ZipEntry entry = entries.nextElement();
3619 // skip directories
3620 if (entry.isDirectory()) {
3621 continue;
3622 }
3623 String entryName = entry.getName();
3624
3625 if (!entryName.equals(apkGdbServerPath)) {
3626 continue;
3627 }
3628
3629 String installGdbServerPath = installGdbServerDir.getPath() +
3630 "/" + GDBSERVER;
3631 File installGdbServerFile = new File(installGdbServerPath);
3632 if (! installGdbServerFile.exists() ||
3633 installGdbServerFile.length() != entry.getSize() ||
3634 installGdbServerFile.lastModified() != entry.getTime()) {
3635 if (Config.LOGD) {
3636 Log.d(TAG, "Caching gdbserver " + entry.getName());
3637 }
3638 if (mInstaller == null) {
3639 installGdbServerDir.mkdir();
3640 }
3641 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3642 installGdbServerFile);
3643 }
3644 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3645 }
3646 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3647 }
3648
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003649 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3650 // and copy them to /data/data/<appname>/lib.
3651 //
3652 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3653 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3654 // one if ro.product.cpu.abi2 is defined.
3655 //
3656 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3657 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003658 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003659 try {
3660 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3661
3662 // some architectures are capable of supporting several CPU ABIs
3663 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3664 // this is indicated by the definition of the ro.product.cpu.abi2
3665 // system property.
3666 //
3667 // only scan the package twice in case of ABI mismatch
3668 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003669 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003670 if (cpuAbi2 != null) {
3671 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003673
3674 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003675 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003676 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003678
3679 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3680 cpuAbi = cpuAbi2;
3681 }
3682 }
3683
3684 // for debuggable packages, also extract gdbserver from lib/<abi>
3685 // into /data/data/<appname>/lib too.
3686 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3687 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3688 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3689 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3690 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003693 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003694 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003695 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003697 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003698 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003700 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 }
3702
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003703 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003705 File binaryDir,
3706 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 InputStream inputStream = zipFile.getInputStream(entry);
3708 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003709 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003711 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 // now need to be left as world readable and owned by the system.
3713 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3714 ! tempFile.setLastModified(entry.getTime()) ||
3715 FileUtils.setPermissions(tempFilePath,
3716 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003717 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003719 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 // Failed to properly write file.
3721 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003722 throw new IOException("Couldn't create cached binary "
3723 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
3725 } finally {
3726 inputStream.close();
3727 }
3728 }
3729
3730 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3731 if (chatty && Config.LOGD) Log.d(
3732 TAG, "Removing package " + pkg.applicationInfo.packageName );
3733
3734 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003737 mPackages.remove(pkg.applicationInfo.packageName);
3738 if (pkg.mPath != null) {
3739 mAppDirs.remove(pkg.mPath);
3740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 PackageSetting ps = (PackageSetting)pkg.mExtras;
3743 if (ps != null && ps.sharedUser != null) {
3744 // XXX don't do this until the data is removed.
3745 if (false) {
3746 ps.sharedUser.packages.remove(ps);
3747 if (ps.sharedUser.packages.size() == 0) {
3748 // Remove.
3749 }
3750 }
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 int N = pkg.providers.size();
3754 StringBuilder r = null;
3755 int i;
3756 for (i=0; i<N; i++) {
3757 PackageParser.Provider p = pkg.providers.get(i);
3758 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3759 p.info.name));
3760 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003762 /* The is another ContentProvider with this authority when
3763 * this app was installed so this authority is null,
3764 * Ignore it as we don't have to unregister the provider.
3765 */
3766 continue;
3767 }
3768 String names[] = p.info.authority.split(";");
3769 for (int j = 0; j < names.length; j++) {
3770 if (mProviders.get(names[j]) == p) {
3771 mProviders.remove(names[j]);
3772 if (chatty && Config.LOGD) Log.d(
3773 TAG, "Unregistered content provider: " + names[j] +
3774 ", className = " + p.info.name +
3775 ", isSyncable = " + p.info.isSyncable);
3776 }
3777 }
3778 if (chatty) {
3779 if (r == null) {
3780 r = new StringBuilder(256);
3781 } else {
3782 r.append(' ');
3783 }
3784 r.append(p.info.name);
3785 }
3786 }
3787 if (r != null) {
3788 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 N = pkg.services.size();
3792 r = null;
3793 for (i=0; i<N; i++) {
3794 PackageParser.Service s = pkg.services.get(i);
3795 mServices.removeService(s);
3796 if (chatty) {
3797 if (r == null) {
3798 r = new StringBuilder(256);
3799 } else {
3800 r.append(' ');
3801 }
3802 r.append(s.info.name);
3803 }
3804 }
3805 if (r != null) {
3806 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 N = pkg.receivers.size();
3810 r = null;
3811 for (i=0; i<N; i++) {
3812 PackageParser.Activity a = pkg.receivers.get(i);
3813 mReceivers.removeActivity(a, "receiver");
3814 if (chatty) {
3815 if (r == null) {
3816 r = new StringBuilder(256);
3817 } else {
3818 r.append(' ');
3819 }
3820 r.append(a.info.name);
3821 }
3822 }
3823 if (r != null) {
3824 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 N = pkg.activities.size();
3828 r = null;
3829 for (i=0; i<N; i++) {
3830 PackageParser.Activity a = pkg.activities.get(i);
3831 mActivities.removeActivity(a, "activity");
3832 if (chatty) {
3833 if (r == null) {
3834 r = new StringBuilder(256);
3835 } else {
3836 r.append(' ');
3837 }
3838 r.append(a.info.name);
3839 }
3840 }
3841 if (r != null) {
3842 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 N = pkg.permissions.size();
3846 r = null;
3847 for (i=0; i<N; i++) {
3848 PackageParser.Permission p = pkg.permissions.get(i);
3849 boolean tree = false;
3850 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3851 if (bp == null) {
3852 tree = true;
3853 bp = mSettings.mPermissionTrees.get(p.info.name);
3854 }
3855 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003856 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 if (chatty) {
3858 if (r == null) {
3859 r = new StringBuilder(256);
3860 } else {
3861 r.append(' ');
3862 }
3863 r.append(p.info.name);
3864 }
3865 }
3866 }
3867 if (r != null) {
3868 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 N = pkg.instrumentation.size();
3872 r = null;
3873 for (i=0; i<N; i++) {
3874 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003875 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 if (chatty) {
3877 if (r == null) {
3878 r = new StringBuilder(256);
3879 } else {
3880 r.append(' ');
3881 }
3882 r.append(a.info.name);
3883 }
3884 }
3885 if (r != null) {
3886 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3887 }
3888 }
3889 }
3890
3891 private static final boolean isPackageFilename(String name) {
3892 return name != null && name.endsWith(".apk");
3893 }
3894
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003895 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3896 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3897 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3898 return true;
3899 }
3900 }
3901 return false;
3902 }
3903
3904 private void updatePermissionsLP(String changingPkg,
3905 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 // Make sure there are no dangling permission trees.
3907 Iterator<BasePermission> it = mSettings.mPermissionTrees
3908 .values().iterator();
3909 while (it.hasNext()) {
3910 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003911 if (bp.packageSetting == null) {
3912 // We may not yet have parsed the package, so just see if
3913 // we still know about its settings.
3914 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3915 }
3916 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003917 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 + " from package " + bp.sourcePackage);
3919 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003920 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3921 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3922 Slog.i(TAG, "Removing old permission tree: " + bp.name
3923 + " from package " + bp.sourcePackage);
3924 grantPermissions = true;
3925 it.remove();
3926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
3928 }
3929
3930 // Make sure all dynamic permissions have been assigned to a package,
3931 // and make sure there are no dangling permissions.
3932 it = mSettings.mPermissions.values().iterator();
3933 while (it.hasNext()) {
3934 BasePermission bp = it.next();
3935 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3936 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3937 + bp.name + " pkg=" + bp.sourcePackage
3938 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003939 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 BasePermission tree = findPermissionTreeLP(bp.name);
3941 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003942 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 bp.perm = new PackageParser.Permission(tree.perm.owner,
3944 new PermissionInfo(bp.pendingInfo));
3945 bp.perm.info.packageName = tree.perm.info.packageName;
3946 bp.perm.info.name = bp.name;
3947 bp.uid = tree.uid;
3948 }
3949 }
3950 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003951 if (bp.packageSetting == null) {
3952 // We may not yet have parsed the package, so just see if
3953 // we still know about its settings.
3954 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3955 }
3956 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003957 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 + " from package " + bp.sourcePackage);
3959 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003960 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3961 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3962 Slog.i(TAG, "Removing old permission: " + bp.name
3963 + " from package " + bp.sourcePackage);
3964 grantPermissions = true;
3965 it.remove();
3966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 }
3968 }
3969
3970 // Now update the permissions for all packages, in particular
3971 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003972 if (grantPermissions) {
3973 for (PackageParser.Package pkg : mPackages.values()) {
3974 if (pkg != pkgInfo) {
3975 grantPermissionsLP(pkg, false);
3976 }
3977 }
3978 }
3979
3980 if (pkgInfo != null) {
3981 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 }
3983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3986 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3987 if (ps == null) {
3988 return;
3989 }
3990 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003991 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 if (replace) {
3994 ps.permissionsFixed = false;
3995 if (gp == ps) {
3996 gp.grantedPermissions.clear();
3997 gp.gids = mGlobalGids;
3998 }
3999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 if (gp.gids == null) {
4002 gp.gids = mGlobalGids;
4003 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004004
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 final int N = pkg.requestedPermissions.size();
4006 for (int i=0; i<N; i++) {
4007 String name = pkg.requestedPermissions.get(i);
4008 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 if (false) {
4010 if (gp != ps) {
4011 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004012 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
4014 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004015 if (bp != null && bp.packageSetting != null) {
4016 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004018 boolean allowedSig = false;
4019 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4020 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004022 } else if (bp.packageSetting == null) {
4023 // This permission is invalid; skip it.
4024 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004025 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4026 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4027 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004029 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004031 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4033 // For updated system applications, the signatureOrSystem permission
4034 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004035 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4037 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4038 if(sysPs.grantedPermissions.contains(perm)) {
4039 allowed = true;
4040 } else {
4041 allowed = false;
4042 }
4043 } else {
4044 allowed = true;
4045 }
4046 }
4047 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004048 if (allowed) {
4049 allowedSig = true;
4050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 } else {
4052 allowed = false;
4053 }
4054 if (false) {
4055 if (gp != ps) {
4056 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4057 }
4058 }
4059 if (allowed) {
4060 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4061 && ps.permissionsFixed) {
4062 // If this is an existing, non-system package, then
4063 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004064 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004066 // Except... if this is a permission that was added
4067 // to the platform (note: need to only do this when
4068 // updating the platform).
4069 final int NP = PackageParser.NEW_PERMISSIONS.length;
4070 for (int ip=0; ip<NP; ip++) {
4071 final PackageParser.NewPermissionInfo npi
4072 = PackageParser.NEW_PERMISSIONS[ip];
4073 if (npi.name.equals(perm)
4074 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4075 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004076 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004077 + pkg.packageName);
4078 break;
4079 }
4080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 }
4082 }
4083 if (allowed) {
4084 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004085 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 gp.grantedPermissions.add(perm);
4087 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004088 } else if (!ps.haveGids) {
4089 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 }
4091 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004092 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 + " to package " + pkg.packageName
4094 + " because it was previously installed without");
4095 }
4096 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004097 if (gp.grantedPermissions.remove(perm)) {
4098 changedPermission = true;
4099 gp.gids = removeInts(gp.gids, bp.gids);
4100 Slog.i(TAG, "Un-granting permission " + perm
4101 + " from package " + pkg.packageName
4102 + " (protectionLevel=" + bp.protectionLevel
4103 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4104 + ")");
4105 } else {
4106 Slog.w(TAG, "Not granting permission " + perm
4107 + " to package " + pkg.packageName
4108 + " (protectionLevel=" + bp.protectionLevel
4109 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4110 + ")");
4111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 }
4113 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004114 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 + " in package " + pkg.packageName);
4116 }
4117 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004118
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004119 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004120 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4121 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 // This is the first that we have heard about this package, so the
4123 // permissions we have now selected are fixed until explicitly
4124 // changed.
4125 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004127 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 private final class ActivityIntentResolver
4131 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004132 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004134 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004135 }
4136
Mihai Preda074edef2009-05-18 17:13:31 +02004137 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004139 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4141 }
4142
Mihai Predaeae850c2009-05-13 10:13:48 +02004143 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4144 ArrayList<PackageParser.Activity> packageActivities) {
4145 if (packageActivities == null) {
4146 return null;
4147 }
4148 mFlags = flags;
4149 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4150 int N = packageActivities.size();
4151 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4152 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004153
4154 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004155 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004156 intentFilters = packageActivities.get(i).intents;
4157 if (intentFilters != null && intentFilters.size() > 0) {
4158 listCut.add(intentFilters);
4159 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004160 }
4161 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4162 }
4163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004165 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 if (SHOW_INFO || Config.LOGV) Log.v(
4167 TAG, " " + type + " " +
4168 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4169 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4170 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004171 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4173 if (SHOW_INFO || Config.LOGV) {
4174 Log.v(TAG, " IntentFilter:");
4175 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4176 }
4177 if (!intent.debugCheck()) {
4178 Log.w(TAG, "==> For Activity " + a.info.name);
4179 }
4180 addFilter(intent);
4181 }
4182 }
4183
4184 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004185 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 if (SHOW_INFO || Config.LOGV) Log.v(
4187 TAG, " " + type + " " +
4188 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4189 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4190 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004191 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4193 if (SHOW_INFO || Config.LOGV) {
4194 Log.v(TAG, " IntentFilter:");
4195 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4196 }
4197 removeFilter(intent);
4198 }
4199 }
4200
4201 @Override
4202 protected boolean allowFilterResult(
4203 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4204 ActivityInfo filterAi = filter.activity.info;
4205 for (int i=dest.size()-1; i>=0; i--) {
4206 ActivityInfo destAi = dest.get(i).activityInfo;
4207 if (destAi.name == filterAi.name
4208 && destAi.packageName == filterAi.packageName) {
4209 return false;
4210 }
4211 }
4212 return true;
4213 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004216 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4217 return info.activity.owner.packageName;
4218 }
4219
4220 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4222 int match) {
4223 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4224 return null;
4225 }
4226 final PackageParser.Activity activity = info.activity;
4227 if (mSafeMode && (activity.info.applicationInfo.flags
4228 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4229 return null;
4230 }
4231 final ResolveInfo res = new ResolveInfo();
4232 res.activityInfo = PackageParser.generateActivityInfo(activity,
4233 mFlags);
4234 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4235 res.filter = info;
4236 }
4237 res.priority = info.getPriority();
4238 res.preferredOrder = activity.owner.mPreferredOrder;
4239 //System.out.println("Result: " + res.activityInfo.className +
4240 // " = " + res.priority);
4241 res.match = match;
4242 res.isDefault = info.hasDefault;
4243 res.labelRes = info.labelRes;
4244 res.nonLocalizedLabel = info.nonLocalizedLabel;
4245 res.icon = info.icon;
4246 return res;
4247 }
4248
4249 @Override
4250 protected void sortResults(List<ResolveInfo> results) {
4251 Collections.sort(results, mResolvePrioritySorter);
4252 }
4253
4254 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004255 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004256 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004257 out.print(prefix); out.print(
4258 Integer.toHexString(System.identityHashCode(filter.activity)));
4259 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004260 out.print(filter.activity.getComponentShortName());
4261 out.print(" filter ");
4262 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004263 }
4264
4265// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4266// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4267// final List<ResolveInfo> retList = Lists.newArrayList();
4268// while (i.hasNext()) {
4269// final ResolveInfo resolveInfo = i.next();
4270// if (isEnabledLP(resolveInfo.activityInfo)) {
4271// retList.add(resolveInfo);
4272// }
4273// }
4274// return retList;
4275// }
4276
4277 // Keys are String (activity class name), values are Activity.
4278 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4279 = new HashMap<ComponentName, PackageParser.Activity>();
4280 private int mFlags;
4281 }
4282
4283 private final class ServiceIntentResolver
4284 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004285 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004287 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 }
4289
Mihai Preda074edef2009-05-18 17:13:31 +02004290 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004292 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4294 }
4295
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004296 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4297 ArrayList<PackageParser.Service> packageServices) {
4298 if (packageServices == null) {
4299 return null;
4300 }
4301 mFlags = flags;
4302 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4303 int N = packageServices.size();
4304 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4305 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4306
4307 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4308 for (int i = 0; i < N; ++i) {
4309 intentFilters = packageServices.get(i).intents;
4310 if (intentFilters != null && intentFilters.size() > 0) {
4311 listCut.add(intentFilters);
4312 }
4313 }
4314 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4315 }
4316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004318 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 if (SHOW_INFO || Config.LOGV) Log.v(
4320 TAG, " " + (s.info.nonLocalizedLabel != null
4321 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4322 if (SHOW_INFO || Config.LOGV) Log.v(
4323 TAG, " Class=" + s.info.name);
4324 int NI = s.intents.size();
4325 int j;
4326 for (j=0; j<NI; j++) {
4327 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4328 if (SHOW_INFO || Config.LOGV) {
4329 Log.v(TAG, " IntentFilter:");
4330 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4331 }
4332 if (!intent.debugCheck()) {
4333 Log.w(TAG, "==> For Service " + s.info.name);
4334 }
4335 addFilter(intent);
4336 }
4337 }
4338
4339 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004340 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 if (SHOW_INFO || Config.LOGV) Log.v(
4342 TAG, " " + (s.info.nonLocalizedLabel != null
4343 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4344 if (SHOW_INFO || Config.LOGV) Log.v(
4345 TAG, " Class=" + s.info.name);
4346 int NI = s.intents.size();
4347 int j;
4348 for (j=0; j<NI; j++) {
4349 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4350 if (SHOW_INFO || Config.LOGV) {
4351 Log.v(TAG, " IntentFilter:");
4352 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4353 }
4354 removeFilter(intent);
4355 }
4356 }
4357
4358 @Override
4359 protected boolean allowFilterResult(
4360 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4361 ServiceInfo filterSi = filter.service.info;
4362 for (int i=dest.size()-1; i>=0; i--) {
4363 ServiceInfo destAi = dest.get(i).serviceInfo;
4364 if (destAi.name == filterSi.name
4365 && destAi.packageName == filterSi.packageName) {
4366 return false;
4367 }
4368 }
4369 return true;
4370 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004373 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4374 return info.service.owner.packageName;
4375 }
4376
4377 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4379 int match) {
4380 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4381 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4382 return null;
4383 }
4384 final PackageParser.Service service = info.service;
4385 if (mSafeMode && (service.info.applicationInfo.flags
4386 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4387 return null;
4388 }
4389 final ResolveInfo res = new ResolveInfo();
4390 res.serviceInfo = PackageParser.generateServiceInfo(service,
4391 mFlags);
4392 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4393 res.filter = filter;
4394 }
4395 res.priority = info.getPriority();
4396 res.preferredOrder = service.owner.mPreferredOrder;
4397 //System.out.println("Result: " + res.activityInfo.className +
4398 // " = " + res.priority);
4399 res.match = match;
4400 res.isDefault = info.hasDefault;
4401 res.labelRes = info.labelRes;
4402 res.nonLocalizedLabel = info.nonLocalizedLabel;
4403 res.icon = info.icon;
4404 return res;
4405 }
4406
4407 @Override
4408 protected void sortResults(List<ResolveInfo> results) {
4409 Collections.sort(results, mResolvePrioritySorter);
4410 }
4411
4412 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004413 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004414 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004415 out.print(prefix); out.print(
4416 Integer.toHexString(System.identityHashCode(filter.service)));
4417 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004418 out.print(filter.service.getComponentShortName());
4419 out.print(" filter ");
4420 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 }
4422
4423// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4424// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4425// final List<ResolveInfo> retList = Lists.newArrayList();
4426// while (i.hasNext()) {
4427// final ResolveInfo resolveInfo = (ResolveInfo) i;
4428// if (isEnabledLP(resolveInfo.serviceInfo)) {
4429// retList.add(resolveInfo);
4430// }
4431// }
4432// return retList;
4433// }
4434
4435 // Keys are String (activity class name), values are Activity.
4436 private final HashMap<ComponentName, PackageParser.Service> mServices
4437 = new HashMap<ComponentName, PackageParser.Service>();
4438 private int mFlags;
4439 };
4440
4441 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4442 new Comparator<ResolveInfo>() {
4443 public int compare(ResolveInfo r1, ResolveInfo r2) {
4444 int v1 = r1.priority;
4445 int v2 = r2.priority;
4446 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4447 if (v1 != v2) {
4448 return (v1 > v2) ? -1 : 1;
4449 }
4450 v1 = r1.preferredOrder;
4451 v2 = r2.preferredOrder;
4452 if (v1 != v2) {
4453 return (v1 > v2) ? -1 : 1;
4454 }
4455 if (r1.isDefault != r2.isDefault) {
4456 return r1.isDefault ? -1 : 1;
4457 }
4458 v1 = r1.match;
4459 v2 = r2.match;
4460 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4461 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4462 }
4463 };
4464
4465 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4466 new Comparator<ProviderInfo>() {
4467 public int compare(ProviderInfo p1, ProviderInfo p2) {
4468 final int v1 = p1.initOrder;
4469 final int v2 = p2.initOrder;
4470 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4471 }
4472 };
4473
4474 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4475 IActivityManager am = ActivityManagerNative.getDefault();
4476 if (am != null) {
4477 try {
4478 final Intent intent = new Intent(action,
4479 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4480 if (extras != null) {
4481 intent.putExtras(extras);
4482 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004483 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 am.broadcastIntent(
4485 null, intent,
4486 null, null, 0, null, null, null, false, false);
4487 } catch (RemoteException ex) {
4488 }
4489 }
4490 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004491
4492 public String nextPackageToClean(String lastPackage) {
4493 synchronized (mPackages) {
4494 if (!mMediaMounted) {
4495 // If the external storage is no longer mounted at this point,
4496 // the caller may not have been able to delete all of this
4497 // packages files and can not delete any more. Bail.
4498 return null;
4499 }
4500 if (lastPackage != null) {
4501 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4502 }
4503 return mSettings.mPackagesToBeCleaned.size() > 0
4504 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4505 }
4506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004508 void schedulePackageCleaning(String packageName) {
4509 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4510 }
4511
4512 void startCleaningPackages() {
4513 synchronized (mPackages) {
4514 if (!mMediaMounted) {
4515 return;
4516 }
4517 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4518 return;
4519 }
4520 }
4521 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4522 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4523 IActivityManager am = ActivityManagerNative.getDefault();
4524 if (am != null) {
4525 try {
4526 am.startService(null, intent, null);
4527 } catch (RemoteException e) {
4528 }
4529 }
4530 }
4531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 private final class AppDirObserver extends FileObserver {
4533 public AppDirObserver(String path, int mask, boolean isrom) {
4534 super(path, mask);
4535 mRootDir = path;
4536 mIsRom = isrom;
4537 }
4538
4539 public void onEvent(int event, String path) {
4540 String removedPackage = null;
4541 int removedUid = -1;
4542 String addedPackage = null;
4543 int addedUid = -1;
4544
4545 synchronized (mInstallLock) {
4546 String fullPathStr = null;
4547 File fullPath = null;
4548 if (path != null) {
4549 fullPath = new File(mRootDir, path);
4550 fullPathStr = fullPath.getPath();
4551 }
4552
4553 if (Config.LOGV) Log.v(
4554 TAG, "File " + fullPathStr + " changed: "
4555 + Integer.toHexString(event));
4556
4557 if (!isPackageFilename(path)) {
4558 if (Config.LOGV) Log.v(
4559 TAG, "Ignoring change of non-package file: " + fullPathStr);
4560 return;
4561 }
4562
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004563 // Ignore packages that are being installed or
4564 // have just been installed.
4565 if (ignoreCodePath(fullPathStr)) {
4566 return;
4567 }
4568 PackageParser.Package p = null;
4569 synchronized (mPackages) {
4570 p = mAppDirs.get(fullPathStr);
4571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004573 if (p != null) {
4574 removePackageLI(p, true);
4575 removedPackage = p.applicationInfo.packageName;
4576 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
4578 }
4579
4580 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004582 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004583 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4584 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 PackageParser.PARSE_CHATTY |
4586 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004587 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 if (p != null) {
4589 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004590 updatePermissionsLP(p.packageName, p,
4591 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 }
4593 addedPackage = p.applicationInfo.packageName;
4594 addedUid = p.applicationInfo.uid;
4595 }
4596 }
4597 }
4598
4599 synchronized (mPackages) {
4600 mSettings.writeLP();
4601 }
4602 }
4603
4604 if (removedPackage != null) {
4605 Bundle extras = new Bundle(1);
4606 extras.putInt(Intent.EXTRA_UID, removedUid);
4607 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4608 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4609 }
4610 if (addedPackage != null) {
4611 Bundle extras = new Bundle(1);
4612 extras.putInt(Intent.EXTRA_UID, addedUid);
4613 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4614 }
4615 }
4616
4617 private final String mRootDir;
4618 private final boolean mIsRom;
4619 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 /* Called when a downloaded package installation has been confirmed by the user */
4622 public void installPackage(
4623 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004624 installPackage(packageURI, observer, flags, null);
4625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004626
Jacek Surazski65e13172009-04-28 15:26:38 +02004627 /* Called when a downloaded package installation has been confirmed by the user */
4628 public void installPackage(
4629 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4630 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 mContext.enforceCallingOrSelfPermission(
4632 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004633
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004634 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004635 msg.obj = new InstallParams(packageURI, observer, flags,
4636 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004637 mHandler.sendMessage(msg);
4638 }
4639
Christopher Tate1bb69062010-02-19 17:02:12 -08004640 public void finishPackageInstall(int token) {
4641 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4642 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4643 mHandler.sendMessage(msg);
4644 }
4645
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004646 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 // Queue up an async operation since the package installation may take a little while.
4648 mHandler.post(new Runnable() {
4649 public void run() {
4650 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004651 // Result object to be returned
4652 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004653 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004654 res.uid = -1;
4655 res.pkg = null;
4656 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004657 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004658 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004659 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004660 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004661 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004662 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004664
4665 // A restore should be performed at this point if (a) the install
4666 // succeeded, (b) the operation is not an update, and (c) the new
4667 // package has a backupAgent defined.
4668 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004669 boolean doRestore = (!update
4670 && res.pkg != null
4671 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004672
4673 // Set up the post-install work request bookkeeping. This will be used
4674 // and cleaned up by the post-install event handling regardless of whether
4675 // there's a restore pass performed. Token values are >= 1.
4676 int token;
4677 if (mNextInstallToken < 0) mNextInstallToken = 1;
4678 token = mNextInstallToken++;
4679
4680 PostInstallData data = new PostInstallData(args, res);
4681 mRunningInstalls.put(token, data);
4682 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4683
4684 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4685 // Pass responsibility to the Backup Manager. It will perform a
4686 // restore if appropriate, then pass responsibility back to the
4687 // Package Manager to run the post-install observer callbacks
4688 // and broadcasts.
4689 IBackupManager bm = IBackupManager.Stub.asInterface(
4690 ServiceManager.getService(Context.BACKUP_SERVICE));
4691 if (bm != null) {
4692 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4693 + " to BM for possible restore");
4694 try {
4695 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4696 } catch (RemoteException e) {
4697 // can't happen; the backup manager is local
4698 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004699 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004700 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004701 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004702 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004703 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004704 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004706 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004707
4708 if (!doRestore) {
4709 // No restore possible, or the Backup Manager was mysteriously not
4710 // available -- just fire the post-install work request directly.
4711 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4712 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4713 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 }
4716 });
4717 }
4718
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004719 abstract class HandlerParams {
4720 final static int MAX_RETRIES = 4;
4721 int retry = 0;
4722 final void startCopy() {
4723 try {
4724 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4725 retry++;
4726 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004727 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004728 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4729 handleServiceError();
4730 return;
4731 } else {
4732 handleStartCopy();
4733 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4734 mHandler.sendEmptyMessage(MCS_UNBIND);
4735 }
4736 } catch (RemoteException e) {
4737 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4738 mHandler.sendEmptyMessage(MCS_RECONNECT);
4739 }
4740 handleReturnCode();
4741 }
4742
4743 final void serviceError() {
4744 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4745 handleServiceError();
4746 handleReturnCode();
4747 }
4748 abstract void handleStartCopy() throws RemoteException;
4749 abstract void handleServiceError();
4750 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004751 }
4752
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004753 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004754 final IPackageInstallObserver observer;
4755 int flags;
4756 final Uri packageURI;
4757 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 private InstallArgs mArgs;
4759 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004760 InstallParams(Uri packageURI,
4761 IPackageInstallObserver observer, int flags,
4762 String installerPackageName) {
4763 this.packageURI = packageURI;
4764 this.flags = flags;
4765 this.observer = observer;
4766 this.installerPackageName = installerPackageName;
4767 }
4768
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004769 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4770 String packageName = pkgLite.packageName;
4771 int installLocation = pkgLite.installLocation;
4772 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4773 synchronized (mPackages) {
4774 PackageParser.Package pkg = mPackages.get(packageName);
4775 if (pkg != null) {
4776 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4777 // Check for updated system application.
4778 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4779 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004780 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004781 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4782 }
4783 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4784 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004785 if (onSd) {
4786 // Install flag overrides everything.
4787 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4788 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004789 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004790 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4791 // Application explicitly specified internal.
4792 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4793 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4794 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004795 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004796 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004797 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4798 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4799 }
4800 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004801 }
4802 }
4803 } else {
4804 // Invalid install. Return error code
4805 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4806 }
4807 }
4808 }
4809 // All the special cases have been taken care of.
4810 // Return result based on recommended install location.
4811 if (onSd) {
4812 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4813 }
4814 return pkgLite.recommendedInstallLocation;
4815 }
4816
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004817 /*
4818 * Invoke remote method to get package information and install
4819 * location values. Override install location based on default
4820 * policy if needed and then create install arguments based
4821 * on the install location.
4822 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004823 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004824 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004825 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4826 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004827 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4828 if (onInt && onSd) {
4829 // Check if both bits are set.
4830 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4831 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4832 } else if (fwdLocked && onSd) {
4833 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004834 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004835 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004836 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004837 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004838 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004839 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004840 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4841 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4842 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4843 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4844 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4846 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4847 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004848 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4849 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004850 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004851 // Override with defaults if needed.
4852 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004853 if (!onSd && !onInt) {
4854 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004855 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4856 // Set the flag to install on external media.
4857 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004858 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859 } else {
4860 // Make sure the flag for installing on external
4861 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004862 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 flags &= ~PackageManager.INSTALL_EXTERNAL;
4864 }
4865 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 }
4867 }
4868 // Create the file args now.
4869 mArgs = createInstallArgs(this);
4870 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4871 // Create copy only if we are not in an erroneous state.
4872 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004873 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004874 }
4875 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 }
4877
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004878 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 void handleReturnCode() {
4880 processPendingInstall(mArgs, mRet);
4881 }
4882
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004883 @Override
4884 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004885 mArgs = createInstallArgs(this);
4886 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004888 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004889
4890 /*
4891 * Utility class used in movePackage api.
4892 * srcArgs and targetArgs are not set for invalid flags and make
4893 * sure to do null checks when invoking methods on them.
4894 * We probably want to return ErrorPrams for both failed installs
4895 * and moves.
4896 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004897 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 final IPackageMoveObserver observer;
4899 final int flags;
4900 final String packageName;
4901 final InstallArgs srcArgs;
4902 final InstallArgs targetArgs;
4903 int mRet;
4904 MoveParams(InstallArgs srcArgs,
4905 IPackageMoveObserver observer,
4906 int flags, String packageName) {
4907 this.srcArgs = srcArgs;
4908 this.observer = observer;
4909 this.flags = flags;
4910 this.packageName = packageName;
4911 if (srcArgs != null) {
4912 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4913 targetArgs = createInstallArgs(packageUri, flags, packageName);
4914 } else {
4915 targetArgs = null;
4916 }
4917 }
4918
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004919 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004920 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4921 // Check for storage space on target medium
4922 if (!targetArgs.checkFreeStorage(mContainerService)) {
4923 Log.w(TAG, "Insufficient storage to install");
4924 return;
4925 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004926 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004927 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004929 if (DEBUG_SD_INSTALL) {
4930 StringBuilder builder = new StringBuilder();
4931 if (srcArgs != null) {
4932 builder.append("src: ");
4933 builder.append(srcArgs.getCodePath());
4934 }
4935 if (targetArgs != null) {
4936 builder.append(" target : ");
4937 builder.append(targetArgs.getCodePath());
4938 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004939 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004940 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004941 }
4942
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004943 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004944 void handleReturnCode() {
4945 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004946 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4947 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4948 currentStatus = PackageManager.MOVE_SUCCEEDED;
4949 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4950 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4951 }
4952 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004953 }
4954
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004955 @Override
4956 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004957 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004958 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004959 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004960
4961 private InstallArgs createInstallArgs(InstallParams params) {
4962 if (installOnSd(params.flags)) {
4963 return new SdInstallArgs(params);
4964 } else {
4965 return new FileInstallArgs(params);
4966 }
4967 }
4968
4969 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4970 if (installOnSd(flags)) {
4971 return new SdInstallArgs(fullCodePath, fullResourcePath);
4972 } else {
4973 return new FileInstallArgs(fullCodePath, fullResourcePath);
4974 }
4975 }
4976
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4978 if (installOnSd(flags)) {
4979 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4980 return new SdInstallArgs(packageURI, cid);
4981 } else {
4982 return new FileInstallArgs(packageURI, pkgName);
4983 }
4984 }
4985
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004986 static abstract class InstallArgs {
4987 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004988 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 final int flags;
4990 final Uri packageURI;
4991 final String installerPackageName;
4992
4993 InstallArgs(Uri packageURI,
4994 IPackageInstallObserver observer, int flags,
4995 String installerPackageName) {
4996 this.packageURI = packageURI;
4997 this.flags = flags;
4998 this.observer = observer;
4999 this.installerPackageName = installerPackageName;
5000 }
5001
5002 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005003 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005004 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005006 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 abstract String getCodePath();
5008 abstract String getResourcePath();
5009 // Need installer lock especially for dex file removal.
5010 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005011 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005012 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 }
5014
5015 class FileInstallArgs extends InstallArgs {
5016 File installDir;
5017 String codeFileName;
5018 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005019 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005020
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005021 FileInstallArgs(InstallParams params) {
5022 super(params.packageURI, params.observer,
5023 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024 }
5025
5026 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5027 super(null, null, 0, null);
5028 File codeFile = new File(fullCodePath);
5029 installDir = codeFile.getParentFile();
5030 codeFileName = fullCodePath;
5031 resourceFileName = fullResourcePath;
5032 }
5033
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005034 FileInstallArgs(Uri packageURI, String pkgName) {
5035 super(packageURI, null, 0, null);
5036 boolean fwdLocked = isFwdLocked(flags);
5037 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5038 String apkName = getNextCodePath(null, pkgName, ".apk");
5039 codeFileName = new File(installDir, apkName + ".apk").getPath();
5040 resourceFileName = getResourcePathFromCodePath();
5041 }
5042
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005043 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5044 return imcs.checkFreeStorage(false, packageURI);
5045 }
5046
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005047 String getCodePath() {
5048 return codeFileName;
5049 }
5050
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 void createCopyFile() {
5052 boolean fwdLocked = isFwdLocked(flags);
5053 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5054 codeFileName = createTempPackageFile(installDir).getPath();
5055 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005056 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005057 }
5058
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005059 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005060 if (temp) {
5061 // Generate temp file name
5062 createCopyFile();
5063 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005064 // Get a ParcelFileDescriptor to write to the output file
5065 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005066 if (!created) {
5067 try {
5068 codeFile.createNewFile();
5069 // Set permissions
5070 if (!setPermissions()) {
5071 // Failed setting permissions.
5072 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5073 }
5074 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005075 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005076 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5077 }
5078 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 ParcelFileDescriptor out = null;
5080 try {
5081 out = ParcelFileDescriptor.open(codeFile,
5082 ParcelFileDescriptor.MODE_READ_WRITE);
5083 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005084 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005085 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5086 }
5087 // Copy the resource now
5088 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5089 try {
5090 if (imcs.copyResource(packageURI, out)) {
5091 ret = PackageManager.INSTALL_SUCCEEDED;
5092 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005093 } finally {
5094 try { if (out != null) out.close(); } catch (IOException e) {}
5095 }
5096 return ret;
5097 }
5098
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005099 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005100 if (status != PackageManager.INSTALL_SUCCEEDED) {
5101 cleanUp();
5102 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005103 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 }
5105
5106 boolean doRename(int status, final String pkgName, String oldCodePath) {
5107 if (status != PackageManager.INSTALL_SUCCEEDED) {
5108 cleanUp();
5109 return false;
5110 } else {
5111 // Rename based on packageName
5112 File codeFile = new File(getCodePath());
5113 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5114 File desFile = new File(installDir, apkName + ".apk");
5115 if (!codeFile.renameTo(desFile)) {
5116 return false;
5117 }
5118 // Reset paths since the file has been renamed.
5119 codeFileName = desFile.getPath();
5120 resourceFileName = getResourcePathFromCodePath();
5121 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005122 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005123 // Failed setting permissions.
5124 return false;
5125 }
5126 return true;
5127 }
5128 }
5129
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005130 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005131 if (status != PackageManager.INSTALL_SUCCEEDED) {
5132 cleanUp();
5133 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005134 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 }
5136
5137 String getResourcePath() {
5138 return resourceFileName;
5139 }
5140
5141 String getResourcePathFromCodePath() {
5142 String codePath = getCodePath();
5143 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5144 String apkNameOnly = getApkName(codePath);
5145 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5146 } else {
5147 return codePath;
5148 }
5149 }
5150
5151 private boolean cleanUp() {
5152 boolean ret = true;
5153 String sourceDir = getCodePath();
5154 String publicSourceDir = getResourcePath();
5155 if (sourceDir != null) {
5156 File sourceFile = new File(sourceDir);
5157 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005158 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005159 ret = false;
5160 }
5161 // Delete application's code and resources
5162 sourceFile.delete();
5163 }
5164 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5165 final File publicSourceFile = new File(publicSourceDir);
5166 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005167 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 }
5169 if (publicSourceFile.exists()) {
5170 publicSourceFile.delete();
5171 }
5172 }
5173 return ret;
5174 }
5175
5176 void cleanUpResourcesLI() {
5177 String sourceDir = getCodePath();
5178 if (cleanUp() && mInstaller != null) {
5179 int retCode = mInstaller.rmdex(sourceDir);
5180 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005181 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005182 + " at location "
5183 + sourceDir + ", retcode=" + retCode);
5184 // we don't consider this to be a failure of the core package deletion
5185 }
5186 }
5187 }
5188
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005189 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 // TODO Do this in a more elegant way later on. for now just a hack
5191 if (!isFwdLocked(flags)) {
5192 final int filePermissions =
5193 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5194 |FileUtils.S_IROTH;
5195 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5196 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005197 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 getCodePath()
5199 + ". The return code was: " + retCode);
5200 // TODO Define new internal error
5201 return false;
5202 }
5203 return true;
5204 }
5205 return true;
5206 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005207
5208 boolean doPostDeleteLI(boolean delete) {
5209 cleanUpResourcesLI();
5210 return true;
5211 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005212 }
5213
5214 class SdInstallArgs extends InstallArgs {
5215 String cid;
5216 String cachePath;
5217 static final String RES_FILE_NAME = "pkg.apk";
5218
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005219 SdInstallArgs(InstallParams params) {
5220 super(params.packageURI, params.observer,
5221 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 }
5223
5224 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005225 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 // Extract cid from fullCodePath
5227 int eidx = fullCodePath.lastIndexOf("/");
5228 String subStr1 = fullCodePath.substring(0, eidx);
5229 int sidx = subStr1.lastIndexOf("/");
5230 cid = subStr1.substring(sidx+1, eidx);
5231 cachePath = subStr1;
5232 }
5233
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005234 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005235 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5236 this.cid = cid;
5237 }
5238
5239 SdInstallArgs(Uri packageURI, String cid) {
5240 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 this.cid = cid;
5242 }
5243
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 void createCopyFile() {
5245 cid = getTempContainerId();
5246 }
5247
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005248 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5249 return imcs.checkFreeStorage(true, packageURI);
5250 }
5251
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005252 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005253 if (temp) {
5254 createCopyFile();
5255 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005256 cachePath = imcs.copyResourceToContainer(
5257 packageURI, cid,
5258 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005259 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5260 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005261 }
5262
5263 @Override
5264 String getCodePath() {
5265 return cachePath + "/" + RES_FILE_NAME;
5266 }
5267
5268 @Override
5269 String getResourcePath() {
5270 return cachePath + "/" + RES_FILE_NAME;
5271 }
5272
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005273 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 if (status != PackageManager.INSTALL_SUCCEEDED) {
5275 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005276 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005277 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005278 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005279 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005280 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005281 if (cachePath == null) {
5282 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5283 }
5284 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005285 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005286 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005287 }
5288
5289 boolean doRename(int status, final String pkgName,
5290 String oldCodePath) {
5291 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005292 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005293 if (PackageHelper.isContainerMounted(cid)) {
5294 // Unmount the container
5295 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005296 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005297 return false;
5298 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005299 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005300 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005301 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5302 " which might be stale. Will try to clean up.");
5303 // Clean up the stale container and proceed to recreate.
5304 if (!PackageHelper.destroySdDir(newCacheId)) {
5305 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5306 return false;
5307 }
5308 // Successfully cleaned up stale container. Try to rename again.
5309 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5310 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5311 + " inspite of cleaning it up.");
5312 return false;
5313 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005314 }
5315 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005316 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005317 newCachePath = PackageHelper.mountSdDir(newCacheId,
5318 getEncryptKey(), Process.SYSTEM_UID);
5319 } else {
5320 newCachePath = PackageHelper.getSdDir(newCacheId);
5321 }
5322 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005323 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005324 return false;
5325 }
5326 Log.i(TAG, "Succesfully renamed " + cid +
5327 " at path: " + cachePath + " to " + newCacheId +
5328 " at new path: " + newCachePath);
5329 cid = newCacheId;
5330 cachePath = newCachePath;
5331 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005332 }
5333
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005334 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 if (status != PackageManager.INSTALL_SUCCEEDED) {
5336 cleanUp();
5337 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005338 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005339 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005340 PackageHelper.mountSdDir(cid,
5341 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005342 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005344 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005345 }
5346
5347 private void cleanUp() {
5348 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005349 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005350 }
5351
5352 void cleanUpResourcesLI() {
5353 String sourceFile = getCodePath();
5354 // Remove dex file
5355 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005356 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005357 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005358 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005359 + " at location "
5360 + sourceFile.toString() + ", retcode=" + retCode);
5361 // we don't consider this to be a failure of the core package deletion
5362 }
5363 }
5364 cleanUp();
5365 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005366
5367 boolean matchContainer(String app) {
5368 if (cid.startsWith(app)) {
5369 return true;
5370 }
5371 return false;
5372 }
5373
5374 String getPackageName() {
5375 int idx = cid.lastIndexOf("-");
5376 if (idx == -1) {
5377 return cid;
5378 }
5379 return cid.substring(0, idx);
5380 }
5381
5382 boolean doPostDeleteLI(boolean delete) {
5383 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005384 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 if (mounted) {
5386 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005387 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005388 }
5389 if (ret && delete) {
5390 cleanUpResourcesLI();
5391 }
5392 return ret;
5393 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 };
5395
5396 // Utility method used to create code paths based on package name and available index.
5397 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5398 String idxStr = "";
5399 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005400 // Fall back to default value of idx=1 if prefix is not
5401 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005402 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005403 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005404 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005405 if (subStr.endsWith(suffix)) {
5406 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005408 // If oldCodePath already contains prefix find out the
5409 // ending index to either increment or decrement.
5410 int sidx = subStr.lastIndexOf(prefix);
5411 if (sidx != -1) {
5412 subStr = subStr.substring(sidx + prefix.length());
5413 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005414 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5415 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005416 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 try {
5418 idx = Integer.parseInt(subStr);
5419 if (idx <= 1) {
5420 idx++;
5421 } else {
5422 idx--;
5423 }
5424 } catch(NumberFormatException e) {
5425 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005426 }
5427 }
5428 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005429 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005430 return prefix + idxStr;
5431 }
5432
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005433 // Utility method used to ignore ADD/REMOVE events
5434 // by directory observer.
5435 private static boolean ignoreCodePath(String fullPathStr) {
5436 String apkName = getApkName(fullPathStr);
5437 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5438 if (idx != -1 && ((idx+1) < apkName.length())) {
5439 // Make sure the package ends with a numeral
5440 String version = apkName.substring(idx+1);
5441 try {
5442 Integer.parseInt(version);
5443 return true;
5444 } catch (NumberFormatException e) {}
5445 }
5446 return false;
5447 }
5448
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005449 // Utility method that returns the relative package path with respect
5450 // to the installation directory. Like say for /data/data/com.test-1.apk
5451 // string com.test-1 is returned.
5452 static String getApkName(String codePath) {
5453 if (codePath == null) {
5454 return null;
5455 }
5456 int sidx = codePath.lastIndexOf("/");
5457 int eidx = codePath.lastIndexOf(".");
5458 if (eidx == -1) {
5459 eidx = codePath.length();
5460 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005461 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005462 return null;
5463 }
5464 return codePath.substring(sidx+1, eidx);
5465 }
5466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 class PackageInstalledInfo {
5468 String name;
5469 int uid;
5470 PackageParser.Package pkg;
5471 int returnCode;
5472 PackageRemovedInfo removedInfo;
5473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 /*
5476 * Install a non-existing package.
5477 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005478 private void installNewPackageLI(PackageParser.Package pkg,
5479 int parseFlags,
5480 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005481 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005483 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005484
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005485 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 res.name = pkgName;
5487 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005488 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5489 // A package with the same name is already installed, though
5490 // it has been renamed to an older name. The package we
5491 // are trying to install should be installed as an update to
5492 // the existing one, but that has not been requested, so bail.
5493 Slog.w(TAG, "Attempt to re-install " + pkgName
5494 + " without first uninstalling package running as "
5495 + mSettings.mRenamedPackages.get(pkgName));
5496 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5497 return;
5498 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005499 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005501 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 + " without first uninstalling.");
5503 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5504 return;
5505 }
5506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005508 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005510 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5512 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5513 }
5514 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005515 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005516 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 res);
5518 // delete the partially installed application. the data directory will have to be
5519 // restored if it was already existing
5520 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5521 // remove package from internal structures. Note that we want deletePackageX to
5522 // delete the package data and cache directories that it created in
5523 // scanPackageLocked, unless those directories existed before we even tried to
5524 // install.
5525 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005526 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5528 res.removedInfo);
5529 }
5530 }
5531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005532
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005533 private void replacePackageLI(PackageParser.Package pkg,
5534 int parseFlags,
5535 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005536 String installerPackageName, PackageInstalledInfo res) {
5537
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005538 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005539 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 // First find the old package info and check signatures
5541 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005542 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005543 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005544 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5546 return;
5547 }
5548 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005549 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005550 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005551 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005553 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005554 }
5555 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005558 PackageParser.Package pkg,
5559 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005560 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 PackageParser.Package newPackage = null;
5562 String pkgName = deletedPackage.packageName;
5563 boolean deletedPkg = true;
5564 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005565
Jacek Surazski65e13172009-04-28 15:26:38 +02005566 String oldInstallerPackageName = null;
5567 synchronized (mPackages) {
5568 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005572 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 res.removedInfo)) {
5574 // If the existing package was'nt successfully deleted
5575 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5576 deletedPkg = false;
5577 } else {
5578 // Successfully deleted the old package. Now proceed with re-installation
5579 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005580 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005582 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5584 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005585 }
5586 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005587 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005588 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 res);
5590 updatedSettings = true;
5591 }
5592 }
5593
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005594 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 // remove package from internal structures. Note that we want deletePackageX to
5596 // delete the package data and cache directories that it created in
5597 // scanPackageLocked, unless those directories existed before we even tried to
5598 // install.
5599 if(updatedSettings) {
5600 deletePackageLI(
5601 pkgName, true,
5602 PackageManager.DONT_DELETE_DATA,
5603 res.removedInfo);
5604 }
5605 // Since we failed to install the new package we need to restore the old
5606 // package that we deleted.
5607 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005608 File restoreFile = new File(deletedPackage.mPath);
5609 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005610 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005611 return;
5612 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005613 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005614 boolean oldOnSd = isExternal(deletedPackage);
5615 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5616 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5617 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5618 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5619 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5620 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5621 return;
5622 }
5623 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005624 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005625 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5626 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005627 mSettings.writeLP();
5628 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005629 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 }
5631 }
5632 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005635 PackageParser.Package pkg,
5636 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005637 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 PackageParser.Package newPackage = null;
5639 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005640 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 PackageParser.PARSE_IS_SYSTEM;
5642 String packageName = deletedPackage.packageName;
5643 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5644 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005645 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 return;
5647 }
5648 PackageParser.Package oldPkg;
5649 PackageSetting oldPkgSetting;
5650 synchronized (mPackages) {
5651 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005652 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5654 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005655 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 return;
5657 }
5658 }
5659 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5660 res.removedInfo.removedPackage = packageName;
5661 // Remove existing system package
5662 removePackageLI(oldPkg, true);
5663 synchronized (mPackages) {
5664 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5665 }
5666
5667 // Successfully disabled the old package. Now proceed with re-installation
5668 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5669 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005670 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005672 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5674 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5675 }
5676 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005677 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 updatedSettings = true;
5679 }
5680
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005681 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 // Re installation failed. Restore old information
5683 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005684 if (newPackage != null) {
5685 removePackageLI(newPackage, true);
5686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005688 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005690 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 // Restore the old system information in Settings
5692 synchronized(mPackages) {
5693 if(updatedSettings) {
5694 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005695 mSettings.setInstallerPackageName(packageName,
5696 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 }
5698 mSettings.writeLP();
5699 }
5700 }
5701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005702
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005703 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005704 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005705 int retCode;
5706 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5707 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5708 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005709 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005710 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5711 }
5712 }
5713 return PackageManager.INSTALL_SUCCEEDED;
5714 }
5715
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005716 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005717 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005718 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 synchronized (mPackages) {
5720 //write settings. the installStatus will be incomplete at this stage.
5721 //note that the new package setting would have already been
5722 //added to mPackages. It hasn't been persisted yet.
5723 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5724 mSettings.writeLP();
5725 }
5726
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005727 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005728 != PackageManager.INSTALL_SUCCEEDED) {
5729 // Discontinue if moving dex files failed.
5730 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005732 if((res.returnCode = setPermissionsLI(newPackage))
5733 != PackageManager.INSTALL_SUCCEEDED) {
5734 if (mInstaller != null) {
5735 mInstaller.rmdex(newPackage.mScanPath);
5736 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005737 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005739 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005741 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005742 updatePermissionsLP(newPackage.packageName, newPackage,
5743 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 res.name = pkgName;
5745 res.uid = newPackage.applicationInfo.uid;
5746 res.pkg = newPackage;
5747 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005748 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5750 //to update install status
5751 mSettings.writeLP();
5752 }
5753 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005754
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005755 private void installPackageLI(InstallArgs args,
5756 boolean newInstall, PackageInstalledInfo res) {
5757 int pFlags = args.flags;
5758 String installerPackageName = args.installerPackageName;
5759 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005760 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005761 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005762 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005763 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005764 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005765 // Result object to be returned
5766 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5767
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005768 // Retrieve PackageSettings and parse package
5769 int parseFlags = PackageParser.PARSE_CHATTY |
5770 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5771 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5772 parseFlags |= mDefParseFlags;
5773 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5774 pp.setSeparateProcesses(mSeparateProcesses);
5775 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5776 null, mMetrics, parseFlags);
5777 if (pkg == null) {
5778 res.returnCode = pp.getParseError();
5779 return;
5780 }
5781 String pkgName = res.name = pkg.packageName;
5782 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5783 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5784 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5785 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005787 }
5788 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5789 res.returnCode = pp.getParseError();
5790 return;
5791 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005792 // Get rid of all references to package scan path via parser.
5793 pp = null;
5794 String oldCodePath = null;
5795 boolean systemApp = false;
5796 synchronized (mPackages) {
5797 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005798 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5799 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005800 if (pkg.mOriginalPackages != null
5801 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005802 && mPackages.containsKey(oldName)) {
5803 // This package is derived from an original package,
5804 // and this device has been updating from that original
5805 // name. We must continue using the original name, so
5806 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005807 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005808 pkgName = pkg.packageName;
5809 replace = true;
5810 } else if (mPackages.containsKey(pkgName)) {
5811 // This package, under its official name, already exists
5812 // on the device; we should replace it.
5813 replace = true;
5814 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005815 }
5816 PackageSetting ps = mSettings.mPackages.get(pkgName);
5817 if (ps != null) {
5818 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5819 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5820 systemApp = (ps.pkg.applicationInfo.flags &
5821 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005822 }
5823 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005825
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005826 if (systemApp && onSd) {
5827 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005828 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005829 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5830 return;
5831 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005832
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005833 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5834 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5835 return;
5836 }
5837 // Set application objects path explicitly after the rename
5838 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005839 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005840 replacePackageLI(pkg, parseFlags, scanMode,
5841 installerPackageName, res);
5842 } else {
5843 installNewPackageLI(pkg, parseFlags, scanMode,
5844 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 }
5846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005847
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005848 private int setPermissionsLI(PackageParser.Package newPackage) {
5849 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005850 int retCode = 0;
5851 // TODO Gross hack but fix later. Ideally move this to be a post installation
5852 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005853 if ((newPackage.applicationInfo.flags
5854 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5855 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 try {
5857 extractPublicFiles(newPackage, destResourceFile);
5858 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005859 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 -08005860 " forward-locked app.");
5861 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5862 } finally {
5863 //TODO clean up the extracted public files
5864 }
5865 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005866 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 newPackage.applicationInfo.uid);
5868 } else {
5869 final int filePermissions =
5870 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005871 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 newPackage.applicationInfo.uid);
5873 }
5874 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005875 // The permissions on the resource file was set when it was copied for
5876 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005880 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005881 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005883 // TODO Define new internal error
5884 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
5886 return PackageManager.INSTALL_SUCCEEDED;
5887 }
5888
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005889 private boolean isForwardLocked(PackageParser.Package pkg) {
5890 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 }
5892
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005893 private boolean isExternal(PackageParser.Package pkg) {
5894 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5895 }
5896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 private void extractPublicFiles(PackageParser.Package newPackage,
5898 File publicZipFile) throws IOException {
5899 final ZipOutputStream publicZipOutStream =
5900 new ZipOutputStream(new FileOutputStream(publicZipFile));
5901 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5902
5903 // Copy manifest, resources.arsc and res directory to public zip
5904
5905 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5906 while (privateZipEntries.hasMoreElements()) {
5907 final ZipEntry zipEntry = privateZipEntries.nextElement();
5908 final String zipEntryName = zipEntry.getName();
5909 if ("AndroidManifest.xml".equals(zipEntryName)
5910 || "resources.arsc".equals(zipEntryName)
5911 || zipEntryName.startsWith("res/")) {
5912 try {
5913 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5914 } catch (IOException e) {
5915 try {
5916 publicZipOutStream.close();
5917 throw e;
5918 } finally {
5919 publicZipFile.delete();
5920 }
5921 }
5922 }
5923 }
5924
5925 publicZipOutStream.close();
5926 FileUtils.setPermissions(
5927 publicZipFile.getAbsolutePath(),
5928 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5929 -1, -1);
5930 }
5931
5932 private static void copyZipEntry(ZipEntry zipEntry,
5933 ZipFile inZipFile,
5934 ZipOutputStream outZipStream) throws IOException {
5935 byte[] buffer = new byte[4096];
5936 int num;
5937
5938 ZipEntry newEntry;
5939 if (zipEntry.getMethod() == ZipEntry.STORED) {
5940 // Preserve the STORED method of the input entry.
5941 newEntry = new ZipEntry(zipEntry);
5942 } else {
5943 // Create a new entry so that the compressed len is recomputed.
5944 newEntry = new ZipEntry(zipEntry.getName());
5945 }
5946 outZipStream.putNextEntry(newEntry);
5947
5948 InputStream data = inZipFile.getInputStream(zipEntry);
5949 while ((num = data.read(buffer)) > 0) {
5950 outZipStream.write(buffer, 0, num);
5951 }
5952 outZipStream.flush();
5953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 private void deleteTempPackageFiles() {
5956 FilenameFilter filter = new FilenameFilter() {
5957 public boolean accept(File dir, String name) {
5958 return name.startsWith("vmdl") && name.endsWith(".tmp");
5959 }
5960 };
5961 String tmpFilesList[] = mAppInstallDir.list(filter);
5962 if(tmpFilesList == null) {
5963 return;
5964 }
5965 for(int i = 0; i < tmpFilesList.length; i++) {
5966 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5967 tmpFile.delete();
5968 }
5969 }
5970
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 File tmpPackageFile;
5973 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005974 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005976 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 return null;
5978 }
5979 try {
5980 FileUtils.setPermissions(
5981 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5982 -1, -1);
5983 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005984 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 return null;
5986 }
5987 return tmpPackageFile;
5988 }
5989
5990 public void deletePackage(final String packageName,
5991 final IPackageDeleteObserver observer,
5992 final int flags) {
5993 mContext.enforceCallingOrSelfPermission(
5994 android.Manifest.permission.DELETE_PACKAGES, null);
5995 // Queue up an async operation since the package deletion may take a little while.
5996 mHandler.post(new Runnable() {
5997 public void run() {
5998 mHandler.removeCallbacks(this);
5999 final boolean succeded = deletePackageX(packageName, true, true, flags);
6000 if (observer != null) {
6001 try {
6002 observer.packageDeleted(succeded);
6003 } catch (RemoteException e) {
6004 Log.i(TAG, "Observer no longer exists.");
6005 } //end catch
6006 } //end if
6007 } //end run
6008 });
6009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 /**
6012 * This method is an internal method that could be get invoked either
6013 * to delete an installed package or to clean up a failed installation.
6014 * After deleting an installed package, a broadcast is sent to notify any
6015 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006016 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 * installation wouldn't have sent the initial broadcast either
6018 * The key steps in deleting a package are
6019 * deleting the package information in internal structures like mPackages,
6020 * deleting the packages base directories through installd
6021 * updating mSettings to reflect current status
6022 * persisting settings for later use
6023 * sending a broadcast if necessary
6024 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6026 boolean deleteCodeAndResources, int flags) {
6027 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006028 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006030 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6031 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6032 try {
6033 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006034 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006035 return false;
6036 }
6037 } catch (RemoteException e) {
6038 }
6039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 synchronized (mInstallLock) {
6041 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6042 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006045 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6046 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6047
6048 // If the removed package was a system update, the old system packaged
6049 // was re-enabled; we need to broadcast this information
6050 if (systemUpdate) {
6051 Bundle extras = new Bundle(1);
6052 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6053 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6054
6055 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
6056 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
6057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006059 // Force a gc here.
6060 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006061 // Delete the resources here after sending the broadcast to let
6062 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006063 if (info.args != null) {
6064 synchronized (mInstallLock) {
6065 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006066 }
6067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 return res;
6069 }
6070
6071 static class PackageRemovedInfo {
6072 String removedPackage;
6073 int uid = -1;
6074 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006075 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006076 // Clean up resources deleted packages.
6077 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 void sendBroadcast(boolean fullRemove, boolean replacing) {
6080 Bundle extras = new Bundle(1);
6081 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6082 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6083 if (replacing) {
6084 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6085 }
6086 if (removedPackage != null) {
6087 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6088 }
6089 if (removedUid >= 0) {
6090 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6091 }
6092 }
6093 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 /*
6096 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6097 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006098 * 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 -08006099 * delete a partially installed application.
6100 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006101 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 int flags) {
6103 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006104 if (outInfo != null) {
6105 outInfo.removedPackage = packageName;
6106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 removePackageLI(p, true);
6108 // Retrieve object to delete permissions for shared user later on
6109 PackageSetting deletedPs;
6110 synchronized (mPackages) {
6111 deletedPs = mSettings.mPackages.get(packageName);
6112 }
6113 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6114 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006115 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006117 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 + packageName + ", retcode=" + retCode);
6119 // we don't consider this to be a failure of the core package deletion
6120 }
6121 } else {
6122 //for emulator
6123 PackageParser.Package pkg = mPackages.get(packageName);
6124 File dataDir = new File(pkg.applicationInfo.dataDir);
6125 dataDir.delete();
6126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 }
6128 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006129 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006130 schedulePackageCleaning(packageName);
6131
6132 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6133 if (outInfo != null) {
6134 outInfo.removedUid = mSettings.removePackageLP(packageName);
6135 }
6136 if (deletedPs != null) {
6137 updatePermissionsLP(deletedPs.name, null, false, false);
6138 if (deletedPs.sharedUser != null) {
6139 // remove permissions associated with package
6140 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6141 }
6142 }
6143 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006144 // remove from preferred activities.
6145 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6146 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6147 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6148 removed.add(pa);
6149 }
6150 }
6151 for (PreferredActivity pa : removed) {
6152 mSettings.mPreferredActivities.removeFilter(pa);
6153 }
6154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006156 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 }
6158 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 /*
6161 * Tries to delete system package.
6162 */
6163 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006164 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 ApplicationInfo applicationInfo = p.applicationInfo;
6166 //applicable for non-partially installed applications only
6167 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006168 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 return false;
6170 }
6171 PackageSetting ps = null;
6172 // Confirm if the system package has been updated
6173 // An updated system app can be deleted. This will also have to restore
6174 // the system pkg from system partition
6175 synchronized (mPackages) {
6176 ps = mSettings.getDisabledSystemPkg(p.packageName);
6177 }
6178 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006179 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 return false;
6181 } else {
6182 Log.i(TAG, "Deleting system pkg from data partition");
6183 }
6184 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006185 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006186 boolean deleteCodeAndResources = false;
6187 if (ps.versionCode < p.mVersionCode) {
6188 // Delete code and resources for downgrades
6189 deleteCodeAndResources = true;
6190 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6191 flags &= ~PackageManager.DONT_DELETE_DATA;
6192 }
6193 } else {
6194 // Preserve data by setting flag
6195 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6196 flags |= PackageManager.DONT_DELETE_DATA;
6197 }
6198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6200 if (!ret) {
6201 return false;
6202 }
6203 synchronized (mPackages) {
6204 // Reinstate the old system package
6205 mSettings.enableSystemPackageLP(p.packageName);
6206 }
6207 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006208 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006210 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006213 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 return false;
6215 }
6216 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006217 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 mSettings.writeLP();
6219 }
6220 return true;
6221 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6224 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6225 ApplicationInfo applicationInfo = p.applicationInfo;
6226 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006227 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 return false;
6229 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006230 if (outInfo != null) {
6231 outInfo.uid = applicationInfo.uid;
6232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233
6234 // Delete package data from internal structures and also remove data if flag is set
6235 removePackageDataLI(p, outInfo, flags);
6236
6237 // Delete application code and resources
6238 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006239 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006240 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006241 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006242 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6243 PackageManager.INSTALL_FORWARD_LOCK : 0;
6244 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006245 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 }
6247 return true;
6248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 /*
6251 * This method handles package deletion in general
6252 */
6253 private boolean deletePackageLI(String packageName,
6254 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6255 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006256 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 return false;
6258 }
6259 PackageParser.Package p;
6260 boolean dataOnly = false;
6261 synchronized (mPackages) {
6262 p = mPackages.get(packageName);
6263 if (p == null) {
6264 //this retrieves partially installed apps
6265 dataOnly = true;
6266 PackageSetting ps = mSettings.mPackages.get(packageName);
6267 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006268 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 return false;
6270 }
6271 p = ps.pkg;
6272 }
6273 }
6274 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006275 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 return false;
6277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 if (dataOnly) {
6280 // Delete application data first
6281 removePackageDataLI(p, outInfo, flags);
6282 return true;
6283 }
6284 // At this point the package should have ApplicationInfo associated with it
6285 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006286 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 return false;
6288 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006289 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6291 Log.i(TAG, "Removing system package:"+p.packageName);
6292 // When an updated system application is deleted we delete the existing resources as well and
6293 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006294 ret = deleteSystemPackageLI(p, flags, outInfo);
6295 } else {
6296 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006297 // Kill application pre-emptively especially for apps on sd.
6298 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006299 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006301 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 public void clearApplicationUserData(final String packageName,
6305 final IPackageDataObserver observer) {
6306 mContext.enforceCallingOrSelfPermission(
6307 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6308 // Queue up an async operation since the package deletion may take a little while.
6309 mHandler.post(new Runnable() {
6310 public void run() {
6311 mHandler.removeCallbacks(this);
6312 final boolean succeeded;
6313 synchronized (mInstallLock) {
6314 succeeded = clearApplicationUserDataLI(packageName);
6315 }
6316 if (succeeded) {
6317 // invoke DeviceStorageMonitor's update method to clear any notifications
6318 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6319 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6320 if (dsm != null) {
6321 dsm.updateMemory();
6322 }
6323 }
6324 if(observer != null) {
6325 try {
6326 observer.onRemoveCompleted(packageName, succeeded);
6327 } catch (RemoteException e) {
6328 Log.i(TAG, "Observer no longer exists.");
6329 }
6330 } //end if observer
6331 } //end run
6332 });
6333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 private boolean clearApplicationUserDataLI(String packageName) {
6336 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006337 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 return false;
6339 }
6340 PackageParser.Package p;
6341 boolean dataOnly = false;
6342 synchronized (mPackages) {
6343 p = mPackages.get(packageName);
6344 if(p == null) {
6345 dataOnly = true;
6346 PackageSetting ps = mSettings.mPackages.get(packageName);
6347 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006348 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 return false;
6350 }
6351 p = ps.pkg;
6352 }
6353 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 if(!dataOnly) {
6356 //need to check this only for fully installed applications
6357 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006358 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 return false;
6360 }
6361 final ApplicationInfo applicationInfo = p.applicationInfo;
6362 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006363 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 return false;
6365 }
6366 }
6367 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006368 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006370 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 + packageName);
6372 return false;
6373 }
6374 }
6375 return true;
6376 }
6377
6378 public void deleteApplicationCacheFiles(final String packageName,
6379 final IPackageDataObserver observer) {
6380 mContext.enforceCallingOrSelfPermission(
6381 android.Manifest.permission.DELETE_CACHE_FILES, null);
6382 // Queue up an async operation since the package deletion may take a little while.
6383 mHandler.post(new Runnable() {
6384 public void run() {
6385 mHandler.removeCallbacks(this);
6386 final boolean succeded;
6387 synchronized (mInstallLock) {
6388 succeded = deleteApplicationCacheFilesLI(packageName);
6389 }
6390 if(observer != null) {
6391 try {
6392 observer.onRemoveCompleted(packageName, succeded);
6393 } catch (RemoteException e) {
6394 Log.i(TAG, "Observer no longer exists.");
6395 }
6396 } //end if observer
6397 } //end run
6398 });
6399 }
6400
6401 private boolean deleteApplicationCacheFilesLI(String packageName) {
6402 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006403 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 return false;
6405 }
6406 PackageParser.Package p;
6407 synchronized (mPackages) {
6408 p = mPackages.get(packageName);
6409 }
6410 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006411 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 return false;
6413 }
6414 final ApplicationInfo applicationInfo = p.applicationInfo;
6415 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006416 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return false;
6418 }
6419 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006420 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006422 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 + packageName);
6424 return false;
6425 }
6426 }
6427 return true;
6428 }
6429
6430 public void getPackageSizeInfo(final String packageName,
6431 final IPackageStatsObserver observer) {
6432 mContext.enforceCallingOrSelfPermission(
6433 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6434 // Queue up an async operation since the package deletion may take a little while.
6435 mHandler.post(new Runnable() {
6436 public void run() {
6437 mHandler.removeCallbacks(this);
6438 PackageStats lStats = new PackageStats(packageName);
6439 final boolean succeded;
6440 synchronized (mInstallLock) {
6441 succeded = getPackageSizeInfoLI(packageName, lStats);
6442 }
6443 if(observer != null) {
6444 try {
6445 observer.onGetStatsCompleted(lStats, succeded);
6446 } catch (RemoteException e) {
6447 Log.i(TAG, "Observer no longer exists.");
6448 }
6449 } //end if observer
6450 } //end run
6451 });
6452 }
6453
6454 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6455 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006456 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 return false;
6458 }
6459 PackageParser.Package p;
6460 boolean dataOnly = false;
6461 synchronized (mPackages) {
6462 p = mPackages.get(packageName);
6463 if(p == null) {
6464 dataOnly = true;
6465 PackageSetting ps = mSettings.mPackages.get(packageName);
6466 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006467 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 return false;
6469 }
6470 p = ps.pkg;
6471 }
6472 }
6473 String publicSrcDir = null;
6474 if(!dataOnly) {
6475 final ApplicationInfo applicationInfo = p.applicationInfo;
6476 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006477 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 return false;
6479 }
6480 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6481 }
6482 if (mInstaller != null) {
6483 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006484 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 if (res < 0) {
6486 return false;
6487 } else {
6488 return true;
6489 }
6490 }
6491 return true;
6492 }
6493
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 public void addPackageToPreferred(String packageName) {
6496 mContext.enforceCallingOrSelfPermission(
6497 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006498 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 }
6500
6501 public void removePackageFromPreferred(String packageName) {
6502 mContext.enforceCallingOrSelfPermission(
6503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006504 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 }
6506
6507 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006508 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 }
6510
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006511 int getUidTargetSdkVersionLockedLP(int uid) {
6512 Object obj = mSettings.getUserIdLP(uid);
6513 if (obj instanceof SharedUserSetting) {
6514 SharedUserSetting sus = (SharedUserSetting)obj;
6515 final int N = sus.packages.size();
6516 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6517 Iterator<PackageSetting> it = sus.packages.iterator();
6518 int i=0;
6519 while (it.hasNext()) {
6520 PackageSetting ps = it.next();
6521 if (ps.pkg != null) {
6522 int v = ps.pkg.applicationInfo.targetSdkVersion;
6523 if (v < vers) vers = v;
6524 }
6525 }
6526 return vers;
6527 } else if (obj instanceof PackageSetting) {
6528 PackageSetting ps = (PackageSetting)obj;
6529 if (ps.pkg != null) {
6530 return ps.pkg.applicationInfo.targetSdkVersion;
6531 }
6532 }
6533 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6534 }
6535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 public void addPreferredActivity(IntentFilter filter, int match,
6537 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006539 if (mContext.checkCallingOrSelfPermission(
6540 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6541 != PackageManager.PERMISSION_GRANTED) {
6542 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6543 < Build.VERSION_CODES.FROYO) {
6544 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6545 + Binder.getCallingUid());
6546 return;
6547 }
6548 mContext.enforceCallingOrSelfPermission(
6549 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6550 }
6551
6552 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6554 mSettings.mPreferredActivities.addFilter(
6555 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006556 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 }
6558 }
6559
Satish Sampath8dbe6122009-06-02 23:35:54 +01006560 public void replacePreferredActivity(IntentFilter filter, int match,
6561 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006562 if (filter.countActions() != 1) {
6563 throw new IllegalArgumentException(
6564 "replacePreferredActivity expects filter to have only 1 action.");
6565 }
6566 if (filter.countCategories() != 1) {
6567 throw new IllegalArgumentException(
6568 "replacePreferredActivity expects filter to have only 1 category.");
6569 }
6570 if (filter.countDataAuthorities() != 0
6571 || filter.countDataPaths() != 0
6572 || filter.countDataSchemes() != 0
6573 || filter.countDataTypes() != 0) {
6574 throw new IllegalArgumentException(
6575 "replacePreferredActivity expects filter to have no data authorities, " +
6576 "paths, schemes or types.");
6577 }
6578 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006579 if (mContext.checkCallingOrSelfPermission(
6580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6581 != PackageManager.PERMISSION_GRANTED) {
6582 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6583 < Build.VERSION_CODES.FROYO) {
6584 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6585 + Binder.getCallingUid());
6586 return;
6587 }
6588 mContext.enforceCallingOrSelfPermission(
6589 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6590 }
6591
Satish Sampath8dbe6122009-06-02 23:35:54 +01006592 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6593 String action = filter.getAction(0);
6594 String category = filter.getCategory(0);
6595 while (it.hasNext()) {
6596 PreferredActivity pa = it.next();
6597 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6598 it.remove();
6599 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6600 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6601 }
6602 }
6603 addPreferredActivity(filter, match, set, activity);
6604 }
6605 }
6606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006609 int uid = Binder.getCallingUid();
6610 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006611 if (pkg == null || pkg.applicationInfo.uid != uid) {
6612 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 clearPackagePreferredActivities() from uid "
6618 + Binder.getCallingUid());
6619 return;
6620 }
6621 mContext.enforceCallingOrSelfPermission(
6622 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6623 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006624 }
6625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006627 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 }
6629 }
6630 }
6631
6632 boolean clearPackagePreferredActivitiesLP(String packageName) {
6633 boolean changed = false;
6634 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6635 while (it.hasNext()) {
6636 PreferredActivity pa = it.next();
6637 if (pa.mActivity.getPackageName().equals(packageName)) {
6638 it.remove();
6639 changed = true;
6640 }
6641 }
6642 return changed;
6643 }
6644
6645 public int getPreferredActivities(List<IntentFilter> outFilters,
6646 List<ComponentName> outActivities, String packageName) {
6647
6648 int num = 0;
6649 synchronized (mPackages) {
6650 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6651 while (it.hasNext()) {
6652 PreferredActivity pa = it.next();
6653 if (packageName == null
6654 || pa.mActivity.getPackageName().equals(packageName)) {
6655 if (outFilters != null) {
6656 outFilters.add(new IntentFilter(pa));
6657 }
6658 if (outActivities != null) {
6659 outActivities.add(pa.mActivity);
6660 }
6661 }
6662 }
6663 }
6664
6665 return num;
6666 }
6667
6668 public void setApplicationEnabledSetting(String appPackageName,
6669 int newState, int flags) {
6670 setEnabledSetting(appPackageName, null, newState, flags);
6671 }
6672
6673 public void setComponentEnabledSetting(ComponentName componentName,
6674 int newState, int flags) {
6675 setEnabledSetting(componentName.getPackageName(),
6676 componentName.getClassName(), newState, flags);
6677 }
6678
6679 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006680 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6682 || newState == COMPONENT_ENABLED_STATE_ENABLED
6683 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6684 throw new IllegalArgumentException("Invalid new component state: "
6685 + newState);
6686 }
6687 PackageSetting pkgSetting;
6688 final int uid = Binder.getCallingUid();
6689 final int permission = mContext.checkCallingPermission(
6690 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6691 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006692 boolean sendNow = false;
6693 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006694 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006696 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006698 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006700 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006702 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 }
6704 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006705 "Unknown component: " + packageName
6706 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 }
6708 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6709 throw new SecurityException(
6710 "Permission Denial: attempt to change component state from pid="
6711 + Binder.getCallingPid()
6712 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6713 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006714 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006716 if (pkgSetting.enabled == newState) {
6717 // Nothing to do
6718 return;
6719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 pkgSetting.enabled = newState;
6721 } else {
6722 // We're dealing with a component level state change
6723 switch (newState) {
6724 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006725 if (!pkgSetting.enableComponentLP(className)) {
6726 return;
6727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 break;
6729 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006730 if (!pkgSetting.disableComponentLP(className)) {
6731 return;
6732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 break;
6734 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006735 if (!pkgSetting.restoreComponentLP(className)) {
6736 return;
6737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 break;
6739 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006740 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743 }
6744 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006745 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006746 components = mPendingBroadcasts.get(packageName);
6747 boolean newPackage = components == null;
6748 if (newPackage) {
6749 components = new ArrayList<String>();
6750 }
6751 if (!components.contains(componentName)) {
6752 components.add(componentName);
6753 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6755 sendNow = true;
6756 // Purge entry from pending broadcast list if another one exists already
6757 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006758 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006760 if (newPackage) {
6761 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006762 }
6763 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6764 // Schedule a message
6765 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6766 }
6767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 long callingId = Binder.clearCallingIdentity();
6771 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 if (sendNow) {
6773 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006774 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 } finally {
6777 Binder.restoreCallingIdentity(callingId);
6778 }
6779 }
6780
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006781 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006782 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6783 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6784 + " components=" + componentNames);
6785 Bundle extras = new Bundle(4);
6786 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6787 String nameList[] = new String[componentNames.size()];
6788 componentNames.toArray(nameList);
6789 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006790 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6791 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006792 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006793 }
6794
Jacek Surazski65e13172009-04-28 15:26:38 +02006795 public String getInstallerPackageName(String packageName) {
6796 synchronized (mPackages) {
6797 PackageSetting pkg = mSettings.mPackages.get(packageName);
6798 if (pkg == null) {
6799 throw new IllegalArgumentException("Unknown package: " + packageName);
6800 }
6801 return pkg.installerPackageName;
6802 }
6803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 public int getApplicationEnabledSetting(String appPackageName) {
6806 synchronized (mPackages) {
6807 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6808 if (pkg == null) {
6809 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6810 }
6811 return pkg.enabled;
6812 }
6813 }
6814
6815 public int getComponentEnabledSetting(ComponentName componentName) {
6816 synchronized (mPackages) {
6817 final String packageNameStr = componentName.getPackageName();
6818 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6819 if (pkg == null) {
6820 throw new IllegalArgumentException("Unknown component: " + componentName);
6821 }
6822 final String classNameStr = componentName.getClassName();
6823 return pkg.currentEnabledStateLP(classNameStr);
6824 }
6825 }
6826
6827 public void enterSafeMode() {
6828 if (!mSystemReady) {
6829 mSafeMode = true;
6830 }
6831 }
6832
6833 public void systemReady() {
6834 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006835
6836 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006837 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006838 mContext.getContentResolver(),
6839 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006840 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006841 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006842 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 }
6845
6846 public boolean isSafeMode() {
6847 return mSafeMode;
6848 }
6849
6850 public boolean hasSystemUidErrors() {
6851 return mHasSystemUidErrors;
6852 }
6853
6854 static String arrayToString(int[] array) {
6855 StringBuffer buf = new StringBuffer(128);
6856 buf.append('[');
6857 if (array != null) {
6858 for (int i=0; i<array.length; i++) {
6859 if (i > 0) buf.append(", ");
6860 buf.append(array[i]);
6861 }
6862 }
6863 buf.append(']');
6864 return buf.toString();
6865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 @Override
6868 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6869 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6870 != PackageManager.PERMISSION_GRANTED) {
6871 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6872 + Binder.getCallingPid()
6873 + ", uid=" + Binder.getCallingUid()
6874 + " without permission "
6875 + android.Manifest.permission.DUMP);
6876 return;
6877 }
6878
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006879 String packageName = null;
6880
6881 int opti = 0;
6882 while (opti < args.length) {
6883 String opt = args[opti];
6884 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6885 break;
6886 }
6887 opti++;
6888 if ("-a".equals(opt)) {
6889 // Right now we only know how to print all.
6890 } else if ("-h".equals(opt)) {
6891 pw.println("Package manager dump options:");
6892 pw.println(" [-h] [cmd] ...");
6893 pw.println(" cmd may be one of:");
6894 pw.println(" [package.name]: info about given package");
6895 return;
6896 } else {
6897 pw.println("Unknown argument: " + opt + "; use -h for help");
6898 }
6899 }
6900
6901 // Is the caller requesting to dump a particular piece of data?
6902 if (opti < args.length) {
6903 String cmd = args[opti];
6904 opti++;
6905 // Is this a package name?
6906 if ("android".equals(cmd) || cmd.contains(".")) {
6907 packageName = cmd;
6908 }
6909 }
6910
6911 boolean printedTitle = false;
6912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006914 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6915 printedTitle = true;
6916 }
6917 if (mReceivers.dump(pw, printedTitle
6918 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6919 " ", packageName)) {
6920 printedTitle = true;
6921 }
6922 if (mServices.dump(pw, printedTitle
6923 ? "\nService Resolver Table:" : "Service Resolver Table:",
6924 " ", packageName)) {
6925 printedTitle = true;
6926 }
6927 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6928 ? "\nPreferred Activities:" : "Preferred Activities:",
6929 " ", packageName)) {
6930 printedTitle = true;
6931 }
6932 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 {
6934 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006935 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6936 continue;
6937 }
6938 if (!printedSomething) {
6939 if (printedTitle) pw.println(" ");
6940 pw.println("Permissions:");
6941 printedSomething = true;
6942 printedTitle = true;
6943 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006944 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6945 pw.print(Integer.toHexString(System.identityHashCode(p)));
6946 pw.println("):");
6947 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6948 pw.print(" uid="); pw.print(p.uid);
6949 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006950 pw.print(" type="); pw.print(p.type);
6951 pw.print(" prot="); pw.println(p.protectionLevel);
6952 if (p.packageSetting != null) {
6953 pw.print(" packageSetting="); pw.println(p.packageSetting);
6954 }
6955 if (p.perm != null) {
6956 pw.print(" perm="); pw.println(p.perm);
6957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 }
6959 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006960 printedSomething = false;
6961 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 {
6963 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006964 if (packageName != null && !packageName.equals(ps.realName)
6965 && !packageName.equals(ps.name)) {
6966 continue;
6967 }
6968 if (!printedSomething) {
6969 if (printedTitle) pw.println(" ");
6970 pw.println("Packages:");
6971 printedSomething = true;
6972 printedTitle = true;
6973 }
6974 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006975 pw.print(" Package [");
6976 pw.print(ps.realName != null ? ps.realName : ps.name);
6977 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006978 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6979 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006980 if (ps.realName != null) {
6981 pw.print(" compat name="); pw.println(ps.name);
6982 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006983 pw.print(" userId="); pw.print(ps.userId);
6984 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6985 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6986 pw.print(" pkg="); pw.println(ps.pkg);
6987 pw.print(" codePath="); pw.println(ps.codePathString);
6988 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006990 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006991 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006992 pw.print(" supportsScreens=[");
6993 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006994 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006995 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006996 if (!first) pw.print(", ");
6997 first = false;
6998 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007000 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007001 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007002 if (!first) pw.print(", ");
7003 first = false;
7004 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007006 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007007 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007008 if (!first) pw.print(", ");
7009 first = false;
7010 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007012 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007013 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007014 if (!first) pw.print(", ");
7015 first = false;
7016 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007018 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007019 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7020 if (!first) pw.print(", ");
7021 first = false;
7022 pw.print("anyDensity");
7023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007025 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007026 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7027 pw.print(" signatures="); pw.println(ps.signatures);
7028 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007029 pw.print(" haveGids="); pw.println(ps.haveGids);
7030 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007031 pw.print(" installStatus="); pw.print(ps.installStatus);
7032 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 if (ps.disabledComponents.size() > 0) {
7034 pw.println(" disabledComponents:");
7035 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007036 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 }
7038 }
7039 if (ps.enabledComponents.size() > 0) {
7040 pw.println(" enabledComponents:");
7041 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007042 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 }
7044 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007045 if (ps.grantedPermissions.size() > 0) {
7046 pw.println(" grantedPermissions:");
7047 for (String s : ps.grantedPermissions) {
7048 pw.print(" "); pw.println(s);
7049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 }
7052 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007053 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007054 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007055 for (HashMap.Entry<String, String> e
7056 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007057 if (packageName != null && !packageName.equals(e.getKey())
7058 && !packageName.equals(e.getValue())) {
7059 continue;
7060 }
7061 if (!printedSomething) {
7062 if (printedTitle) pw.println(" ");
7063 pw.println("Renamed packages:");
7064 printedSomething = true;
7065 printedTitle = true;
7066 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007067 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7068 pw.println(e.getValue());
7069 }
7070 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007071 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007072 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007073 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007074 if (packageName != null && !packageName.equals(ps.realName)
7075 && !packageName.equals(ps.name)) {
7076 continue;
7077 }
7078 if (!printedSomething) {
7079 if (printedTitle) pw.println(" ");
7080 pw.println("Hidden system packages:");
7081 printedSomething = true;
7082 printedTitle = true;
7083 }
7084 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 pw.print(ps.realName != null ? ps.realName : ps.name);
7086 pw.print("] (");
7087 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7088 pw.println("):");
7089 if (ps.realName != null) {
7090 pw.print(" compat name="); pw.println(ps.name);
7091 }
7092 pw.print(" userId="); pw.println(ps.userId);
7093 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7094 pw.print(" codePath="); pw.println(ps.codePathString);
7095 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7096 }
7097 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007098 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 {
7100 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007101 if (packageName != null && su != packageSharedUser) {
7102 continue;
7103 }
7104 if (!printedSomething) {
7105 if (printedTitle) pw.println(" ");
7106 pw.println("Shared users:");
7107 printedSomething = true;
7108 printedTitle = true;
7109 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007110 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7111 pw.print(Integer.toHexString(System.identityHashCode(su)));
7112 pw.println("):");
7113 pw.print(" userId="); pw.print(su.userId);
7114 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 pw.println(" grantedPermissions:");
7116 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007117 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 }
7120 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007121
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007122 if (packageName == null) {
7123 if (printedTitle) pw.println(" ");
7124 printedTitle = true;
7125 pw.println("Settings parse messages:");
7126 pw.println(mSettings.mReadMessages.toString());
7127
7128 pw.println(" ");
7129 pw.println("Package warning messages:");
7130 File fname = getSettingsProblemFile();
7131 FileInputStream in;
7132 try {
7133 in = new FileInputStream(fname);
7134 int avail = in.available();
7135 byte[] data = new byte[avail];
7136 in.read(data);
7137 pw.println(new String(data));
7138 } catch (FileNotFoundException e) {
7139 } catch (IOException e) {
7140 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007143
7144 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007145 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007146 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007147 if (packageName != null && !packageName.equals(p.info.packageName)) {
7148 continue;
7149 }
7150 if (!printedSomething) {
7151 if (printedTitle) pw.println(" ");
7152 pw.println("Registered ContentProviders:");
7153 printedSomething = true;
7154 printedTitle = true;
7155 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007156 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007157 pw.println(p.toString());
7158 }
7159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 }
7161
7162 static final class BasePermission {
7163 final static int TYPE_NORMAL = 0;
7164 final static int TYPE_BUILTIN = 1;
7165 final static int TYPE_DYNAMIC = 2;
7166
7167 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007168 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007169 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007171 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007172 PackageParser.Permission perm;
7173 PermissionInfo pendingInfo;
7174 int uid;
7175 int[] gids;
7176
7177 BasePermission(String _name, String _sourcePackage, int _type) {
7178 name = _name;
7179 sourcePackage = _sourcePackage;
7180 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007181 // Default to most conservative protection level.
7182 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7183 }
7184
7185 public String toString() {
7186 return "BasePermission{"
7187 + Integer.toHexString(System.identityHashCode(this))
7188 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 }
7190 }
7191
7192 static class PackageSignatures {
7193 private Signature[] mSignatures;
7194
7195 PackageSignatures(Signature[] sigs) {
7196 assignSignatures(sigs);
7197 }
7198
7199 PackageSignatures() {
7200 }
7201
7202 void writeXml(XmlSerializer serializer, String tagName,
7203 ArrayList<Signature> pastSignatures) throws IOException {
7204 if (mSignatures == null) {
7205 return;
7206 }
7207 serializer.startTag(null, tagName);
7208 serializer.attribute(null, "count",
7209 Integer.toString(mSignatures.length));
7210 for (int i=0; i<mSignatures.length; i++) {
7211 serializer.startTag(null, "cert");
7212 final Signature sig = mSignatures[i];
7213 final int sigHash = sig.hashCode();
7214 final int numPast = pastSignatures.size();
7215 int j;
7216 for (j=0; j<numPast; j++) {
7217 Signature pastSig = pastSignatures.get(j);
7218 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7219 serializer.attribute(null, "index", Integer.toString(j));
7220 break;
7221 }
7222 }
7223 if (j >= numPast) {
7224 pastSignatures.add(sig);
7225 serializer.attribute(null, "index", Integer.toString(numPast));
7226 serializer.attribute(null, "key", sig.toCharsString());
7227 }
7228 serializer.endTag(null, "cert");
7229 }
7230 serializer.endTag(null, tagName);
7231 }
7232
7233 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7234 throws IOException, XmlPullParserException {
7235 String countStr = parser.getAttributeValue(null, "count");
7236 if (countStr == null) {
7237 reportSettingsProblem(Log.WARN,
7238 "Error in package manager settings: <signatures> has"
7239 + " no count at " + parser.getPositionDescription());
7240 XmlUtils.skipCurrentTag(parser);
7241 }
7242 final int count = Integer.parseInt(countStr);
7243 mSignatures = new Signature[count];
7244 int pos = 0;
7245
7246 int outerDepth = parser.getDepth();
7247 int type;
7248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7249 && (type != XmlPullParser.END_TAG
7250 || parser.getDepth() > outerDepth)) {
7251 if (type == XmlPullParser.END_TAG
7252 || type == XmlPullParser.TEXT) {
7253 continue;
7254 }
7255
7256 String tagName = parser.getName();
7257 if (tagName.equals("cert")) {
7258 if (pos < count) {
7259 String index = parser.getAttributeValue(null, "index");
7260 if (index != null) {
7261 try {
7262 int idx = Integer.parseInt(index);
7263 String key = parser.getAttributeValue(null, "key");
7264 if (key == null) {
7265 if (idx >= 0 && idx < pastSignatures.size()) {
7266 Signature sig = pastSignatures.get(idx);
7267 if (sig != null) {
7268 mSignatures[pos] = pastSignatures.get(idx);
7269 pos++;
7270 } else {
7271 reportSettingsProblem(Log.WARN,
7272 "Error in package manager settings: <cert> "
7273 + "index " + index + " is not defined at "
7274 + parser.getPositionDescription());
7275 }
7276 } else {
7277 reportSettingsProblem(Log.WARN,
7278 "Error in package manager settings: <cert> "
7279 + "index " + index + " is out of bounds at "
7280 + parser.getPositionDescription());
7281 }
7282 } else {
7283 while (pastSignatures.size() <= idx) {
7284 pastSignatures.add(null);
7285 }
7286 Signature sig = new Signature(key);
7287 pastSignatures.set(idx, sig);
7288 mSignatures[pos] = sig;
7289 pos++;
7290 }
7291 } catch (NumberFormatException e) {
7292 reportSettingsProblem(Log.WARN,
7293 "Error in package manager settings: <cert> "
7294 + "index " + index + " is not a number at "
7295 + parser.getPositionDescription());
7296 }
7297 } else {
7298 reportSettingsProblem(Log.WARN,
7299 "Error in package manager settings: <cert> has"
7300 + " no index at " + parser.getPositionDescription());
7301 }
7302 } else {
7303 reportSettingsProblem(Log.WARN,
7304 "Error in package manager settings: too "
7305 + "many <cert> tags, expected " + count
7306 + " at " + parser.getPositionDescription());
7307 }
7308 } else {
7309 reportSettingsProblem(Log.WARN,
7310 "Unknown element under <cert>: "
7311 + parser.getName());
7312 }
7313 XmlUtils.skipCurrentTag(parser);
7314 }
7315
7316 if (pos < count) {
7317 // Should never happen -- there is an error in the written
7318 // settings -- but if it does we don't want to generate
7319 // a bad array.
7320 Signature[] newSigs = new Signature[pos];
7321 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7322 mSignatures = newSigs;
7323 }
7324 }
7325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 private void assignSignatures(Signature[] sigs) {
7327 if (sigs == null) {
7328 mSignatures = null;
7329 return;
7330 }
7331 mSignatures = new Signature[sigs.length];
7332 for (int i=0; i<sigs.length; i++) {
7333 mSignatures[i] = sigs[i];
7334 }
7335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 @Override
7338 public String toString() {
7339 StringBuffer buf = new StringBuffer(128);
7340 buf.append("PackageSignatures{");
7341 buf.append(Integer.toHexString(System.identityHashCode(this)));
7342 buf.append(" [");
7343 if (mSignatures != null) {
7344 for (int i=0; i<mSignatures.length; i++) {
7345 if (i > 0) buf.append(", ");
7346 buf.append(Integer.toHexString(
7347 System.identityHashCode(mSignatures[i])));
7348 }
7349 }
7350 buf.append("]}");
7351 return buf.toString();
7352 }
7353 }
7354
7355 static class PreferredActivity extends IntentFilter {
7356 final int mMatch;
7357 final String[] mSetPackages;
7358 final String[] mSetClasses;
7359 final String[] mSetComponents;
7360 final ComponentName mActivity;
7361 final String mShortActivity;
7362 String mParseError;
7363
7364 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7365 ComponentName activity) {
7366 super(filter);
7367 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7368 mActivity = activity;
7369 mShortActivity = activity.flattenToShortString();
7370 mParseError = null;
7371 if (set != null) {
7372 final int N = set.length;
7373 String[] myPackages = new String[N];
7374 String[] myClasses = new String[N];
7375 String[] myComponents = new String[N];
7376 for (int i=0; i<N; i++) {
7377 ComponentName cn = set[i];
7378 if (cn == null) {
7379 mSetPackages = null;
7380 mSetClasses = null;
7381 mSetComponents = null;
7382 return;
7383 }
7384 myPackages[i] = cn.getPackageName().intern();
7385 myClasses[i] = cn.getClassName().intern();
7386 myComponents[i] = cn.flattenToShortString().intern();
7387 }
7388 mSetPackages = myPackages;
7389 mSetClasses = myClasses;
7390 mSetComponents = myComponents;
7391 } else {
7392 mSetPackages = null;
7393 mSetClasses = null;
7394 mSetComponents = null;
7395 }
7396 }
7397
7398 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7399 IOException {
7400 mShortActivity = parser.getAttributeValue(null, "name");
7401 mActivity = ComponentName.unflattenFromString(mShortActivity);
7402 if (mActivity == null) {
7403 mParseError = "Bad activity name " + mShortActivity;
7404 }
7405 String matchStr = parser.getAttributeValue(null, "match");
7406 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7407 String setCountStr = parser.getAttributeValue(null, "set");
7408 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7409
7410 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7411 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7412 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7413
7414 int setPos = 0;
7415
7416 int outerDepth = parser.getDepth();
7417 int type;
7418 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7419 && (type != XmlPullParser.END_TAG
7420 || parser.getDepth() > outerDepth)) {
7421 if (type == XmlPullParser.END_TAG
7422 || type == XmlPullParser.TEXT) {
7423 continue;
7424 }
7425
7426 String tagName = parser.getName();
7427 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7428 // + parser.getDepth() + " tag=" + tagName);
7429 if (tagName.equals("set")) {
7430 String name = parser.getAttributeValue(null, "name");
7431 if (name == null) {
7432 if (mParseError == null) {
7433 mParseError = "No name in set tag in preferred activity "
7434 + mShortActivity;
7435 }
7436 } else if (setPos >= setCount) {
7437 if (mParseError == null) {
7438 mParseError = "Too many set tags in preferred activity "
7439 + mShortActivity;
7440 }
7441 } else {
7442 ComponentName cn = ComponentName.unflattenFromString(name);
7443 if (cn == null) {
7444 if (mParseError == null) {
7445 mParseError = "Bad set name " + name + " in preferred activity "
7446 + mShortActivity;
7447 }
7448 } else {
7449 myPackages[setPos] = cn.getPackageName();
7450 myClasses[setPos] = cn.getClassName();
7451 myComponents[setPos] = name;
7452 setPos++;
7453 }
7454 }
7455 XmlUtils.skipCurrentTag(parser);
7456 } else if (tagName.equals("filter")) {
7457 //Log.i(TAG, "Starting to parse filter...");
7458 readFromXml(parser);
7459 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7460 // + parser.getDepth() + " tag=" + parser.getName());
7461 } else {
7462 reportSettingsProblem(Log.WARN,
7463 "Unknown element under <preferred-activities>: "
7464 + parser.getName());
7465 XmlUtils.skipCurrentTag(parser);
7466 }
7467 }
7468
7469 if (setPos != setCount) {
7470 if (mParseError == null) {
7471 mParseError = "Not enough set tags (expected " + setCount
7472 + " but found " + setPos + ") in " + mShortActivity;
7473 }
7474 }
7475
7476 mSetPackages = myPackages;
7477 mSetClasses = myClasses;
7478 mSetComponents = myComponents;
7479 }
7480
7481 public void writeToXml(XmlSerializer serializer) throws IOException {
7482 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7483 serializer.attribute(null, "name", mShortActivity);
7484 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7485 serializer.attribute(null, "set", Integer.toString(NS));
7486 for (int s=0; s<NS; s++) {
7487 serializer.startTag(null, "set");
7488 serializer.attribute(null, "name", mSetComponents[s]);
7489 serializer.endTag(null, "set");
7490 }
7491 serializer.startTag(null, "filter");
7492 super.writeToXml(serializer);
7493 serializer.endTag(null, "filter");
7494 }
7495
7496 boolean sameSet(List<ResolveInfo> query, int priority) {
7497 if (mSetPackages == null) return false;
7498 final int NQ = query.size();
7499 final int NS = mSetPackages.length;
7500 int numMatch = 0;
7501 for (int i=0; i<NQ; i++) {
7502 ResolveInfo ri = query.get(i);
7503 if (ri.priority != priority) continue;
7504 ActivityInfo ai = ri.activityInfo;
7505 boolean good = false;
7506 for (int j=0; j<NS; j++) {
7507 if (mSetPackages[j].equals(ai.packageName)
7508 && mSetClasses[j].equals(ai.name)) {
7509 numMatch++;
7510 good = true;
7511 break;
7512 }
7513 }
7514 if (!good) return false;
7515 }
7516 return numMatch == NS;
7517 }
7518 }
7519
7520 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007521 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 HashSet<String> grantedPermissions = new HashSet<String>();
7524 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007527 setFlags(pkgFlags);
7528 }
7529
7530 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007531 this.pkgFlags = pkgFlags & (
7532 ApplicationInfo.FLAG_SYSTEM |
7533 ApplicationInfo.FLAG_FORWARD_LOCK |
7534 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 }
7536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 /**
7539 * Settings base class for pending and resolved classes.
7540 */
7541 static class PackageSettingBase extends GrantedPermissions {
7542 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007543 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007544 File codePath;
7545 String codePathString;
7546 File resourcePath;
7547 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 private long timeStamp;
7549 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007550 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007552 boolean uidError;
7553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 PackageSignatures signatures = new PackageSignatures();
7555
7556 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007557 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007559 /* Explicitly disabled components */
7560 HashSet<String> disabledComponents = new HashSet<String>(0);
7561 /* Explicitly enabled components */
7562 HashSet<String> enabledComponents = new HashSet<String>(0);
7563 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7564 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007565
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007566 PackageSettingBase origPackage;
7567
Jacek Surazski65e13172009-04-28 15:26:38 +02007568 /* package name of the app that installed this package */
7569 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007571 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007572 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 super(pkgFlags);
7574 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007575 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007576 init(codePath, resourcePath, pVersionCode);
7577 }
7578
7579 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580 this.codePath = codePath;
7581 this.codePathString = codePath.toString();
7582 this.resourcePath = resourcePath;
7583 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007584 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007586
Jacek Surazski65e13172009-04-28 15:26:38 +02007587 public void setInstallerPackageName(String packageName) {
7588 installerPackageName = packageName;
7589 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007590
Jacek Surazski65e13172009-04-28 15:26:38 +02007591 String getInstallerPackageName() {
7592 return installerPackageName;
7593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 public void setInstallStatus(int newStatus) {
7596 installStatus = newStatus;
7597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 public int getInstallStatus() {
7600 return installStatus;
7601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 public void setTimeStamp(long newStamp) {
7604 if (newStamp != timeStamp) {
7605 timeStamp = newStamp;
7606 timeStampString = Long.toString(newStamp);
7607 }
7608 }
7609
7610 public void setTimeStamp(long newStamp, String newStampStr) {
7611 timeStamp = newStamp;
7612 timeStampString = newStampStr;
7613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007615 public long getTimeStamp() {
7616 return timeStamp;
7617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 public String getTimeStampStr() {
7620 return timeStampString;
7621 }
7622
7623 public void copyFrom(PackageSettingBase base) {
7624 grantedPermissions = base.grantedPermissions;
7625 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 timeStamp = base.timeStamp;
7628 timeStampString = base.timeStampString;
7629 signatures = base.signatures;
7630 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007631 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 disabledComponents = base.disabledComponents;
7633 enabledComponents = base.enabledComponents;
7634 enabled = base.enabled;
7635 installStatus = base.installStatus;
7636 }
7637
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007638 boolean enableComponentLP(String componentClassName) {
7639 boolean changed = disabledComponents.remove(componentClassName);
7640 changed |= enabledComponents.add(componentClassName);
7641 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 }
7643
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007644 boolean disableComponentLP(String componentClassName) {
7645 boolean changed = enabledComponents.remove(componentClassName);
7646 changed |= disabledComponents.add(componentClassName);
7647 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007648 }
7649
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007650 boolean restoreComponentLP(String componentClassName) {
7651 boolean changed = enabledComponents.remove(componentClassName);
7652 changed |= disabledComponents.remove(componentClassName);
7653 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 }
7655
7656 int currentEnabledStateLP(String componentName) {
7657 if (enabledComponents.contains(componentName)) {
7658 return COMPONENT_ENABLED_STATE_ENABLED;
7659 } else if (disabledComponents.contains(componentName)) {
7660 return COMPONENT_ENABLED_STATE_DISABLED;
7661 } else {
7662 return COMPONENT_ENABLED_STATE_DEFAULT;
7663 }
7664 }
7665 }
7666
7667 /**
7668 * Settings data for a particular package we know about.
7669 */
7670 static final class PackageSetting extends PackageSettingBase {
7671 int userId;
7672 PackageParser.Package pkg;
7673 SharedUserSetting sharedUser;
7674
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007675 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007676 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007677 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 @Override
7681 public String toString() {
7682 return "PackageSetting{"
7683 + Integer.toHexString(System.identityHashCode(this))
7684 + " " + name + "/" + userId + "}";
7685 }
7686 }
7687
7688 /**
7689 * Settings data for a particular shared user ID we know about.
7690 */
7691 static final class SharedUserSetting extends GrantedPermissions {
7692 final String name;
7693 int userId;
7694 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7695 final PackageSignatures signatures = new PackageSignatures();
7696
7697 SharedUserSetting(String _name, int _pkgFlags) {
7698 super(_pkgFlags);
7699 name = _name;
7700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 @Override
7703 public String toString() {
7704 return "SharedUserSetting{"
7705 + Integer.toHexString(System.identityHashCode(this))
7706 + " " + name + "/" + userId + "}";
7707 }
7708 }
7709
7710 /**
7711 * Holds information about dynamic settings.
7712 */
7713 private static final class Settings {
7714 private final File mSettingsFilename;
7715 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007716 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 private final HashMap<String, PackageSetting> mPackages =
7718 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 // List of replaced system applications
7720 final HashMap<String, PackageSetting> mDisabledSysPackages =
7721 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007722
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007723 // These are the last platform API version we were using for
7724 // the apps installed on internal and external storage. It is
7725 // used to grant newer permissions one time during a system upgrade.
7726 int mInternalSdkPlatform;
7727 int mExternalSdkPlatform;
7728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 // The user's preferred activities associated with particular intent
7730 // filters.
7731 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7732 new IntentResolver<PreferredActivity, PreferredActivity>() {
7733 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007734 protected String packageForFilter(PreferredActivity filter) {
7735 return filter.mActivity.getPackageName();
7736 }
7737 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007738 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007740 out.print(prefix); out.print(
7741 Integer.toHexString(System.identityHashCode(filter)));
7742 out.print(' ');
7743 out.print(filter.mActivity.flattenToShortString());
7744 out.print(" match=0x");
7745 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007746 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007747 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007749 out.print(prefix); out.print(" ");
7750 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 }
7752 }
7753 }
7754 };
7755 private final HashMap<String, SharedUserSetting> mSharedUsers =
7756 new HashMap<String, SharedUserSetting>();
7757 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7758 private final SparseArray<Object> mOtherUserIds =
7759 new SparseArray<Object>();
7760
7761 // For reading/writing settings file.
7762 private final ArrayList<Signature> mPastSignatures =
7763 new ArrayList<Signature>();
7764
7765 // Mapping from permission names to info about them.
7766 final HashMap<String, BasePermission> mPermissions =
7767 new HashMap<String, BasePermission>();
7768
7769 // Mapping from permission tree names to info about them.
7770 final HashMap<String, BasePermission> mPermissionTrees =
7771 new HashMap<String, BasePermission>();
7772
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007773 // Packages that have been uninstalled and still need their external
7774 // storage data deleted.
7775 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7776
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007777 // Packages that have been renamed since they were first installed.
7778 // Keys are the new names of the packages, values are the original
7779 // names. The packages appear everwhere else under their original
7780 // names.
7781 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 private final StringBuilder mReadMessages = new StringBuilder();
7784
7785 private static final class PendingPackage extends PackageSettingBase {
7786 final int sharedId;
7787
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007788 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007789 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007790 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 this.sharedId = sharedId;
7792 }
7793 }
7794 private final ArrayList<PendingPackage> mPendingPackages
7795 = new ArrayList<PendingPackage>();
7796
7797 Settings() {
7798 File dataDir = Environment.getDataDirectory();
7799 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007800 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 systemDir.mkdirs();
7802 FileUtils.setPermissions(systemDir.toString(),
7803 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7804 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7805 -1, -1);
7806 mSettingsFilename = new File(systemDir, "packages.xml");
7807 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007808 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 }
7810
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007811 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007812 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 int pkgFlags, boolean create, boolean add) {
7814 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007815 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007816 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 return p;
7818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007819
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007820 PackageSetting peekPackageLP(String name) {
7821 return mPackages.get(name);
7822 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 PackageSetting p = mPackages.get(name);
7824 if (p != null && p.codePath.getPath().equals(codePath)) {
7825 return p;
7826 }
7827 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007828 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 void setInstallStatus(String pkgName, int status) {
7832 PackageSetting p = mPackages.get(pkgName);
7833 if(p != null) {
7834 if(p.getInstallStatus() != status) {
7835 p.setInstallStatus(status);
7836 }
7837 }
7838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839
Jacek Surazski65e13172009-04-28 15:26:38 +02007840 void setInstallerPackageName(String pkgName,
7841 String installerPkgName) {
7842 PackageSetting p = mPackages.get(pkgName);
7843 if(p != null) {
7844 p.setInstallerPackageName(installerPkgName);
7845 }
7846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007847
Jacek Surazski65e13172009-04-28 15:26:38 +02007848 String getInstallerPackageName(String pkgName) {
7849 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007850 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007851 }
7852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 int getInstallStatus(String pkgName) {
7854 PackageSetting p = mPackages.get(pkgName);
7855 if(p != null) {
7856 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 return -1;
7859 }
7860
7861 SharedUserSetting getSharedUserLP(String name,
7862 int pkgFlags, boolean create) {
7863 SharedUserSetting s = mSharedUsers.get(name);
7864 if (s == null) {
7865 if (!create) {
7866 return null;
7867 }
7868 s = new SharedUserSetting(name, pkgFlags);
7869 if (MULTIPLE_APPLICATION_UIDS) {
7870 s.userId = newUserIdLP(s);
7871 } else {
7872 s.userId = FIRST_APPLICATION_UID;
7873 }
7874 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7875 // < 0 means we couldn't assign a userid; fall out and return
7876 // s, which is currently null
7877 if (s.userId >= 0) {
7878 mSharedUsers.put(name, s);
7879 }
7880 }
7881
7882 return s;
7883 }
7884
7885 int disableSystemPackageLP(String name) {
7886 PackageSetting p = mPackages.get(name);
7887 if(p == null) {
7888 Log.w(TAG, "Package:"+name+" is not an installed package");
7889 return -1;
7890 }
7891 PackageSetting dp = mDisabledSysPackages.get(name);
7892 // always make sure the system package code and resource paths dont change
7893 if(dp == null) {
7894 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7895 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7896 }
7897 mDisabledSysPackages.put(name, p);
7898 }
7899 return removePackageLP(name);
7900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 PackageSetting enableSystemPackageLP(String name) {
7903 PackageSetting p = mDisabledSysPackages.get(name);
7904 if(p == null) {
7905 Log.w(TAG, "Package:"+name+" is not disabled");
7906 return null;
7907 }
7908 // Reset flag in ApplicationInfo object
7909 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7910 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7911 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007912 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007913 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 mDisabledSysPackages.remove(name);
7915 return ret;
7916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007917
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007918 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007919 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 PackageSetting p = mPackages.get(name);
7921 if (p != null) {
7922 if (p.userId == uid) {
7923 return p;
7924 }
7925 reportSettingsProblem(Log.ERROR,
7926 "Adding duplicate package, keeping first: " + name);
7927 return null;
7928 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007929 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 p.userId = uid;
7931 if (addUserIdLP(uid, p, name)) {
7932 mPackages.put(name, p);
7933 return p;
7934 }
7935 return null;
7936 }
7937
7938 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7939 SharedUserSetting s = mSharedUsers.get(name);
7940 if (s != null) {
7941 if (s.userId == uid) {
7942 return s;
7943 }
7944 reportSettingsProblem(Log.ERROR,
7945 "Adding duplicate shared user, keeping first: " + name);
7946 return null;
7947 }
7948 s = new SharedUserSetting(name, pkgFlags);
7949 s.userId = uid;
7950 if (addUserIdLP(uid, s, name)) {
7951 mSharedUsers.put(name, s);
7952 return s;
7953 }
7954 return null;
7955 }
7956
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007957 // Transfer ownership of permissions from one package to another.
7958 private void transferPermissions(String origPkg, String newPkg) {
7959 // Transfer ownership of permissions to the new package.
7960 for (int i=0; i<2; i++) {
7961 HashMap<String, BasePermission> permissions =
7962 i == 0 ? mPermissionTrees : mPermissions;
7963 for (BasePermission bp : permissions.values()) {
7964 if (origPkg.equals(bp.sourcePackage)) {
7965 if (DEBUG_UPGRADE) Log.v(TAG,
7966 "Moving permission " + bp.name
7967 + " from pkg " + bp.sourcePackage
7968 + " to " + newPkg);
7969 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007970 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007971 bp.perm = null;
7972 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007973 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007974 }
7975 bp.uid = 0;
7976 bp.gids = null;
7977 }
7978 }
7979 }
7980 }
7981
7982 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007983 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007984 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 PackageSetting p = mPackages.get(name);
7986 if (p != null) {
7987 if (!p.codePath.equals(codePath)) {
7988 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007989 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007990 // This is an updated system app with versions in both system
7991 // and data partition. Just let the most recent version
7992 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007993 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007994 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007995 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007996 // Just a change in the code path is not an issue, but
7997 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007998 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007999 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008001 }
8002 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 reportSettingsProblem(Log.WARN,
8004 "Package " + name + " shared user changed from "
8005 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8006 + " to "
8007 + (sharedUser != null ? sharedUser.name : "<nothing>")
8008 + "; replacing with new");
8009 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008010 } else {
8011 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8012 // If what we are scanning is a system package, then
8013 // make it so, regardless of whether it was previously
8014 // installed only in the data partition.
8015 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 }
8018 }
8019 if (p == null) {
8020 // Create a new PackageSettings entry. this can end up here because
8021 // of code path mismatch or user id mismatch of an updated system partition
8022 if (!create) {
8023 return null;
8024 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008025 if (origPackage != null) {
8026 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008027 p = new PackageSetting(origPackage.name, name, codePath,
8028 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008029 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8030 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008031 // Note that we will retain the new package's signature so
8032 // that we can keep its data.
8033 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008034 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008035 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008036 p.sharedUser = origPackage.sharedUser;
8037 p.userId = origPackage.userId;
8038 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008039 mRenamedPackages.put(name, origPackage.name);
8040 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008041 // Update new package state.
8042 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008044 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008045 p.setTimeStamp(codePath.lastModified());
8046 p.sharedUser = sharedUser;
8047 if (sharedUser != null) {
8048 p.userId = sharedUser.userId;
8049 } else if (MULTIPLE_APPLICATION_UIDS) {
8050 // Clone the setting here for disabled system packages
8051 PackageSetting dis = mDisabledSysPackages.get(name);
8052 if (dis != null) {
8053 // For disabled packages a new setting is created
8054 // from the existing user id. This still has to be
8055 // added to list of user id's
8056 // Copy signatures from previous setting
8057 if (dis.signatures.mSignatures != null) {
8058 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8059 }
8060 p.userId = dis.userId;
8061 // Clone permissions
8062 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008063 // Clone component info
8064 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8065 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8066 // Add new setting to list of user ids
8067 addUserIdLP(p.userId, p, name);
8068 } else {
8069 // Assign new user id
8070 p.userId = newUserIdLP(p);
8071 }
8072 } else {
8073 p.userId = FIRST_APPLICATION_UID;
8074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 }
8076 if (p.userId < 0) {
8077 reportSettingsProblem(Log.WARN,
8078 "Package " + name + " could not be assigned a valid uid");
8079 return null;
8080 }
8081 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008082 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008084 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 }
8086 }
8087 return p;
8088 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008089
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008090 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008091 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008092 String codePath = pkg.applicationInfo.sourceDir;
8093 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008094 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008095 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008096 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008097 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008098 p.codePath = new File(codePath);
8099 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008100 }
8101 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008102 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008103 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008104 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008105 p.resourcePath = new File(resourcePath);
8106 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008107 }
8108 // Update version code if needed
8109 if (pkg.mVersionCode != p.versionCode) {
8110 p.versionCode = pkg.mVersionCode;
8111 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008112 // Update signatures if needed.
8113 if (p.signatures.mSignatures == null) {
8114 p.signatures.assignSignatures(pkg.mSignatures);
8115 }
8116 // If this app defines a shared user id initialize
8117 // the shared user signatures as well.
8118 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8119 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8120 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008121 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8122 }
8123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 // Utility method that adds a PackageSetting to mPackages and
8125 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008126 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008127 SharedUserSetting sharedUser) {
8128 mPackages.put(name, p);
8129 if (sharedUser != null) {
8130 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8131 reportSettingsProblem(Log.ERROR,
8132 "Package " + p.name + " was user "
8133 + p.sharedUser + " but is now " + sharedUser
8134 + "; I am not changing its files so it will probably fail!");
8135 p.sharedUser.packages.remove(p);
8136 } else if (p.userId != sharedUser.userId) {
8137 reportSettingsProblem(Log.ERROR,
8138 "Package " + p.name + " was user id " + p.userId
8139 + " but is now user " + sharedUser
8140 + " with id " + sharedUser.userId
8141 + "; I am not changing its files so it will probably fail!");
8142 }
8143
8144 sharedUser.packages.add(p);
8145 p.sharedUser = sharedUser;
8146 p.userId = sharedUser.userId;
8147 }
8148 }
8149
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008150 /*
8151 * Update the shared user setting when a package using
8152 * specifying the shared user id is removed. The gids
8153 * associated with each permission of the deleted package
8154 * are removed from the shared user's gid list only if its
8155 * not in use by other permissions of packages in the
8156 * shared user setting.
8157 */
8158 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008160 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 return;
8162 }
8163 // No sharedUserId
8164 if (deletedPs.sharedUser == null) {
8165 return;
8166 }
8167 SharedUserSetting sus = deletedPs.sharedUser;
8168 // Update permissions
8169 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8170 boolean used = false;
8171 if (!sus.grantedPermissions.contains (eachPerm)) {
8172 continue;
8173 }
8174 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008175 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008176 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008177 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 used = true;
8179 break;
8180 }
8181 }
8182 if (!used) {
8183 // can safely delete this permission from list
8184 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 }
8186 }
8187 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008188 int newGids[] = globalGids;
8189 for (String eachPerm : sus.grantedPermissions) {
8190 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008191 if (bp != null) {
8192 newGids = appendInts(newGids, bp.gids);
8193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008194 }
8195 sus.gids = newGids;
8196 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 private int removePackageLP(String name) {
8199 PackageSetting p = mPackages.get(name);
8200 if (p != null) {
8201 mPackages.remove(name);
8202 if (p.sharedUser != null) {
8203 p.sharedUser.packages.remove(p);
8204 if (p.sharedUser.packages.size() == 0) {
8205 mSharedUsers.remove(p.sharedUser.name);
8206 removeUserIdLP(p.sharedUser.userId);
8207 return p.sharedUser.userId;
8208 }
8209 } else {
8210 removeUserIdLP(p.userId);
8211 return p.userId;
8212 }
8213 }
8214 return -1;
8215 }
8216
8217 private boolean addUserIdLP(int uid, Object obj, Object name) {
8218 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8219 return false;
8220 }
8221
8222 if (uid >= FIRST_APPLICATION_UID) {
8223 int N = mUserIds.size();
8224 final int index = uid - FIRST_APPLICATION_UID;
8225 while (index >= N) {
8226 mUserIds.add(null);
8227 N++;
8228 }
8229 if (mUserIds.get(index) != null) {
8230 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008231 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 + " name=" + name);
8233 return false;
8234 }
8235 mUserIds.set(index, obj);
8236 } else {
8237 if (mOtherUserIds.get(uid) != null) {
8238 reportSettingsProblem(Log.ERROR,
8239 "Adding duplicate shared id: " + uid
8240 + " name=" + name);
8241 return false;
8242 }
8243 mOtherUserIds.put(uid, obj);
8244 }
8245 return true;
8246 }
8247
8248 public Object getUserIdLP(int uid) {
8249 if (uid >= FIRST_APPLICATION_UID) {
8250 int N = mUserIds.size();
8251 final int index = uid - FIRST_APPLICATION_UID;
8252 return index < N ? mUserIds.get(index) : null;
8253 } else {
8254 return mOtherUserIds.get(uid);
8255 }
8256 }
8257
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008258 private Set<String> findPackagesWithFlag(int flag) {
8259 Set<String> ret = new HashSet<String>();
8260 for (PackageSetting ps : mPackages.values()) {
8261 // Has to match atleast all the flag bits set on flag
8262 if ((ps.pkgFlags & flag) == flag) {
8263 ret.add(ps.name);
8264 }
8265 }
8266 return ret;
8267 }
8268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 private void removeUserIdLP(int uid) {
8270 if (uid >= FIRST_APPLICATION_UID) {
8271 int N = mUserIds.size();
8272 final int index = uid - FIRST_APPLICATION_UID;
8273 if (index < N) mUserIds.set(index, null);
8274 } else {
8275 mOtherUserIds.remove(uid);
8276 }
8277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 void writeLP() {
8280 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8281
8282 // Keep the old settings around until we know the new ones have
8283 // been successfully written.
8284 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008285 // Presence of backup settings file indicates that we failed
8286 // to persist settings earlier. So preserve the older
8287 // backup for future reference since the current settings
8288 // might have been corrupted.
8289 if (!mBackupSettingsFilename.exists()) {
8290 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008291 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008292 return;
8293 }
8294 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008295 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008296 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 }
8299
8300 mPastSignatures.clear();
8301
8302 try {
8303 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8304
8305 //XmlSerializer serializer = XmlUtils.serializerInstance();
8306 XmlSerializer serializer = new FastXmlSerializer();
8307 serializer.setOutput(str, "utf-8");
8308 serializer.startDocument(null, true);
8309 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8310
8311 serializer.startTag(null, "packages");
8312
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008313 serializer.startTag(null, "last-platform-version");
8314 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8315 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8316 serializer.endTag(null, "last-platform-version");
8317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008318 serializer.startTag(null, "permission-trees");
8319 for (BasePermission bp : mPermissionTrees.values()) {
8320 writePermission(serializer, bp);
8321 }
8322 serializer.endTag(null, "permission-trees");
8323
8324 serializer.startTag(null, "permissions");
8325 for (BasePermission bp : mPermissions.values()) {
8326 writePermission(serializer, bp);
8327 }
8328 serializer.endTag(null, "permissions");
8329
8330 for (PackageSetting pkg : mPackages.values()) {
8331 writePackage(serializer, pkg);
8332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8335 writeDisabledSysPackage(serializer, pkg);
8336 }
8337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 serializer.startTag(null, "preferred-activities");
8339 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8340 serializer.startTag(null, "item");
8341 pa.writeToXml(serializer);
8342 serializer.endTag(null, "item");
8343 }
8344 serializer.endTag(null, "preferred-activities");
8345
8346 for (SharedUserSetting usr : mSharedUsers.values()) {
8347 serializer.startTag(null, "shared-user");
8348 serializer.attribute(null, "name", usr.name);
8349 serializer.attribute(null, "userId",
8350 Integer.toString(usr.userId));
8351 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8352 serializer.startTag(null, "perms");
8353 for (String name : usr.grantedPermissions) {
8354 serializer.startTag(null, "item");
8355 serializer.attribute(null, "name", name);
8356 serializer.endTag(null, "item");
8357 }
8358 serializer.endTag(null, "perms");
8359 serializer.endTag(null, "shared-user");
8360 }
8361
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008362 if (mPackagesToBeCleaned.size() > 0) {
8363 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8364 serializer.startTag(null, "cleaning-package");
8365 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8366 serializer.endTag(null, "cleaning-package");
8367 }
8368 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008369
8370 if (mRenamedPackages.size() > 0) {
8371 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8372 serializer.startTag(null, "renamed-package");
8373 serializer.attribute(null, "new", e.getKey());
8374 serializer.attribute(null, "old", e.getValue());
8375 serializer.endTag(null, "renamed-package");
8376 }
8377 }
8378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 serializer.endTag(null, "packages");
8380
8381 serializer.endDocument();
8382
8383 str.flush();
8384 str.close();
8385
8386 // New settings successfully written, old ones are no longer
8387 // needed.
8388 mBackupSettingsFilename.delete();
8389 FileUtils.setPermissions(mSettingsFilename.toString(),
8390 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8391 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8392 |FileUtils.S_IROTH,
8393 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008394
8395 // Write package list file now, use a JournaledFile.
8396 //
8397 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8398 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8399
8400 str = new FileOutputStream(journal.chooseForWrite());
8401 try {
8402 StringBuilder sb = new StringBuilder();
8403 for (PackageSetting pkg : mPackages.values()) {
8404 ApplicationInfo ai = pkg.pkg.applicationInfo;
8405 String dataPath = ai.dataDir;
8406 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8407
8408 // Avoid any application that has a space in its path
8409 // or that is handled by the system.
8410 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8411 continue;
8412
8413 // we store on each line the following information for now:
8414 //
8415 // pkgName - package name
8416 // userId - application-specific user id
8417 // debugFlag - 0 or 1 if the package is debuggable.
8418 // dataPath - path to package's data path
8419 //
8420 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8421 //
8422 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8423 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8424 // system/core/run-as/run-as.c
8425 //
8426 sb.setLength(0);
8427 sb.append(ai.packageName);
8428 sb.append(" ");
8429 sb.append((int)ai.uid);
8430 sb.append(isDebug ? " 1 " : " 0 ");
8431 sb.append(dataPath);
8432 sb.append("\n");
8433 str.write(sb.toString().getBytes());
8434 }
8435 str.flush();
8436 str.close();
8437 journal.commit();
8438 }
8439 catch (Exception e) {
8440 journal.rollback();
8441 }
8442
8443 FileUtils.setPermissions(mPackageListFilename.toString(),
8444 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8445 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8446 |FileUtils.S_IROTH,
8447 -1, -1);
8448
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008449 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450
8451 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008452 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 -08008453 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008454 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 -08008455 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008456 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008457 if (mSettingsFilename.exists()) {
8458 if (!mSettingsFilename.delete()) {
8459 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8460 }
8461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 //Debug.stopMethodTracing();
8463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008464
8465 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008466 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 serializer.startTag(null, "updated-package");
8468 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008469 if (pkg.realName != null) {
8470 serializer.attribute(null, "realName", pkg.realName);
8471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 serializer.attribute(null, "codePath", pkg.codePathString);
8473 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008474 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8476 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8477 }
8478 if (pkg.sharedUser == null) {
8479 serializer.attribute(null, "userId",
8480 Integer.toString(pkg.userId));
8481 } else {
8482 serializer.attribute(null, "sharedUserId",
8483 Integer.toString(pkg.userId));
8484 }
8485 serializer.startTag(null, "perms");
8486 if (pkg.sharedUser == null) {
8487 // If this is a shared user, the permissions will
8488 // be written there. We still need to write an
8489 // empty permissions list so permissionsFixed will
8490 // be set.
8491 for (final String name : pkg.grantedPermissions) {
8492 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008493 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 // We only need to write signature or system permissions but this wont
8495 // match the semantics of grantedPermissions. So write all permissions.
8496 serializer.startTag(null, "item");
8497 serializer.attribute(null, "name", name);
8498 serializer.endTag(null, "item");
8499 }
8500 }
8501 }
8502 serializer.endTag(null, "perms");
8503 serializer.endTag(null, "updated-package");
8504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008505
8506 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008507 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 serializer.startTag(null, "package");
8509 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008510 if (pkg.realName != null) {
8511 serializer.attribute(null, "realName", pkg.realName);
8512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 serializer.attribute(null, "codePath", pkg.codePathString);
8514 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8515 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8516 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008517 serializer.attribute(null, "flags",
8518 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008519 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008520 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 if (pkg.sharedUser == null) {
8522 serializer.attribute(null, "userId",
8523 Integer.toString(pkg.userId));
8524 } else {
8525 serializer.attribute(null, "sharedUserId",
8526 Integer.toString(pkg.userId));
8527 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008528 if (pkg.uidError) {
8529 serializer.attribute(null, "uidError", "true");
8530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8532 serializer.attribute(null, "enabled",
8533 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8534 ? "true" : "false");
8535 }
8536 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8537 serializer.attribute(null, "installStatus", "false");
8538 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008539 if (pkg.installerPackageName != null) {
8540 serializer.attribute(null, "installer", pkg.installerPackageName);
8541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8543 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8544 serializer.startTag(null, "perms");
8545 if (pkg.sharedUser == null) {
8546 // If this is a shared user, the permissions will
8547 // be written there. We still need to write an
8548 // empty permissions list so permissionsFixed will
8549 // be set.
8550 for (final String name : pkg.grantedPermissions) {
8551 serializer.startTag(null, "item");
8552 serializer.attribute(null, "name", name);
8553 serializer.endTag(null, "item");
8554 }
8555 }
8556 serializer.endTag(null, "perms");
8557 }
8558 if (pkg.disabledComponents.size() > 0) {
8559 serializer.startTag(null, "disabled-components");
8560 for (final String name : pkg.disabledComponents) {
8561 serializer.startTag(null, "item");
8562 serializer.attribute(null, "name", name);
8563 serializer.endTag(null, "item");
8564 }
8565 serializer.endTag(null, "disabled-components");
8566 }
8567 if (pkg.enabledComponents.size() > 0) {
8568 serializer.startTag(null, "enabled-components");
8569 for (final String name : pkg.enabledComponents) {
8570 serializer.startTag(null, "item");
8571 serializer.attribute(null, "name", name);
8572 serializer.endTag(null, "item");
8573 }
8574 serializer.endTag(null, "enabled-components");
8575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 serializer.endTag(null, "package");
8578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 void writePermission(XmlSerializer serializer, BasePermission bp)
8581 throws XmlPullParserException, java.io.IOException {
8582 if (bp.type != BasePermission.TYPE_BUILTIN
8583 && bp.sourcePackage != null) {
8584 serializer.startTag(null, "item");
8585 serializer.attribute(null, "name", bp.name);
8586 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008587 if (bp.protectionLevel !=
8588 PermissionInfo.PROTECTION_NORMAL) {
8589 serializer.attribute(null, "protection",
8590 Integer.toString(bp.protectionLevel));
8591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 if (DEBUG_SETTINGS) Log.v(TAG,
8593 "Writing perm: name=" + bp.name + " type=" + bp.type);
8594 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8595 PermissionInfo pi = bp.perm != null ? bp.perm.info
8596 : bp.pendingInfo;
8597 if (pi != null) {
8598 serializer.attribute(null, "type", "dynamic");
8599 if (pi.icon != 0) {
8600 serializer.attribute(null, "icon",
8601 Integer.toString(pi.icon));
8602 }
8603 if (pi.nonLocalizedLabel != null) {
8604 serializer.attribute(null, "label",
8605 pi.nonLocalizedLabel.toString());
8606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 }
8608 }
8609 serializer.endTag(null, "item");
8610 }
8611 }
8612
8613 String getReadMessagesLP() {
8614 return mReadMessages.toString();
8615 }
8616
Oscar Montemayora8529f62009-11-18 10:14:20 -08008617 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8619 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008620 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 while(its.hasNext()) {
8622 String key = its.next();
8623 PackageSetting ps = mPackages.get(key);
8624 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008625 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008626 }
8627 }
8628 return ret;
8629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 boolean readLP() {
8632 FileInputStream str = null;
8633 if (mBackupSettingsFilename.exists()) {
8634 try {
8635 str = new FileInputStream(mBackupSettingsFilename);
8636 mReadMessages.append("Reading from backup settings file\n");
8637 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008638 if (mSettingsFilename.exists()) {
8639 // If both the backup and settings file exist, we
8640 // ignore the settings since it might have been
8641 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008642 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008643 mSettingsFilename.delete();
8644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 } catch (java.io.IOException e) {
8646 // We'll try for the normal settings file.
8647 }
8648 }
8649
8650 mPastSignatures.clear();
8651
8652 try {
8653 if (str == null) {
8654 if (!mSettingsFilename.exists()) {
8655 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008656 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 return false;
8658 }
8659 str = new FileInputStream(mSettingsFilename);
8660 }
8661 XmlPullParser parser = Xml.newPullParser();
8662 parser.setInput(str, null);
8663
8664 int type;
8665 while ((type=parser.next()) != XmlPullParser.START_TAG
8666 && type != XmlPullParser.END_DOCUMENT) {
8667 ;
8668 }
8669
8670 if (type != XmlPullParser.START_TAG) {
8671 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008672 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 return false;
8674 }
8675
8676 int outerDepth = parser.getDepth();
8677 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8678 && (type != XmlPullParser.END_TAG
8679 || parser.getDepth() > outerDepth)) {
8680 if (type == XmlPullParser.END_TAG
8681 || type == XmlPullParser.TEXT) {
8682 continue;
8683 }
8684
8685 String tagName = parser.getName();
8686 if (tagName.equals("package")) {
8687 readPackageLP(parser);
8688 } else if (tagName.equals("permissions")) {
8689 readPermissionsLP(mPermissions, parser);
8690 } else if (tagName.equals("permission-trees")) {
8691 readPermissionsLP(mPermissionTrees, parser);
8692 } else if (tagName.equals("shared-user")) {
8693 readSharedUserLP(parser);
8694 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008695 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 } else if (tagName.equals("preferred-activities")) {
8697 readPreferredActivitiesLP(parser);
8698 } else if(tagName.equals("updated-package")) {
8699 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008700 } else if (tagName.equals("cleaning-package")) {
8701 String name = parser.getAttributeValue(null, "name");
8702 if (name != null) {
8703 mPackagesToBeCleaned.add(name);
8704 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008705 } else if (tagName.equals("renamed-package")) {
8706 String nname = parser.getAttributeValue(null, "new");
8707 String oname = parser.getAttributeValue(null, "old");
8708 if (nname != null && oname != null) {
8709 mRenamedPackages.put(nname, oname);
8710 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008711 } else if (tagName.equals("last-platform-version")) {
8712 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8713 try {
8714 String internal = parser.getAttributeValue(null, "internal");
8715 if (internal != null) {
8716 mInternalSdkPlatform = Integer.parseInt(internal);
8717 }
8718 String external = parser.getAttributeValue(null, "external");
8719 if (external != null) {
8720 mInternalSdkPlatform = Integer.parseInt(external);
8721 }
8722 } catch (NumberFormatException e) {
8723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008725 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 + parser.getName());
8727 XmlUtils.skipCurrentTag(parser);
8728 }
8729 }
8730
8731 str.close();
8732
8733 } catch(XmlPullParserException e) {
8734 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008735 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736
8737 } catch(java.io.IOException e) {
8738 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008739 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008740
8741 }
8742
8743 int N = mPendingPackages.size();
8744 for (int i=0; i<N; i++) {
8745 final PendingPackage pp = mPendingPackages.get(i);
8746 Object idObj = getUserIdLP(pp.sharedId);
8747 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008748 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008750 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008752 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 + pp.name);
8754 continue;
8755 }
8756 p.copyFrom(pp);
8757 } else if (idObj != null) {
8758 String msg = "Bad package setting: package " + pp.name
8759 + " has shared uid " + pp.sharedId
8760 + " that is not a shared uid\n";
8761 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008762 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008763 } else {
8764 String msg = "Bad package setting: package " + pp.name
8765 + " has shared uid " + pp.sharedId
8766 + " that is not defined\n";
8767 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008768 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 }
8770 }
8771 mPendingPackages.clear();
8772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 mReadMessages.append("Read completed successfully: "
8774 + mPackages.size() + " packages, "
8775 + mSharedUsers.size() + " shared uids\n");
8776
8777 return true;
8778 }
8779
8780 private int readInt(XmlPullParser parser, String ns, String name,
8781 int defValue) {
8782 String v = parser.getAttributeValue(ns, name);
8783 try {
8784 if (v == null) {
8785 return defValue;
8786 }
8787 return Integer.parseInt(v);
8788 } catch (NumberFormatException e) {
8789 reportSettingsProblem(Log.WARN,
8790 "Error in package manager settings: attribute " +
8791 name + " has bad integer value " + v + " at "
8792 + parser.getPositionDescription());
8793 }
8794 return defValue;
8795 }
8796
8797 private void readPermissionsLP(HashMap<String, BasePermission> out,
8798 XmlPullParser parser)
8799 throws IOException, XmlPullParserException {
8800 int outerDepth = parser.getDepth();
8801 int type;
8802 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8803 && (type != XmlPullParser.END_TAG
8804 || parser.getDepth() > outerDepth)) {
8805 if (type == XmlPullParser.END_TAG
8806 || type == XmlPullParser.TEXT) {
8807 continue;
8808 }
8809
8810 String tagName = parser.getName();
8811 if (tagName.equals("item")) {
8812 String name = parser.getAttributeValue(null, "name");
8813 String sourcePackage = parser.getAttributeValue(null, "package");
8814 String ptype = parser.getAttributeValue(null, "type");
8815 if (name != null && sourcePackage != null) {
8816 boolean dynamic = "dynamic".equals(ptype);
8817 BasePermission bp = new BasePermission(name, sourcePackage,
8818 dynamic
8819 ? BasePermission.TYPE_DYNAMIC
8820 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008821 bp.protectionLevel = readInt(parser, null, "protection",
8822 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008823 if (dynamic) {
8824 PermissionInfo pi = new PermissionInfo();
8825 pi.packageName = sourcePackage.intern();
8826 pi.name = name.intern();
8827 pi.icon = readInt(parser, null, "icon", 0);
8828 pi.nonLocalizedLabel = parser.getAttributeValue(
8829 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008830 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008831 bp.pendingInfo = pi;
8832 }
8833 out.put(bp.name, bp);
8834 } else {
8835 reportSettingsProblem(Log.WARN,
8836 "Error in package manager settings: permissions has"
8837 + " no name at " + parser.getPositionDescription());
8838 }
8839 } else {
8840 reportSettingsProblem(Log.WARN,
8841 "Unknown element reading permissions: "
8842 + parser.getName() + " at "
8843 + parser.getPositionDescription());
8844 }
8845 XmlUtils.skipCurrentTag(parser);
8846 }
8847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008850 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008852 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 String codePathStr = parser.getAttributeValue(null, "codePath");
8854 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008855 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 resourcePathStr = codePathStr;
8857 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008858 String version = parser.getAttributeValue(null, "version");
8859 int versionCode = 0;
8860 if (version != null) {
8861 try {
8862 versionCode = Integer.parseInt(version);
8863 } catch (NumberFormatException e) {
8864 }
8865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 int pkgFlags = 0;
8868 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008869 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008870 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008871 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 String timeStampStr = parser.getAttributeValue(null, "ts");
8873 if (timeStampStr != null) {
8874 try {
8875 long timeStamp = Long.parseLong(timeStampStr);
8876 ps.setTimeStamp(timeStamp, timeStampStr);
8877 } catch (NumberFormatException e) {
8878 }
8879 }
8880 String idStr = parser.getAttributeValue(null, "userId");
8881 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8882 if(ps.userId <= 0) {
8883 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8884 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8885 }
8886 int outerDepth = parser.getDepth();
8887 int type;
8888 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8889 && (type != XmlPullParser.END_TAG
8890 || parser.getDepth() > outerDepth)) {
8891 if (type == XmlPullParser.END_TAG
8892 || type == XmlPullParser.TEXT) {
8893 continue;
8894 }
8895
8896 String tagName = parser.getName();
8897 if (tagName.equals("perms")) {
8898 readGrantedPermissionsLP(parser,
8899 ps.grantedPermissions);
8900 } else {
8901 reportSettingsProblem(Log.WARN,
8902 "Unknown element under <updated-package>: "
8903 + parser.getName());
8904 XmlUtils.skipCurrentTag(parser);
8905 }
8906 }
8907 mDisabledSysPackages.put(name, ps);
8908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 private void readPackageLP(XmlPullParser parser)
8911 throws XmlPullParserException, IOException {
8912 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008913 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 String idStr = null;
8915 String sharedIdStr = null;
8916 String codePathStr = null;
8917 String resourcePathStr = null;
8918 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008919 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008920 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 int pkgFlags = 0;
8922 String timeStampStr;
8923 long timeStamp = 0;
8924 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008925 String version = null;
8926 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 try {
8928 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008929 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008930 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008931 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8933 codePathStr = parser.getAttributeValue(null, "codePath");
8934 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008935 version = parser.getAttributeValue(null, "version");
8936 if (version != null) {
8937 try {
8938 versionCode = Integer.parseInt(version);
8939 } catch (NumberFormatException e) {
8940 }
8941 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008942 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008943
8944 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008946 try {
8947 pkgFlags = Integer.parseInt(systemStr);
8948 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 }
8950 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008951 // For backward compatibility
8952 systemStr = parser.getAttributeValue(null, "system");
8953 if (systemStr != null) {
8954 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8955 } else {
8956 // Old settings that don't specify system... just treat
8957 // them as system, good enough.
8958 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 }
8961 timeStampStr = parser.getAttributeValue(null, "ts");
8962 if (timeStampStr != null) {
8963 try {
8964 timeStamp = Long.parseLong(timeStampStr);
8965 } catch (NumberFormatException e) {
8966 }
8967 }
8968 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8969 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8970 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8971 if (resourcePathStr == null) {
8972 resourcePathStr = codePathStr;
8973 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008974 if (realName != null) {
8975 realName = realName.intern();
8976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 if (name == null) {
8978 reportSettingsProblem(Log.WARN,
8979 "Error in package manager settings: <package> has no name at "
8980 + parser.getPositionDescription());
8981 } else if (codePathStr == null) {
8982 reportSettingsProblem(Log.WARN,
8983 "Error in package manager settings: <package> has no codePath at "
8984 + parser.getPositionDescription());
8985 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008986 packageSetting = addPackageLP(name.intern(), realName,
8987 new File(codePathStr), new File(resourcePathStr),
8988 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8990 + ": userId=" + userId + " pkg=" + packageSetting);
8991 if (packageSetting == null) {
8992 reportSettingsProblem(Log.ERROR,
8993 "Failure adding uid " + userId
8994 + " while parsing settings at "
8995 + parser.getPositionDescription());
8996 } else {
8997 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8998 }
8999 } else if (sharedIdStr != null) {
9000 userId = sharedIdStr != null
9001 ? Integer.parseInt(sharedIdStr) : 0;
9002 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009003 packageSetting = new PendingPackage(name.intern(), realName,
9004 new File(codePathStr), new File(resourcePathStr),
9005 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009006 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9007 mPendingPackages.add((PendingPackage) packageSetting);
9008 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9009 + ": sharedUserId=" + userId + " pkg="
9010 + packageSetting);
9011 } else {
9012 reportSettingsProblem(Log.WARN,
9013 "Error in package manager settings: package "
9014 + name + " has bad sharedId " + sharedIdStr
9015 + " at " + parser.getPositionDescription());
9016 }
9017 } else {
9018 reportSettingsProblem(Log.WARN,
9019 "Error in package manager settings: package "
9020 + name + " has bad userId " + idStr + " at "
9021 + parser.getPositionDescription());
9022 }
9023 } catch (NumberFormatException e) {
9024 reportSettingsProblem(Log.WARN,
9025 "Error in package manager settings: package "
9026 + name + " has bad userId " + idStr + " at "
9027 + parser.getPositionDescription());
9028 }
9029 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009030 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009031 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 final String enabledStr = parser.getAttributeValue(null, "enabled");
9033 if (enabledStr != null) {
9034 if (enabledStr.equalsIgnoreCase("true")) {
9035 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9036 } else if (enabledStr.equalsIgnoreCase("false")) {
9037 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9038 } else if (enabledStr.equalsIgnoreCase("default")) {
9039 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9040 } else {
9041 reportSettingsProblem(Log.WARN,
9042 "Error in package manager settings: package "
9043 + name + " has bad enabled value: " + idStr
9044 + " at " + parser.getPositionDescription());
9045 }
9046 } else {
9047 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9048 }
9049 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9050 if (installStatusStr != null) {
9051 if (installStatusStr.equalsIgnoreCase("false")) {
9052 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9053 } else {
9054 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9055 }
9056 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009058 int outerDepth = parser.getDepth();
9059 int type;
9060 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9061 && (type != XmlPullParser.END_TAG
9062 || parser.getDepth() > outerDepth)) {
9063 if (type == XmlPullParser.END_TAG
9064 || type == XmlPullParser.TEXT) {
9065 continue;
9066 }
9067
9068 String tagName = parser.getName();
9069 if (tagName.equals("disabled-components")) {
9070 readDisabledComponentsLP(packageSetting, parser);
9071 } else if (tagName.equals("enabled-components")) {
9072 readEnabledComponentsLP(packageSetting, parser);
9073 } else if (tagName.equals("sigs")) {
9074 packageSetting.signatures.readXml(parser, mPastSignatures);
9075 } else if (tagName.equals("perms")) {
9076 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009077 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 packageSetting.permissionsFixed = true;
9079 } else {
9080 reportSettingsProblem(Log.WARN,
9081 "Unknown element under <package>: "
9082 + parser.getName());
9083 XmlUtils.skipCurrentTag(parser);
9084 }
9085 }
9086 } else {
9087 XmlUtils.skipCurrentTag(parser);
9088 }
9089 }
9090
9091 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9092 XmlPullParser parser)
9093 throws IOException, XmlPullParserException {
9094 int outerDepth = parser.getDepth();
9095 int type;
9096 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9097 && (type != XmlPullParser.END_TAG
9098 || parser.getDepth() > outerDepth)) {
9099 if (type == XmlPullParser.END_TAG
9100 || type == XmlPullParser.TEXT) {
9101 continue;
9102 }
9103
9104 String tagName = parser.getName();
9105 if (tagName.equals("item")) {
9106 String name = parser.getAttributeValue(null, "name");
9107 if (name != null) {
9108 packageSetting.disabledComponents.add(name.intern());
9109 } else {
9110 reportSettingsProblem(Log.WARN,
9111 "Error in package manager settings: <disabled-components> has"
9112 + " no name at " + parser.getPositionDescription());
9113 }
9114 } else {
9115 reportSettingsProblem(Log.WARN,
9116 "Unknown element under <disabled-components>: "
9117 + parser.getName());
9118 }
9119 XmlUtils.skipCurrentTag(parser);
9120 }
9121 }
9122
9123 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9124 XmlPullParser parser)
9125 throws IOException, XmlPullParserException {
9126 int outerDepth = parser.getDepth();
9127 int type;
9128 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9129 && (type != XmlPullParser.END_TAG
9130 || parser.getDepth() > outerDepth)) {
9131 if (type == XmlPullParser.END_TAG
9132 || type == XmlPullParser.TEXT) {
9133 continue;
9134 }
9135
9136 String tagName = parser.getName();
9137 if (tagName.equals("item")) {
9138 String name = parser.getAttributeValue(null, "name");
9139 if (name != null) {
9140 packageSetting.enabledComponents.add(name.intern());
9141 } else {
9142 reportSettingsProblem(Log.WARN,
9143 "Error in package manager settings: <enabled-components> has"
9144 + " no name at " + parser.getPositionDescription());
9145 }
9146 } else {
9147 reportSettingsProblem(Log.WARN,
9148 "Unknown element under <enabled-components>: "
9149 + parser.getName());
9150 }
9151 XmlUtils.skipCurrentTag(parser);
9152 }
9153 }
9154
9155 private void readSharedUserLP(XmlPullParser parser)
9156 throws XmlPullParserException, IOException {
9157 String name = null;
9158 String idStr = null;
9159 int pkgFlags = 0;
9160 SharedUserSetting su = null;
9161 try {
9162 name = parser.getAttributeValue(null, "name");
9163 idStr = parser.getAttributeValue(null, "userId");
9164 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9165 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9166 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9167 }
9168 if (name == null) {
9169 reportSettingsProblem(Log.WARN,
9170 "Error in package manager settings: <shared-user> has no name at "
9171 + parser.getPositionDescription());
9172 } else if (userId == 0) {
9173 reportSettingsProblem(Log.WARN,
9174 "Error in package manager settings: shared-user "
9175 + name + " has bad userId " + idStr + " at "
9176 + parser.getPositionDescription());
9177 } else {
9178 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9179 reportSettingsProblem(Log.ERROR,
9180 "Occurred while parsing settings at "
9181 + parser.getPositionDescription());
9182 }
9183 }
9184 } catch (NumberFormatException e) {
9185 reportSettingsProblem(Log.WARN,
9186 "Error in package manager settings: package "
9187 + name + " has bad userId " + idStr + " at "
9188 + parser.getPositionDescription());
9189 };
9190
9191 if (su != null) {
9192 int outerDepth = parser.getDepth();
9193 int type;
9194 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9195 && (type != XmlPullParser.END_TAG
9196 || parser.getDepth() > outerDepth)) {
9197 if (type == XmlPullParser.END_TAG
9198 || type == XmlPullParser.TEXT) {
9199 continue;
9200 }
9201
9202 String tagName = parser.getName();
9203 if (tagName.equals("sigs")) {
9204 su.signatures.readXml(parser, mPastSignatures);
9205 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009206 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 } else {
9208 reportSettingsProblem(Log.WARN,
9209 "Unknown element under <shared-user>: "
9210 + parser.getName());
9211 XmlUtils.skipCurrentTag(parser);
9212 }
9213 }
9214
9215 } else {
9216 XmlUtils.skipCurrentTag(parser);
9217 }
9218 }
9219
9220 private void readGrantedPermissionsLP(XmlPullParser parser,
9221 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9222 int outerDepth = parser.getDepth();
9223 int type;
9224 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9225 && (type != XmlPullParser.END_TAG
9226 || parser.getDepth() > outerDepth)) {
9227 if (type == XmlPullParser.END_TAG
9228 || type == XmlPullParser.TEXT) {
9229 continue;
9230 }
9231
9232 String tagName = parser.getName();
9233 if (tagName.equals("item")) {
9234 String name = parser.getAttributeValue(null, "name");
9235 if (name != null) {
9236 outPerms.add(name.intern());
9237 } else {
9238 reportSettingsProblem(Log.WARN,
9239 "Error in package manager settings: <perms> has"
9240 + " no name at " + parser.getPositionDescription());
9241 }
9242 } else {
9243 reportSettingsProblem(Log.WARN,
9244 "Unknown element under <perms>: "
9245 + parser.getName());
9246 }
9247 XmlUtils.skipCurrentTag(parser);
9248 }
9249 }
9250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009251 private void readPreferredActivitiesLP(XmlPullParser parser)
9252 throws XmlPullParserException, IOException {
9253 int outerDepth = parser.getDepth();
9254 int type;
9255 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9256 && (type != XmlPullParser.END_TAG
9257 || parser.getDepth() > outerDepth)) {
9258 if (type == XmlPullParser.END_TAG
9259 || type == XmlPullParser.TEXT) {
9260 continue;
9261 }
9262
9263 String tagName = parser.getName();
9264 if (tagName.equals("item")) {
9265 PreferredActivity pa = new PreferredActivity(parser);
9266 if (pa.mParseError == null) {
9267 mPreferredActivities.addFilter(pa);
9268 } else {
9269 reportSettingsProblem(Log.WARN,
9270 "Error in package manager settings: <preferred-activity> "
9271 + pa.mParseError + " at "
9272 + parser.getPositionDescription());
9273 }
9274 } else {
9275 reportSettingsProblem(Log.WARN,
9276 "Unknown element under <preferred-activities>: "
9277 + parser.getName());
9278 XmlUtils.skipCurrentTag(parser);
9279 }
9280 }
9281 }
9282
9283 // Returns -1 if we could not find an available UserId to assign
9284 private int newUserIdLP(Object obj) {
9285 // Let's be stupidly inefficient for now...
9286 final int N = mUserIds.size();
9287 for (int i=0; i<N; i++) {
9288 if (mUserIds.get(i) == null) {
9289 mUserIds.set(i, obj);
9290 return FIRST_APPLICATION_UID + i;
9291 }
9292 }
9293
9294 // None left?
9295 if (N >= MAX_APPLICATION_UIDS) {
9296 return -1;
9297 }
9298
9299 mUserIds.add(obj);
9300 return FIRST_APPLICATION_UID + N;
9301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 public PackageSetting getDisabledSystemPkg(String name) {
9304 synchronized(mPackages) {
9305 PackageSetting ps = mDisabledSysPackages.get(name);
9306 return ps;
9307 }
9308 }
9309
9310 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9311 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9312 if (Config.LOGV) {
9313 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9314 + " componentName = " + componentInfo.name);
9315 Log.v(TAG, "enabledComponents: "
9316 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9317 Log.v(TAG, "disabledComponents: "
9318 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9319 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009320 if (packageSettings == null) {
9321 if (false) {
9322 Log.w(TAG, "WAITING FOR DEBUGGER");
9323 Debug.waitForDebugger();
9324 Log.i(TAG, "We will crash!");
9325 }
9326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9328 || ((componentInfo.enabled
9329 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9330 || (componentInfo.applicationInfo.enabled
9331 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9332 && !packageSettings.disabledComponents.contains(componentInfo.name))
9333 || packageSettings.enabledComponents.contains(componentInfo.name));
9334 }
9335 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009336
9337 // ------- apps on sdcard specific code -------
9338 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009339 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009340 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009341 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009342 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009343
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009344 private String getEncryptKey() {
9345 try {
9346 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9347 if (sdEncKey == null) {
9348 sdEncKey = SystemKeyStore.getInstance().
9349 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9350 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009351 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009352 return null;
9353 }
9354 }
9355 return sdEncKey;
9356 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009357 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009358 return null;
9359 }
9360 }
9361
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009362 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009363 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009364 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009365 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009366 if (list != null) {
9367 int idx = 0;
9368 int idList[] = new int[MAX_CONTAINERS];
9369 boolean neverFound = true;
9370 for (String name : list) {
9371 // Ignore null entries
9372 if (name == null) {
9373 continue;
9374 }
9375 int sidx = name.indexOf(prefix);
9376 if (sidx == -1) {
9377 // Not a temp file. just ignore
9378 continue;
9379 }
9380 String subStr = name.substring(sidx + prefix.length());
9381 idList[idx] = -1;
9382 if (subStr != null) {
9383 try {
9384 int cid = Integer.parseInt(subStr);
9385 idList[idx++] = cid;
9386 neverFound = false;
9387 } catch (NumberFormatException e) {
9388 }
9389 }
9390 }
9391 if (!neverFound) {
9392 // Sort idList
9393 Arrays.sort(idList);
9394 for (int j = 1; j <= idList.length; j++) {
9395 if (idList[j-1] != j) {
9396 tmpIdx = j;
9397 break;
9398 }
9399 }
9400 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009401 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009402 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009403 }
9404
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009405 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009406 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009407 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009408 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9409 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9410 throw new SecurityException("Media status can only be updated by the system");
9411 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009412 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009413 Log.i(TAG, "Updating external media status from " +
9414 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9415 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009416 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9417 mediaStatus+", mMediaMounted=" + mMediaMounted);
9418 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009419 if (reportStatus) {
9420 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9421 }
9422 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009423 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009424 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009425 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009426 // Queue up an async operation since the package installation may take a little while.
9427 mHandler.post(new Runnable() {
9428 public void run() {
9429 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009430 try {
9431 updateExternalMediaStatusInner(mediaStatus);
9432 } finally {
9433 if (reportStatus) {
9434 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9435 }
9436 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009437 }
9438 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009439 }
9440
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009441 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009442 // If we are up here that means there are packages to be
9443 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009444 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009445 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009446 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009447 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009448 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009449
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009450 int uidList[] = new int[list.length];
9451 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009452 HashSet<String> removeCids = new HashSet<String>();
9453 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009454 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009455 for (String cid : list) {
9456 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009457 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9458 boolean failed = true;
9459 try {
9460 String pkgName = args.getPackageName();
9461 if (pkgName == null) {
9462 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009463 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009464 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9465 PackageSetting ps = mSettings.mPackages.get(pkgName);
9466 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009467 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009468 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9469 " corresponds to pkg : " + pkgName +
9470 " at code path: " + ps.codePathString);
9471 // We do have a valid package installed on sdcard
9472 processCids.put(args, ps.codePathString);
9473 failed = false;
9474 int uid = ps.userId;
9475 if (uid != -1) {
9476 uidList[num++] = uid;
9477 }
9478 }
9479 } finally {
9480 if (failed) {
9481 // Stale container on sdcard. Just delete
9482 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9483 removeCids.add(cid);
9484 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009485 }
9486 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009487 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009488 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009489 int uidArr[] = null;
9490 if (num > 0) {
9491 // Sort uid list
9492 Arrays.sort(uidList, 0, num);
9493 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009494 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009495 uidArr[0] = uidList[0];
9496 int di = 0;
9497 for (int i = 1; i < num; i++) {
9498 if (uidList[i-1] != uidList[i]) {
9499 uidArr[di++] = uidList[i];
9500 }
9501 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009502 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009503 // Process packages with valid entries.
9504 if (mediaStatus) {
9505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009506 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 startCleaningPackages();
9508 } else {
9509 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009510 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009511 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009512 }
9513
9514 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9515 ArrayList<String> pkgList, int uidArr[]) {
9516 int size = pkgList.size();
9517 if (size > 0) {
9518 // Send broadcasts here
9519 Bundle extras = new Bundle();
9520 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9521 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009522 if (uidArr != null) {
9523 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9524 }
9525 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9526 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009527 sendPackageBroadcast(action, null, extras);
9528 }
9529 }
9530
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009531 /*
9532 * Look at potentially valid container ids from processCids
9533 * If package information doesn't match the one on record
9534 * or package scanning fails, the cid is added to list of
9535 * removeCids and cleaned up. Since cleaning up containers
9536 * involves destroying them, we do not want any parse
9537 * references to such stale containers. So force gc's
9538 * to avoid unnecessary crashes.
9539 */
9540 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009541 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009542 ArrayList<String> pkgList = new ArrayList<String>();
9543 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009544 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009546 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9548 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009549 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009550 try {
9551 // Make sure there are no container errors first.
9552 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9553 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009554 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009555 " when installing from sdcard");
9556 continue;
9557 }
9558 // Check code path here.
9559 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009560 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 " does not match one in settings " + codePath);
9562 continue;
9563 }
9564 // Parse package
9565 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009566 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009568 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009569 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9570 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009571 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009572 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009573 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 retCode = PackageManager.INSTALL_SUCCEEDED;
9575 pkgList.add(pkg.packageName);
9576 // Post process args
9577 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9578 }
9579 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009580 Slog.i(TAG, "Failed to install pkg from " +
9581 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009582 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 }
9584
9585 } finally {
9586 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9587 // Don't destroy container here. Wait till gc clears things up.
9588 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009589 }
9590 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009591 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009592 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009593 // If the platform SDK has changed since the last time we booted,
9594 // we need to re-grant app permission to catch any new ones that
9595 // appear. This is really a hack, and means that apps can in some
9596 // cases get permissions that the user didn't initially explicitly
9597 // allow... it would be nice to have some better way to handle
9598 // this situation.
9599 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9600 != mSdkVersion;
9601 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9602 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9603 + "; regranting permissions for external storage");
9604 mSettings.mExternalSdkPlatform = mSdkVersion;
9605
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009606 // Make sure group IDs have been assigned, and any permission
9607 // changes in other apps are accounted for
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009608 updatePermissionsLP(null, null, true, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009609 // Persist settings
9610 mSettings.writeLP();
9611 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009612 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009613 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009614 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9615 }
9616 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009617 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009618 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009619 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009620 if (removeCids != null) {
9621 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009622 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009623 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009624 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009625 }
9626
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009627 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009628 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009629 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009630 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009631 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009632 Set<SdInstallArgs> keys = processCids.keySet();
9633 for (SdInstallArgs args : keys) {
9634 String cid = args.cid;
9635 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009637 // Delete package internally
9638 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9639 synchronized (mInstallLock) {
9640 boolean res = deletePackageLI(pkgName, false,
9641 PackageManager.DONT_DELETE_DATA, outInfo);
9642 if (res) {
9643 pkgList.add(pkgName);
9644 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009645 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009646 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009647 }
9648 }
9649 }
9650 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009651 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009653 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 // Force gc
9655 Runtime.getRuntime().gc();
9656 // Just unmount all valid containers.
9657 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009658 synchronized (mInstallLock) {
9659 args.doPostDeleteLI(false);
9660 }
9661 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009662 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009663
9664 public void movePackage(final String packageName,
9665 final IPackageMoveObserver observer, final int flags) {
9666 if (packageName == null) {
9667 return;
9668 }
9669 mContext.enforceCallingOrSelfPermission(
9670 android.Manifest.permission.MOVE_PACKAGE, null);
9671 int returnCode = PackageManager.MOVE_SUCCEEDED;
9672 int currFlags = 0;
9673 int newFlags = 0;
9674 synchronized (mPackages) {
9675 PackageParser.Package pkg = mPackages.get(packageName);
9676 if (pkg == null) {
9677 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9678 }
9679 // Disable moving fwd locked apps and system packages
9680 if (pkg.applicationInfo != null &&
9681 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009682 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009683 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9684 } else if (pkg.applicationInfo != null &&
9685 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009686 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009687 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9688 } else {
9689 // Find install location first
9690 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9691 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009692 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009693 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9694 } else {
9695 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9696 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009697 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009698 PackageManager.INSTALL_EXTERNAL : 0;
9699 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009700 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009701 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9702 }
9703 }
9704 }
9705 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9706 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9707 } else {
9708 Message msg = mHandler.obtainMessage(INIT_COPY);
9709 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9710 pkg.applicationInfo.publicSourceDir);
9711 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9712 packageName);
9713 msg.obj = mp;
9714 mHandler.sendMessage(msg);
9715 }
9716 }
9717 }
9718
9719 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9720 // Queue up an async operation since the package deletion may take a little while.
9721 mHandler.post(new Runnable() {
9722 public void run() {
9723 mHandler.removeCallbacks(this);
9724 int returnCode = currentStatus;
9725 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9726 if (moveSucceeded) {
9727 int uid = -1;
9728 synchronized (mPackages) {
9729 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9730 }
9731 ArrayList<String> pkgList = new ArrayList<String>();
9732 pkgList.add(mp.packageName);
9733 int uidArr[] = new int[] { uid };
9734 // Send resources unavailable broadcast
9735 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9736
9737 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009738 synchronized (mInstallLock) {
9739 synchronized (mPackages) {
9740 PackageParser.Package pkg = mPackages.get(mp.packageName);
9741 if (pkg != null) {
9742 String oldCodePath = pkg.mPath;
9743 String newCodePath = mp.targetArgs.getCodePath();
9744 String newResPath = mp.targetArgs.getResourcePath();
9745 pkg.mPath = newCodePath;
9746 // Move dex files around
9747 if (moveDexFilesLI(pkg)
9748 != PackageManager.INSTALL_SUCCEEDED) {
9749 // Moving of dex files failed. Set
9750 // error code and abort move.
9751 pkg.mPath = pkg.mScanPath;
9752 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9753 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009754 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009755 pkg.mScanPath = newCodePath;
9756 pkg.applicationInfo.sourceDir = newCodePath;
9757 pkg.applicationInfo.publicSourceDir = newResPath;
9758 PackageSetting ps = (PackageSetting) pkg.mExtras;
9759 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9760 ps.codePathString = ps.codePath.getPath();
9761 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9762 ps.resourcePathString = ps.resourcePath.getPath();
9763 // Set the application info flag correctly.
9764 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9765 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9766 } else {
9767 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9768 }
9769 ps.setFlags(pkg.applicationInfo.flags);
9770 mAppDirs.remove(oldCodePath);
9771 mAppDirs.put(newCodePath, pkg);
9772 // Persist settings
9773 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009774 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009775 }
9776 }
9777 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009778 // Send resources available broadcast
9779 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009780 }
9781 if (!moveSucceeded){
9782 // Clean up failed installation
9783 if (mp.targetArgs != null) {
9784 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009785 returnCode);
9786 }
9787 } else {
9788 // Force a gc to clear things up.
9789 Runtime.getRuntime().gc();
9790 // Delete older code
9791 synchronized (mInstallLock) {
9792 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009793 }
9794 }
9795 IPackageMoveObserver observer = mp.observer;
9796 if (observer != null) {
9797 try {
9798 observer.packageMoved(mp.packageName, returnCode);
9799 } catch (RemoteException e) {
9800 Log.i(TAG, "Observer no longer exists.");
9801 }
9802 }
9803 }
9804 });
9805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806}