blob: b95bae4d99d3b3ae9daacccef24aac19a084ed26 [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 Hackbornd4310ac2010-03-16 22:55:08 -0700957 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958
959 mSettings.writeLP();
960
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 // Now after opening every single application zip, make sure they
965 // are all flushed. Not really needed, but keeps things nice and
966 // tidy.
967 Runtime.getRuntime().gc();
968 } // synchronized (mPackages)
969 } // synchronized (mInstallLock)
970 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 @Override
973 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
974 throws RemoteException {
975 try {
976 return super.onTransact(code, data, reply, flags);
977 } catch (RuntimeException e) {
978 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800979 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981 throw e;
982 }
983 }
984
Dianne Hackborne6620b22010-01-22 14:46:21 -0800985 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800986 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700988 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800990 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800991 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993 } else {
994 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800995 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 File dataDir = new File(pkg.applicationInfo.dataDir);
997 dataDir.delete();
998 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800999 if (ps.codePath != null) {
1000 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001001 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001002 }
1003 }
1004 if (ps.resourcePath != null) {
1005 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001006 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001007 }
1008 }
1009 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 }
1011
1012 void readPermissions() {
1013 // Read permissions from .../etc/permission directory.
1014 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1015 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001016 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 return;
1018 }
1019 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001020 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 return;
1022 }
1023
1024 // Iterate over the files in the directory and scan .xml files
1025 for (File f : libraryDir.listFiles()) {
1026 // We'll read platform.xml last
1027 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1028 continue;
1029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001032 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 continue;
1034 }
1035 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 continue;
1038 }
1039
1040 readPermissionsFromXml(f);
1041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1044 final File permFile = new File(Environment.getRootDirectory(),
1045 "etc/permissions/platform.xml");
1046 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001047
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001048 StringBuilder sb = new StringBuilder(128);
1049 sb.append("Libs:");
1050 Iterator<String> it = mSharedLibraries.keySet().iterator();
1051 while (it.hasNext()) {
1052 sb.append(' ');
1053 String name = it.next();
1054 sb.append(name);
1055 sb.append(':');
1056 sb.append(mSharedLibraries.get(name));
1057 }
1058 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001059
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001060 sb.setLength(0);
1061 sb.append("Features:");
1062 it = mAvailableFeatures.keySet().iterator();
1063 while (it.hasNext()) {
1064 sb.append(' ');
1065 sb.append(it.next());
1066 }
1067 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001069
1070 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 FileReader permReader = null;
1072 try {
1073 permReader = new FileReader(permFile);
1074 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001075 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return;
1077 }
1078
1079 try {
1080 XmlPullParser parser = Xml.newPullParser();
1081 parser.setInput(permReader);
1082
1083 XmlUtils.beginDocument(parser, "permissions");
1084
1085 while (true) {
1086 XmlUtils.nextElement(parser);
1087 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1088 break;
1089 }
1090
1091 String name = parser.getName();
1092 if ("group".equals(name)) {
1093 String gidStr = parser.getAttributeValue(null, "gid");
1094 if (gidStr != null) {
1095 int gid = Integer.parseInt(gidStr);
1096 mGlobalGids = appendInt(mGlobalGids, gid);
1097 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 + parser.getPositionDescription());
1100 }
1101
1102 XmlUtils.skipCurrentTag(parser);
1103 continue;
1104 } else if ("permission".equals(name)) {
1105 String perm = parser.getAttributeValue(null, "name");
1106 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001107 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 + parser.getPositionDescription());
1109 XmlUtils.skipCurrentTag(parser);
1110 continue;
1111 }
1112 perm = perm.intern();
1113 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 } else if ("assign-permission".equals(name)) {
1116 String perm = parser.getAttributeValue(null, "name");
1117 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001118 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 + parser.getPositionDescription());
1120 XmlUtils.skipCurrentTag(parser);
1121 continue;
1122 }
1123 String uidStr = parser.getAttributeValue(null, "uid");
1124 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001125 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 + parser.getPositionDescription());
1127 XmlUtils.skipCurrentTag(parser);
1128 continue;
1129 }
1130 int uid = Process.getUidForName(uidStr);
1131 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001132 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 + uidStr + "\" at "
1134 + parser.getPositionDescription());
1135 XmlUtils.skipCurrentTag(parser);
1136 continue;
1137 }
1138 perm = perm.intern();
1139 HashSet<String> perms = mSystemPermissions.get(uid);
1140 if (perms == null) {
1141 perms = new HashSet<String>();
1142 mSystemPermissions.put(uid, perms);
1143 }
1144 perms.add(perm);
1145 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 } else if ("library".equals(name)) {
1148 String lname = parser.getAttributeValue(null, "name");
1149 String lfile = parser.getAttributeValue(null, "file");
1150 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001151 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 + parser.getPositionDescription());
1153 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001154 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 + parser.getPositionDescription());
1156 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001157 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001158 mSharedLibraries.put(lname, lfile);
1159 }
1160 XmlUtils.skipCurrentTag(parser);
1161 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001162
Dianne Hackborn49237342009-08-27 20:08:01 -07001163 } else if ("feature".equals(name)) {
1164 String fname = parser.getAttributeValue(null, "name");
1165 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001166 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001167 + parser.getPositionDescription());
1168 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001169 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001170 FeatureInfo fi = new FeatureInfo();
1171 fi.name = fname;
1172 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
1174 XmlUtils.skipCurrentTag(parser);
1175 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 } else {
1178 XmlUtils.skipCurrentTag(parser);
1179 continue;
1180 }
1181
1182 }
1183 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001184 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001186 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188 }
1189
1190 void readPermission(XmlPullParser parser, String name)
1191 throws IOException, XmlPullParserException {
1192
1193 name = name.intern();
1194
1195 BasePermission bp = mSettings.mPermissions.get(name);
1196 if (bp == null) {
1197 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1198 mSettings.mPermissions.put(name, bp);
1199 }
1200 int outerDepth = parser.getDepth();
1201 int type;
1202 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1203 && (type != XmlPullParser.END_TAG
1204 || parser.getDepth() > outerDepth)) {
1205 if (type == XmlPullParser.END_TAG
1206 || type == XmlPullParser.TEXT) {
1207 continue;
1208 }
1209
1210 String tagName = parser.getName();
1211 if ("group".equals(tagName)) {
1212 String gidStr = parser.getAttributeValue(null, "gid");
1213 if (gidStr != null) {
1214 int gid = Process.getGidForName(gidStr);
1215 bp.gids = appendInt(bp.gids, gid);
1216 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001217 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 + parser.getPositionDescription());
1219 }
1220 }
1221 XmlUtils.skipCurrentTag(parser);
1222 }
1223 }
1224
1225 static int[] appendInt(int[] cur, int val) {
1226 if (cur == null) {
1227 return new int[] { val };
1228 }
1229 final int N = cur.length;
1230 for (int i=0; i<N; i++) {
1231 if (cur[i] == val) {
1232 return cur;
1233 }
1234 }
1235 int[] ret = new int[N+1];
1236 System.arraycopy(cur, 0, ret, 0, N);
1237 ret[N] = val;
1238 return ret;
1239 }
1240
1241 static int[] appendInts(int[] cur, int[] add) {
1242 if (add == null) return cur;
1243 if (cur == null) return add;
1244 final int N = add.length;
1245 for (int i=0; i<N; i++) {
1246 cur = appendInt(cur, add[i]);
1247 }
1248 return cur;
1249 }
1250
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001251 static int[] removeInt(int[] cur, int val) {
1252 if (cur == null) {
1253 return null;
1254 }
1255 final int N = cur.length;
1256 for (int i=0; i<N; i++) {
1257 if (cur[i] == val) {
1258 int[] ret = new int[N-1];
1259 if (i > 0) {
1260 System.arraycopy(cur, 0, ret, 0, i);
1261 }
1262 if (i < (N-1)) {
1263 System.arraycopy(cur, i, ret, i+1, N-i-1);
1264 }
1265 return ret;
1266 }
1267 }
1268 return cur;
1269 }
1270
1271 static int[] removeInts(int[] cur, int[] rem) {
1272 if (rem == null) return cur;
1273 if (cur == null) return cur;
1274 final int N = rem.length;
1275 for (int i=0; i<N; i++) {
1276 cur = removeInt(cur, rem[i]);
1277 }
1278 return cur;
1279 }
1280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001282 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1283 // The package has been uninstalled but has retained data and resources.
1284 return PackageParser.generatePackageInfo(p, null, flags);
1285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 final PackageSetting ps = (PackageSetting)p.mExtras;
1287 if (ps == null) {
1288 return null;
1289 }
1290 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1291 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1292 }
1293
1294 public PackageInfo getPackageInfo(String packageName, int flags) {
1295 synchronized (mPackages) {
1296 PackageParser.Package p = mPackages.get(packageName);
1297 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001298 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 + ": " + p);
1300 if (p != null) {
1301 return generatePackageInfo(p, flags);
1302 }
1303 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1304 return generatePackageInfoFromSettingsLP(packageName, flags);
1305 }
1306 }
1307 return null;
1308 }
1309
Dianne Hackborn47096932010-02-11 15:57:09 -08001310 public String[] currentToCanonicalPackageNames(String[] names) {
1311 String[] out = new String[names.length];
1312 synchronized (mPackages) {
1313 for (int i=names.length-1; i>=0; i--) {
1314 PackageSetting ps = mSettings.mPackages.get(names[i]);
1315 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1316 }
1317 }
1318 return out;
1319 }
1320
1321 public String[] canonicalToCurrentPackageNames(String[] names) {
1322 String[] out = new String[names.length];
1323 synchronized (mPackages) {
1324 for (int i=names.length-1; i>=0; i--) {
1325 String cur = mSettings.mRenamedPackages.get(names[i]);
1326 out[i] = cur != null ? cur : names[i];
1327 }
1328 }
1329 return out;
1330 }
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 public int getPackageUid(String packageName) {
1333 synchronized (mPackages) {
1334 PackageParser.Package p = mPackages.get(packageName);
1335 if(p != null) {
1336 return p.applicationInfo.uid;
1337 }
1338 PackageSetting ps = mSettings.mPackages.get(packageName);
1339 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1340 return -1;
1341 }
1342 p = ps.pkg;
1343 return p != null ? p.applicationInfo.uid : -1;
1344 }
1345 }
1346
1347 public int[] getPackageGids(String packageName) {
1348 synchronized (mPackages) {
1349 PackageParser.Package p = mPackages.get(packageName);
1350 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001351 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 + ": " + p);
1353 if (p != null) {
1354 final PackageSetting ps = (PackageSetting)p.mExtras;
1355 final SharedUserSetting suid = ps.sharedUser;
1356 return suid != null ? suid.gids : ps.gids;
1357 }
1358 }
1359 // stupid thing to indicate an error.
1360 return new int[0];
1361 }
1362
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001363 static final PermissionInfo generatePermissionInfo(
1364 BasePermission bp, int flags) {
1365 if (bp.perm != null) {
1366 return PackageParser.generatePermissionInfo(bp.perm, flags);
1367 }
1368 PermissionInfo pi = new PermissionInfo();
1369 pi.name = bp.name;
1370 pi.packageName = bp.sourcePackage;
1371 pi.nonLocalizedLabel = bp.name;
1372 pi.protectionLevel = bp.protectionLevel;
1373 return pi;
1374 }
1375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 public PermissionInfo getPermissionInfo(String name, int flags) {
1377 synchronized (mPackages) {
1378 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001379 if (p != null) {
1380 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382 return null;
1383 }
1384 }
1385
1386 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1387 synchronized (mPackages) {
1388 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1389 for (BasePermission p : mSettings.mPermissions.values()) {
1390 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001391 if (p.perm == null || p.perm.info.group == null) {
1392 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001395 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1397 }
1398 }
1399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 if (out.size() > 0) {
1402 return out;
1403 }
1404 return mPermissionGroups.containsKey(group) ? out : null;
1405 }
1406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1409 synchronized (mPackages) {
1410 return PackageParser.generatePermissionGroupInfo(
1411 mPermissionGroups.get(name), flags);
1412 }
1413 }
1414
1415 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1416 synchronized (mPackages) {
1417 final int N = mPermissionGroups.size();
1418 ArrayList<PermissionGroupInfo> out
1419 = new ArrayList<PermissionGroupInfo>(N);
1420 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1421 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1422 }
1423 return out;
1424 }
1425 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1428 PackageSetting ps = mSettings.mPackages.get(packageName);
1429 if(ps != null) {
1430 if(ps.pkg == null) {
1431 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1432 if(pInfo != null) {
1433 return pInfo.applicationInfo;
1434 }
1435 return null;
1436 }
1437 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1438 }
1439 return null;
1440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1443 PackageSetting ps = mSettings.mPackages.get(packageName);
1444 if(ps != null) {
1445 if(ps.pkg == null) {
1446 ps.pkg = new PackageParser.Package(packageName);
1447 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001448 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1449 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1450 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1451 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453 return generatePackageInfo(ps.pkg, flags);
1454 }
1455 return null;
1456 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1459 synchronized (mPackages) {
1460 PackageParser.Package p = mPackages.get(packageName);
1461 if (Config.LOGV) Log.v(
1462 TAG, "getApplicationInfo " + packageName
1463 + ": " + p);
1464 if (p != null) {
1465 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001466 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 if ("android".equals(packageName)||"system".equals(packageName)) {
1469 return mAndroidApplication;
1470 }
1471 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1472 return generateApplicationInfoFromSettingsLP(packageName, flags);
1473 }
1474 }
1475 return null;
1476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001477
1478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1480 mContext.enforceCallingOrSelfPermission(
1481 android.Manifest.permission.CLEAR_APP_CACHE, null);
1482 // Queue up an async operation since clearing cache may take a little while.
1483 mHandler.post(new Runnable() {
1484 public void run() {
1485 mHandler.removeCallbacks(this);
1486 int retCode = -1;
1487 if (mInstaller != null) {
1488 retCode = mInstaller.freeCache(freeStorageSize);
1489 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001490 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492 } //end if mInstaller
1493 if (observer != null) {
1494 try {
1495 observer.onRemoveCompleted(null, (retCode >= 0));
1496 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001497 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499 }
1500 }
1501 });
1502 }
1503
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001504 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001505 mContext.enforceCallingOrSelfPermission(
1506 android.Manifest.permission.CLEAR_APP_CACHE, null);
1507 // Queue up an async operation since clearing cache may take a little while.
1508 mHandler.post(new Runnable() {
1509 public void run() {
1510 mHandler.removeCallbacks(this);
1511 int retCode = -1;
1512 if (mInstaller != null) {
1513 retCode = mInstaller.freeCache(freeStorageSize);
1514 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001515 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001516 }
1517 }
1518 if(pi != null) {
1519 try {
1520 // Callback via pending intent
1521 int code = (retCode >= 0) ? 1 : 0;
1522 pi.sendIntent(null, code, null,
1523 null, null);
1524 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001525 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001526 }
1527 }
1528 }
1529 });
1530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1533 synchronized (mPackages) {
1534 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001535
1536 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001538 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 if (mResolveComponentName.equals(component)) {
1541 return mResolveActivity;
1542 }
1543 }
1544 return null;
1545 }
1546
1547 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1548 synchronized (mPackages) {
1549 PackageParser.Activity a = mReceivers.mActivities.get(component);
1550 if (Config.LOGV) Log.v(
1551 TAG, "getReceiverInfo " + component + ": " + a);
1552 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1553 return PackageParser.generateActivityInfo(a, flags);
1554 }
1555 }
1556 return null;
1557 }
1558
1559 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1560 synchronized (mPackages) {
1561 PackageParser.Service s = mServices.mServices.get(component);
1562 if (Config.LOGV) Log.v(
1563 TAG, "getServiceInfo " + component + ": " + s);
1564 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1565 return PackageParser.generateServiceInfo(s, flags);
1566 }
1567 }
1568 return null;
1569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 public String[] getSystemSharedLibraryNames() {
1572 Set<String> libSet;
1573 synchronized (mPackages) {
1574 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001575 int size = libSet.size();
1576 if (size > 0) {
1577 String[] libs = new String[size];
1578 libSet.toArray(libs);
1579 return libs;
1580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001582 return null;
1583 }
1584
1585 public FeatureInfo[] getSystemAvailableFeatures() {
1586 Collection<FeatureInfo> featSet;
1587 synchronized (mPackages) {
1588 featSet = mAvailableFeatures.values();
1589 int size = featSet.size();
1590 if (size > 0) {
1591 FeatureInfo[] features = new FeatureInfo[size+1];
1592 featSet.toArray(features);
1593 FeatureInfo fi = new FeatureInfo();
1594 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1595 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1596 features[size] = fi;
1597 return features;
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 return null;
1601 }
1602
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001603 public boolean hasSystemFeature(String name) {
1604 synchronized (mPackages) {
1605 return mAvailableFeatures.containsKey(name);
1606 }
1607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 public int checkPermission(String permName, String pkgName) {
1610 synchronized (mPackages) {
1611 PackageParser.Package p = mPackages.get(pkgName);
1612 if (p != null && p.mExtras != null) {
1613 PackageSetting ps = (PackageSetting)p.mExtras;
1614 if (ps.sharedUser != null) {
1615 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1616 return PackageManager.PERMISSION_GRANTED;
1617 }
1618 } else if (ps.grantedPermissions.contains(permName)) {
1619 return PackageManager.PERMISSION_GRANTED;
1620 }
1621 }
1622 }
1623 return PackageManager.PERMISSION_DENIED;
1624 }
1625
1626 public int checkUidPermission(String permName, int uid) {
1627 synchronized (mPackages) {
1628 Object obj = mSettings.getUserIdLP(uid);
1629 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001630 GrantedPermissions gp = (GrantedPermissions)obj;
1631 if (gp.grantedPermissions.contains(permName)) {
1632 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 } else {
1635 HashSet<String> perms = mSystemPermissions.get(uid);
1636 if (perms != null && perms.contains(permName)) {
1637 return PackageManager.PERMISSION_GRANTED;
1638 }
1639 }
1640 }
1641 return PackageManager.PERMISSION_DENIED;
1642 }
1643
1644 private BasePermission findPermissionTreeLP(String permName) {
1645 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1646 if (permName.startsWith(bp.name) &&
1647 permName.length() > bp.name.length() &&
1648 permName.charAt(bp.name.length()) == '.') {
1649 return bp;
1650 }
1651 }
1652 return null;
1653 }
1654
1655 private BasePermission checkPermissionTreeLP(String permName) {
1656 if (permName != null) {
1657 BasePermission bp = findPermissionTreeLP(permName);
1658 if (bp != null) {
1659 if (bp.uid == Binder.getCallingUid()) {
1660 return bp;
1661 }
1662 throw new SecurityException("Calling uid "
1663 + Binder.getCallingUid()
1664 + " is not allowed to add to permission tree "
1665 + bp.name + " owned by uid " + bp.uid);
1666 }
1667 }
1668 throw new SecurityException("No permission tree found for " + permName);
1669 }
1670
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001671 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1672 if (s1 == null) {
1673 return s2 == null;
1674 }
1675 if (s2 == null) {
1676 return false;
1677 }
1678 if (s1.getClass() != s2.getClass()) {
1679 return false;
1680 }
1681 return s1.equals(s2);
1682 }
1683
1684 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1685 if (pi1.icon != pi2.icon) return false;
1686 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1687 if (!compareStrings(pi1.name, pi2.name)) return false;
1688 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1689 // We'll take care of setting this one.
1690 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1691 // These are not currently stored in settings.
1692 //if (!compareStrings(pi1.group, pi2.group)) return false;
1693 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1694 //if (pi1.labelRes != pi2.labelRes) return false;
1695 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1696 return true;
1697 }
1698
1699 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1700 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1701 throw new SecurityException("Label must be specified in permission");
1702 }
1703 BasePermission tree = checkPermissionTreeLP(info.name);
1704 BasePermission bp = mSettings.mPermissions.get(info.name);
1705 boolean added = bp == null;
1706 boolean changed = true;
1707 if (added) {
1708 bp = new BasePermission(info.name, tree.sourcePackage,
1709 BasePermission.TYPE_DYNAMIC);
1710 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1711 throw new SecurityException(
1712 "Not allowed to modify non-dynamic permission "
1713 + info.name);
1714 } else {
1715 if (bp.protectionLevel == info.protectionLevel
1716 && bp.perm.owner.equals(tree.perm.owner)
1717 && bp.uid == tree.uid
1718 && comparePermissionInfos(bp.perm.info, info)) {
1719 changed = false;
1720 }
1721 }
1722 bp.protectionLevel = info.protectionLevel;
1723 bp.perm = new PackageParser.Permission(tree.perm.owner,
1724 new PermissionInfo(info));
1725 bp.perm.info.packageName = tree.perm.info.packageName;
1726 bp.uid = tree.uid;
1727 if (added) {
1728 mSettings.mPermissions.put(info.name, bp);
1729 }
1730 if (changed) {
1731 if (!async) {
1732 mSettings.writeLP();
1733 } else {
1734 scheduleWriteSettingsLocked();
1735 }
1736 }
1737 return added;
1738 }
1739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 public boolean addPermission(PermissionInfo info) {
1741 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001742 return addPermissionLocked(info, false);
1743 }
1744 }
1745
1746 public boolean addPermissionAsync(PermissionInfo info) {
1747 synchronized (mPackages) {
1748 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
1750 }
1751
1752 public void removePermission(String name) {
1753 synchronized (mPackages) {
1754 checkPermissionTreeLP(name);
1755 BasePermission bp = mSettings.mPermissions.get(name);
1756 if (bp != null) {
1757 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1758 throw new SecurityException(
1759 "Not allowed to modify non-dynamic permission "
1760 + name);
1761 }
1762 mSettings.mPermissions.remove(name);
1763 mSettings.writeLP();
1764 }
1765 }
1766 }
1767
Dianne Hackborn854060af2009-07-09 18:14:31 -07001768 public boolean isProtectedBroadcast(String actionName) {
1769 synchronized (mPackages) {
1770 return mProtectedBroadcasts.contains(actionName);
1771 }
1772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 public int checkSignatures(String pkg1, String pkg2) {
1775 synchronized (mPackages) {
1776 PackageParser.Package p1 = mPackages.get(pkg1);
1777 PackageParser.Package p2 = mPackages.get(pkg2);
1778 if (p1 == null || p1.mExtras == null
1779 || p2 == null || p2.mExtras == null) {
1780 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1781 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001782 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784 }
1785
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001786 public int checkUidSignatures(int uid1, int uid2) {
1787 synchronized (mPackages) {
1788 Signature[] s1;
1789 Signature[] s2;
1790 Object obj = mSettings.getUserIdLP(uid1);
1791 if (obj != null) {
1792 if (obj instanceof SharedUserSetting) {
1793 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1794 } else if (obj instanceof PackageSetting) {
1795 s1 = ((PackageSetting)obj).signatures.mSignatures;
1796 } else {
1797 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1798 }
1799 } else {
1800 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1801 }
1802 obj = mSettings.getUserIdLP(uid2);
1803 if (obj != null) {
1804 if (obj instanceof SharedUserSetting) {
1805 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1806 } else if (obj instanceof PackageSetting) {
1807 s2 = ((PackageSetting)obj).signatures.mSignatures;
1808 } else {
1809 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1810 }
1811 } else {
1812 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1813 }
1814 return checkSignaturesLP(s1, s2);
1815 }
1816 }
1817
1818 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1819 if (s1 == null) {
1820 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1822 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1823 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001824 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1826 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001827 HashSet<Signature> set1 = new HashSet<Signature>();
1828 for (Signature sig : s1) {
1829 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001831 HashSet<Signature> set2 = new HashSet<Signature>();
1832 for (Signature sig : s2) {
1833 set2.add(sig);
1834 }
1835 // Make sure s2 contains all signatures in s1.
1836 if (set1.equals(set2)) {
1837 return PackageManager.SIGNATURE_MATCH;
1838 }
1839 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
1841
1842 public String[] getPackagesForUid(int uid) {
1843 synchronized (mPackages) {
1844 Object obj = mSettings.getUserIdLP(uid);
1845 if (obj instanceof SharedUserSetting) {
1846 SharedUserSetting sus = (SharedUserSetting)obj;
1847 final int N = sus.packages.size();
1848 String[] res = new String[N];
1849 Iterator<PackageSetting> it = sus.packages.iterator();
1850 int i=0;
1851 while (it.hasNext()) {
1852 res[i++] = it.next().name;
1853 }
1854 return res;
1855 } else if (obj instanceof PackageSetting) {
1856 PackageSetting ps = (PackageSetting)obj;
1857 return new String[] { ps.name };
1858 }
1859 }
1860 return null;
1861 }
1862
1863 public String getNameForUid(int uid) {
1864 synchronized (mPackages) {
1865 Object obj = mSettings.getUserIdLP(uid);
1866 if (obj instanceof SharedUserSetting) {
1867 SharedUserSetting sus = (SharedUserSetting)obj;
1868 return sus.name + ":" + sus.userId;
1869 } else if (obj instanceof PackageSetting) {
1870 PackageSetting ps = (PackageSetting)obj;
1871 return ps.name;
1872 }
1873 }
1874 return null;
1875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 public int getUidForSharedUser(String sharedUserName) {
1878 if(sharedUserName == null) {
1879 return -1;
1880 }
1881 synchronized (mPackages) {
1882 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1883 if(suid == null) {
1884 return -1;
1885 }
1886 return suid.userId;
1887 }
1888 }
1889
1890 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1891 int flags) {
1892 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001893 return chooseBestActivity(intent, resolvedType, flags, query);
1894 }
1895
Mihai Predaeae850c2009-05-13 10:13:48 +02001896 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1897 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 if (query != null) {
1899 final int N = query.size();
1900 if (N == 1) {
1901 return query.get(0);
1902 } else if (N > 1) {
1903 // If there is more than one activity with the same priority,
1904 // then let the user decide between them.
1905 ResolveInfo r0 = query.get(0);
1906 ResolveInfo r1 = query.get(1);
1907 if (false) {
1908 System.out.println(r0.activityInfo.name +
1909 "=" + r0.priority + " vs " +
1910 r1.activityInfo.name +
1911 "=" + r1.priority);
1912 }
1913 // If the first activity has a higher priority, or a different
1914 // default, then it is always desireable to pick it.
1915 if (r0.priority != r1.priority
1916 || r0.preferredOrder != r1.preferredOrder
1917 || r0.isDefault != r1.isDefault) {
1918 return query.get(0);
1919 }
1920 // If we have saved a preference for a preferred activity for
1921 // this Intent, use that.
1922 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1923 flags, query, r0.priority);
1924 if (ri != null) {
1925 return ri;
1926 }
1927 return mResolveInfo;
1928 }
1929 }
1930 return null;
1931 }
1932
1933 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1934 int flags, List<ResolveInfo> query, int priority) {
1935 synchronized (mPackages) {
1936 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1937 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001938 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1940 if (prefs != null && prefs.size() > 0) {
1941 // First figure out how good the original match set is.
1942 // We will only allow preferred activities that came
1943 // from the same match quality.
1944 int match = 0;
1945 final int N = query.size();
1946 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1947 for (int j=0; j<N; j++) {
1948 ResolveInfo ri = query.get(j);
1949 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1950 + ": 0x" + Integer.toHexString(match));
1951 if (ri.match > match) match = ri.match;
1952 }
1953 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1954 + Integer.toHexString(match));
1955 match &= IntentFilter.MATCH_CATEGORY_MASK;
1956 final int M = prefs.size();
1957 for (int i=0; i<M; i++) {
1958 PreferredActivity pa = prefs.get(i);
1959 if (pa.mMatch != match) {
1960 continue;
1961 }
1962 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1963 if (DEBUG_PREFERRED) {
1964 Log.v(TAG, "Got preferred activity:");
1965 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1966 }
1967 if (ai != null) {
1968 for (int j=0; j<N; j++) {
1969 ResolveInfo ri = query.get(j);
1970 if (!ri.activityInfo.applicationInfo.packageName
1971 .equals(ai.applicationInfo.packageName)) {
1972 continue;
1973 }
1974 if (!ri.activityInfo.name.equals(ai.name)) {
1975 continue;
1976 }
1977
1978 // Okay we found a previously set preferred app.
1979 // If the result set is different from when this
1980 // was created, we need to clear it and re-ask the
1981 // user their preference.
1982 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001983 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 + intent + " type " + resolvedType);
1985 mSettings.mPreferredActivities.removeFilter(pa);
1986 return null;
1987 }
1988
1989 // Yay!
1990 return ri;
1991 }
1992 }
1993 }
1994 }
1995 }
1996 return null;
1997 }
1998
1999 public List<ResolveInfo> queryIntentActivities(Intent intent,
2000 String resolvedType, int flags) {
2001 ComponentName comp = intent.getComponent();
2002 if (comp != null) {
2003 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2004 ActivityInfo ai = getActivityInfo(comp, flags);
2005 if (ai != null) {
2006 ResolveInfo ri = new ResolveInfo();
2007 ri.activityInfo = ai;
2008 list.add(ri);
2009 }
2010 return list;
2011 }
2012
2013 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002014 String pkgName = intent.getPackage();
2015 if (pkgName == null) {
2016 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2017 resolvedType, flags);
2018 }
2019 PackageParser.Package pkg = mPackages.get(pkgName);
2020 if (pkg != null) {
2021 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2022 resolvedType, flags, pkg.activities);
2023 }
2024 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026 }
2027
2028 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2029 Intent[] specifics, String[] specificTypes, Intent intent,
2030 String resolvedType, int flags) {
2031 final String resultsAction = intent.getAction();
2032
2033 List<ResolveInfo> results = queryIntentActivities(
2034 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2035 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2036
2037 int specificsPos = 0;
2038 int N;
2039
2040 // todo: note that the algorithm used here is O(N^2). This
2041 // isn't a problem in our current environment, but if we start running
2042 // into situations where we have more than 5 or 10 matches then this
2043 // should probably be changed to something smarter...
2044
2045 // First we go through and resolve each of the specific items
2046 // that were supplied, taking care of removing any corresponding
2047 // duplicate items in the generic resolve list.
2048 if (specifics != null) {
2049 for (int i=0; i<specifics.length; i++) {
2050 final Intent sintent = specifics[i];
2051 if (sintent == null) {
2052 continue;
2053 }
2054
2055 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2056 String action = sintent.getAction();
2057 if (resultsAction != null && resultsAction.equals(action)) {
2058 // If this action was explicitly requested, then don't
2059 // remove things that have it.
2060 action = null;
2061 }
2062 ComponentName comp = sintent.getComponent();
2063 ResolveInfo ri = null;
2064 ActivityInfo ai = null;
2065 if (comp == null) {
2066 ri = resolveIntent(
2067 sintent,
2068 specificTypes != null ? specificTypes[i] : null,
2069 flags);
2070 if (ri == null) {
2071 continue;
2072 }
2073 if (ri == mResolveInfo) {
2074 // ACK! Must do something better with this.
2075 }
2076 ai = ri.activityInfo;
2077 comp = new ComponentName(ai.applicationInfo.packageName,
2078 ai.name);
2079 } else {
2080 ai = getActivityInfo(comp, flags);
2081 if (ai == null) {
2082 continue;
2083 }
2084 }
2085
2086 // Look for any generic query activities that are duplicates
2087 // of this specific one, and remove them from the results.
2088 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2089 N = results.size();
2090 int j;
2091 for (j=specificsPos; j<N; j++) {
2092 ResolveInfo sri = results.get(j);
2093 if ((sri.activityInfo.name.equals(comp.getClassName())
2094 && sri.activityInfo.applicationInfo.packageName.equals(
2095 comp.getPackageName()))
2096 || (action != null && sri.filter.matchAction(action))) {
2097 results.remove(j);
2098 if (Config.LOGV) Log.v(
2099 TAG, "Removing duplicate item from " + j
2100 + " due to specific " + specificsPos);
2101 if (ri == null) {
2102 ri = sri;
2103 }
2104 j--;
2105 N--;
2106 }
2107 }
2108
2109 // Add this specific item to its proper place.
2110 if (ri == null) {
2111 ri = new ResolveInfo();
2112 ri.activityInfo = ai;
2113 }
2114 results.add(specificsPos, ri);
2115 ri.specificIndex = i;
2116 specificsPos++;
2117 }
2118 }
2119
2120 // Now we go through the remaining generic results and remove any
2121 // duplicate actions that are found here.
2122 N = results.size();
2123 for (int i=specificsPos; i<N-1; i++) {
2124 final ResolveInfo rii = results.get(i);
2125 if (rii.filter == null) {
2126 continue;
2127 }
2128
2129 // Iterate over all of the actions of this result's intent
2130 // filter... typically this should be just one.
2131 final Iterator<String> it = rii.filter.actionsIterator();
2132 if (it == null) {
2133 continue;
2134 }
2135 while (it.hasNext()) {
2136 final String action = it.next();
2137 if (resultsAction != null && resultsAction.equals(action)) {
2138 // If this action was explicitly requested, then don't
2139 // remove things that have it.
2140 continue;
2141 }
2142 for (int j=i+1; j<N; j++) {
2143 final ResolveInfo rij = results.get(j);
2144 if (rij.filter != null && rij.filter.hasAction(action)) {
2145 results.remove(j);
2146 if (Config.LOGV) Log.v(
2147 TAG, "Removing duplicate item from " + j
2148 + " due to action " + action + " at " + i);
2149 j--;
2150 N--;
2151 }
2152 }
2153 }
2154
2155 // If the caller didn't request filter information, drop it now
2156 // so we don't have to marshall/unmarshall it.
2157 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2158 rii.filter = null;
2159 }
2160 }
2161
2162 // Filter out the caller activity if so requested.
2163 if (caller != null) {
2164 N = results.size();
2165 for (int i=0; i<N; i++) {
2166 ActivityInfo ainfo = results.get(i).activityInfo;
2167 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2168 && caller.getClassName().equals(ainfo.name)) {
2169 results.remove(i);
2170 break;
2171 }
2172 }
2173 }
2174
2175 // If the caller didn't request filter information,
2176 // drop them now so we don't have to
2177 // marshall/unmarshall it.
2178 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2179 N = results.size();
2180 for (int i=0; i<N; i++) {
2181 results.get(i).filter = null;
2182 }
2183 }
2184
2185 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2186 return results;
2187 }
2188
2189 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2190 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002191 ComponentName comp = intent.getComponent();
2192 if (comp != null) {
2193 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2194 ActivityInfo ai = getReceiverInfo(comp, flags);
2195 if (ai != null) {
2196 ResolveInfo ri = new ResolveInfo();
2197 ri.activityInfo = ai;
2198 list.add(ri);
2199 }
2200 return list;
2201 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002204 String pkgName = intent.getPackage();
2205 if (pkgName == null) {
2206 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2207 resolvedType, flags);
2208 }
2209 PackageParser.Package pkg = mPackages.get(pkgName);
2210 if (pkg != null) {
2211 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2212 resolvedType, flags, pkg.receivers);
2213 }
2214 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 }
2216 }
2217
2218 public ResolveInfo resolveService(Intent intent, String resolvedType,
2219 int flags) {
2220 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2221 flags);
2222 if (query != null) {
2223 if (query.size() >= 1) {
2224 // If there is more than one service with the same priority,
2225 // just arbitrarily pick the first one.
2226 return query.get(0);
2227 }
2228 }
2229 return null;
2230 }
2231
2232 public List<ResolveInfo> queryIntentServices(Intent intent,
2233 String resolvedType, int flags) {
2234 ComponentName comp = intent.getComponent();
2235 if (comp != null) {
2236 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2237 ServiceInfo si = getServiceInfo(comp, flags);
2238 if (si != null) {
2239 ResolveInfo ri = new ResolveInfo();
2240 ri.serviceInfo = si;
2241 list.add(ri);
2242 }
2243 return list;
2244 }
2245
2246 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002247 String pkgName = intent.getPackage();
2248 if (pkgName == null) {
2249 return (List<ResolveInfo>)mServices.queryIntent(intent,
2250 resolvedType, flags);
2251 }
2252 PackageParser.Package pkg = mPackages.get(pkgName);
2253 if (pkg != null) {
2254 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2255 resolvedType, flags, pkg.services);
2256 }
2257 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 public List<PackageInfo> getInstalledPackages(int flags) {
2262 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2263
2264 synchronized (mPackages) {
2265 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2266 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2267 while (i.hasNext()) {
2268 final PackageSetting ps = i.next();
2269 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2270 if(psPkg != null) {
2271 finalList.add(psPkg);
2272 }
2273 }
2274 }
2275 else {
2276 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2277 while (i.hasNext()) {
2278 final PackageParser.Package p = i.next();
2279 if (p.applicationInfo != null) {
2280 PackageInfo pi = generatePackageInfo(p, flags);
2281 if(pi != null) {
2282 finalList.add(pi);
2283 }
2284 }
2285 }
2286 }
2287 }
2288 return finalList;
2289 }
2290
2291 public List<ApplicationInfo> getInstalledApplications(int flags) {
2292 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2293 synchronized(mPackages) {
2294 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2295 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2296 while (i.hasNext()) {
2297 final PackageSetting ps = i.next();
2298 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2299 if(ai != null) {
2300 finalList.add(ai);
2301 }
2302 }
2303 }
2304 else {
2305 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2306 while (i.hasNext()) {
2307 final PackageParser.Package p = i.next();
2308 if (p.applicationInfo != null) {
2309 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2310 if(ai != null) {
2311 finalList.add(ai);
2312 }
2313 }
2314 }
2315 }
2316 }
2317 return finalList;
2318 }
2319
2320 public List<ApplicationInfo> getPersistentApplications(int flags) {
2321 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2322
2323 synchronized (mPackages) {
2324 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2325 while (i.hasNext()) {
2326 PackageParser.Package p = i.next();
2327 if (p.applicationInfo != null
2328 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2329 && (!mSafeMode || (p.applicationInfo.flags
2330 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2331 finalList.add(p.applicationInfo);
2332 }
2333 }
2334 }
2335
2336 return finalList;
2337 }
2338
2339 public ProviderInfo resolveContentProvider(String name, int flags) {
2340 synchronized (mPackages) {
2341 final PackageParser.Provider provider = mProviders.get(name);
2342 return provider != null
2343 && mSettings.isEnabledLP(provider.info, flags)
2344 && (!mSafeMode || (provider.info.applicationInfo.flags
2345 &ApplicationInfo.FLAG_SYSTEM) != 0)
2346 ? PackageParser.generateProviderInfo(provider, flags)
2347 : null;
2348 }
2349 }
2350
Fred Quintana718d8a22009-04-29 17:53:20 -07002351 /**
2352 * @deprecated
2353 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 public void querySyncProviders(List outNames, List outInfo) {
2355 synchronized (mPackages) {
2356 Iterator<Map.Entry<String, PackageParser.Provider>> i
2357 = mProviders.entrySet().iterator();
2358
2359 while (i.hasNext()) {
2360 Map.Entry<String, PackageParser.Provider> entry = i.next();
2361 PackageParser.Provider p = entry.getValue();
2362
2363 if (p.syncable
2364 && (!mSafeMode || (p.info.applicationInfo.flags
2365 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2366 outNames.add(entry.getKey());
2367 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2368 }
2369 }
2370 }
2371 }
2372
2373 public List<ProviderInfo> queryContentProviders(String processName,
2374 int uid, int flags) {
2375 ArrayList<ProviderInfo> finalList = null;
2376
2377 synchronized (mPackages) {
2378 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2379 while (i.hasNext()) {
2380 PackageParser.Provider p = i.next();
2381 if (p.info.authority != null
2382 && (processName == null ||
2383 (p.info.processName.equals(processName)
2384 && p.info.applicationInfo.uid == uid))
2385 && mSettings.isEnabledLP(p.info, flags)
2386 && (!mSafeMode || (p.info.applicationInfo.flags
2387 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2388 if (finalList == null) {
2389 finalList = new ArrayList<ProviderInfo>(3);
2390 }
2391 finalList.add(PackageParser.generateProviderInfo(p,
2392 flags));
2393 }
2394 }
2395 }
2396
2397 if (finalList != null) {
2398 Collections.sort(finalList, mProviderInitOrderSorter);
2399 }
2400
2401 return finalList;
2402 }
2403
2404 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2405 int flags) {
2406 synchronized (mPackages) {
2407 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2408 return PackageParser.generateInstrumentationInfo(i, flags);
2409 }
2410 }
2411
2412 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2413 int flags) {
2414 ArrayList<InstrumentationInfo> finalList =
2415 new ArrayList<InstrumentationInfo>();
2416
2417 synchronized (mPackages) {
2418 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2419 while (i.hasNext()) {
2420 PackageParser.Instrumentation p = i.next();
2421 if (targetPackage == null
2422 || targetPackage.equals(p.info.targetPackage)) {
2423 finalList.add(PackageParser.generateInstrumentationInfo(p,
2424 flags));
2425 }
2426 }
2427 }
2428
2429 return finalList;
2430 }
2431
2432 private void scanDirLI(File dir, int flags, int scanMode) {
2433 Log.d(TAG, "Scanning app dir " + dir);
2434
2435 String[] files = dir.list();
2436
2437 int i;
2438 for (i=0; i<files.length; i++) {
2439 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002440 if (!isPackageFilename(files[i])) {
2441 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002442 continue;
2443 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002444 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002446 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002447 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2448 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002449 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002450 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002451 file.delete();
2452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 }
2454 }
2455
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002456 private static File getSettingsProblemFile() {
2457 File dataDir = Environment.getDataDirectory();
2458 File systemDir = new File(dataDir, "system");
2459 File fname = new File(systemDir, "uiderrors.txt");
2460 return fname;
2461 }
2462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 private static void reportSettingsProblem(int priority, String msg) {
2464 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002465 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 FileOutputStream out = new FileOutputStream(fname, true);
2467 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002468 SimpleDateFormat formatter = new SimpleDateFormat();
2469 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2470 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 pw.close();
2472 FileUtils.setPermissions(
2473 fname.toString(),
2474 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2475 -1, -1);
2476 } catch (java.io.IOException e) {
2477 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002478 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
2480
2481 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2482 PackageParser.Package pkg, File srcFile, int parseFlags) {
2483 if (GET_CERTIFICATES) {
2484 if (ps == null || !ps.codePath.equals(srcFile)
2485 || ps.getTimeStamp() != srcFile.lastModified()) {
2486 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2487 if (!pp.collectCertificates(pkg, parseFlags)) {
2488 mLastScanError = pp.getParseError();
2489 return false;
2490 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002491 } else {
2492 // Lets implicitly assign existing certificates.
2493 pkg.mSignatures = ps.signatures.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002494 }
2495 }
2496 return true;
2497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 /*
2500 * Scan a package and return the newly parsed package.
2501 * Returns null in case of errors and the error code is stored in mLastScanError
2502 */
2503 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002504 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002506 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002508 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002511 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 if (pkg == null) {
2513 mLastScanError = pp.getParseError();
2514 return null;
2515 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002516 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 PackageSetting updatedPkg;
2518 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002519 // Look to see if we already know about this package.
2520 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002521 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002522 // This package has been renamed to its original name. Let's
2523 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002524 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002525 }
2526 // If there was no original package, see one for the real package name.
2527 if (ps == null) {
2528 ps = mSettings.peekPackageLP(pkg.packageName);
2529 }
2530 // Check to see if this package could be hiding/updating a system
2531 // package. Must look for it either under the original or real
2532 // package name depending on our state.
2533 updatedPkg = mSettings.mDisabledSysPackages.get(
2534 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002536 // First check if this is a system package that may involve an update
2537 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2538 if (!ps.codePath.equals(scanFile)) {
2539 // The path has changed from what was last scanned... check the
2540 // version of the new path against what we have stored to determine
2541 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002542 if (pkg.mVersionCode < ps.versionCode) {
2543 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002544 // Ignore entry. Skip it.
2545 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2546 + "ignored: updated version " + ps.versionCode
2547 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002548 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2549 return null;
2550 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002551 // The current app on the system partion is better than
2552 // what we have updated to on the data partition; switch
2553 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002554 // At this point, its safely assumed that package installation for
2555 // apps in system partition will go through. If not there won't be a working
2556 // version of the app
2557 synchronized (mPackages) {
2558 // Just remove the loaded entries from package lists.
2559 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002560 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002561 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002562 + "reverting from " + ps.codePathString
2563 + ": new version " + pkg.mVersionCode
2564 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002565 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2566 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002567 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 }
2570 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002571 if (updatedPkg != null) {
2572 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2573 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2574 }
2575 // Verify certificates against what was last scanned
2576 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002577 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002578 return null;
2579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 // The apk is forward locked (not public) if its code and resources
2581 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002582 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002584 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002585 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002586
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002587 String codePath = null;
2588 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002589 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2590 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002591 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002592 } else {
2593 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002594 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002595 }
2596 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002597 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002598 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002599 codePath = pkg.mScanPath;
2600 // Set application objects path explicitly.
2601 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002603 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
2605
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002606 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2607 String destCodePath, String destResPath) {
2608 pkg.mPath = pkg.mScanPath = destCodePath;
2609 pkg.applicationInfo.sourceDir = destCodePath;
2610 pkg.applicationInfo.publicSourceDir = destResPath;
2611 }
2612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 private static String fixProcessName(String defProcessName,
2614 String processName, int uid) {
2615 if (processName == null) {
2616 return defProcessName;
2617 }
2618 return processName;
2619 }
2620
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002621 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002622 PackageParser.Package pkg) {
2623 if (pkgSetting.signatures.mSignatures != null) {
2624 // Already existing package. Make sure signatures match
2625 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2626 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002627 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002628 + " signatures do not match the previously installed version; ignoring!");
2629 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 return false;
2631 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002632 }
2633 // Check for shared user signatures
2634 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2635 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2636 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2637 Slog.e(TAG, "Package " + pkg.packageName
2638 + " has no signatures that match those in shared user "
2639 + pkgSetting.sharedUser.name + "; ignoring!");
2640 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2641 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 }
2644 return true;
2645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002646
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002647 public boolean performDexOpt(String packageName) {
2648 if (!mNoDexOpt) {
2649 return false;
2650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002651
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002652 PackageParser.Package p;
2653 synchronized (mPackages) {
2654 p = mPackages.get(packageName);
2655 if (p == null || p.mDidDexOpt) {
2656 return false;
2657 }
2658 }
2659 synchronized (mInstallLock) {
2660 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2661 }
2662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002663
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002664 static final int DEX_OPT_SKIPPED = 0;
2665 static final int DEX_OPT_PERFORMED = 1;
2666 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002667
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002668 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2669 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002670 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002671 String path = pkg.mScanPath;
2672 int ret = 0;
2673 try {
2674 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002675 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002676 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002677 pkg.mDidDexOpt = true;
2678 performed = true;
2679 }
2680 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002681 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002682 ret = -1;
2683 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002684 Slog.w(TAG, "IOException reading apk: " + path, e);
2685 ret = -1;
2686 } catch (dalvik.system.StaleDexCacheError e) {
2687 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2688 ret = -1;
2689 } catch (Exception e) {
2690 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002691 ret = -1;
2692 }
2693 if (ret < 0) {
2694 //error from installer
2695 return DEX_OPT_FAILED;
2696 }
2697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002698
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002699 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2700 }
2701
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002702 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2703 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002704 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002705 + " to " + newPkg.packageName
2706 + ": old package not in system partition");
2707 return false;
2708 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002709 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002710 + " to " + newPkg.packageName
2711 + ": old package still exists");
2712 return false;
2713 }
2714 return true;
2715 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002716
2717 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002718 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002719 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002720
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002721 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2722 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002723 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002724 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2725 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002726 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002727 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002728 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2729 return null;
2730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 mScanningPath = scanFile;
2732 if (pkg == null) {
2733 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2734 return null;
2735 }
2736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2738 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2739 }
2740
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002741 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 synchronized (mPackages) {
2743 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002744 Slog.w(TAG, "*************************************************");
2745 Slog.w(TAG, "Core android package being redefined. Skipping.");
2746 Slog.w(TAG, " file=" + mScanningPath);
2747 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2749 return null;
2750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 // Set up information for our fall-back user intent resolution
2753 // activity.
2754 mPlatformPackage = pkg;
2755 pkg.mVersionCode = mSdkVersion;
2756 mAndroidApplication = pkg.applicationInfo;
2757 mResolveActivity.applicationInfo = mAndroidApplication;
2758 mResolveActivity.name = ResolverActivity.class.getName();
2759 mResolveActivity.packageName = mAndroidApplication.packageName;
2760 mResolveActivity.processName = mAndroidApplication.processName;
2761 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2762 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2763 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2764 mResolveActivity.exported = true;
2765 mResolveActivity.enabled = true;
2766 mResolveInfo.activityInfo = mResolveActivity;
2767 mResolveInfo.priority = 0;
2768 mResolveInfo.preferredOrder = 0;
2769 mResolveInfo.match = 0;
2770 mResolveComponentName = new ComponentName(
2771 mAndroidApplication.packageName, mResolveActivity.name);
2772 }
2773 }
2774
2775 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002776 TAG, "Scanning package " + pkg.packageName);
2777 if (mPackages.containsKey(pkg.packageName)
2778 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002779 Slog.w(TAG, "*************************************************");
2780 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002782 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2784 return null;
2785 }
2786
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002787 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002788 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2789 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 SharedUserSetting suid = null;
2792 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002793
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002794 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2795 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002796 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002797 pkg.mRealPackage = null;
2798 pkg.mAdoptPermissions = null;
2799 }
2800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 synchronized (mPackages) {
2802 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002803 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2804 if (mTmpSharedLibraries == null ||
2805 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2806 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2807 }
2808 int num = 0;
2809 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2810 for (int i=0; i<N; i++) {
2811 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002813 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002815 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2817 return null;
2818 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002819 mTmpSharedLibraries[num] = file;
2820 num++;
2821 }
2822 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2823 for (int i=0; i<N; i++) {
2824 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2825 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002826 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002827 + " desires unavailable shared library "
2828 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2829 } else {
2830 mTmpSharedLibraries[num] = file;
2831 num++;
2832 }
2833 }
2834 if (num > 0) {
2835 pkg.usesLibraryFiles = new String[num];
2836 System.arraycopy(mTmpSharedLibraries, 0,
2837 pkg.usesLibraryFiles, 0, num);
2838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002839
Dianne Hackborn49237342009-08-27 20:08:01 -07002840 if (pkg.reqFeatures != null) {
2841 N = pkg.reqFeatures.size();
2842 for (int i=0; i<N; i++) {
2843 FeatureInfo fi = pkg.reqFeatures.get(i);
2844 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2845 // Don't care.
2846 continue;
2847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002848
Dianne Hackborn49237342009-08-27 20:08:01 -07002849 if (fi.name != null) {
2850 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002851 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002852 + " requires unavailable feature "
2853 + fi.name + "; failing!");
2854 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2855 return null;
2856 }
2857 }
2858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 }
2860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 if (pkg.mSharedUserId != null) {
2863 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2864 pkg.applicationInfo.flags, true);
2865 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002866 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 + " for shared user failed");
2868 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2869 return null;
2870 }
2871 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2872 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2873 + suid.userId + "): packages=" + suid.packages);
2874 }
2875 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002876
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002878 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002879 Log.w(TAG, "WAITING FOR DEBUGGER");
2880 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002881 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2882 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002883 }
2884 }
2885
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002886 // Check if we are renaming from an original package name.
2887 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002889 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002890 // This package may need to be renamed to a previously
2891 // installed name. Let's check on that...
2892 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002893 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002894 // This package had originally been installed as the
2895 // original name, and we have already taken care of
2896 // transitioning to the new one. Just update the new
2897 // one to continue using the old name.
2898 realName = pkg.mRealPackage;
2899 if (!pkg.packageName.equals(renamed)) {
2900 // Callers into this function may have already taken
2901 // care of renaming the package; only do it here if
2902 // it is not already done.
2903 pkg.setPackageName(renamed);
2904 }
2905
Dianne Hackbornc1552392010-03-03 16:19:01 -08002906 } else {
2907 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2908 if ((origPackage=mSettings.peekPackageLP(
2909 pkg.mOriginalPackages.get(i))) != null) {
2910 // We do have the package already installed under its
2911 // original name... should we use it?
2912 if (!verifyPackageUpdate(origPackage, pkg)) {
2913 // New package is not compatible with original.
2914 origPackage = null;
2915 continue;
2916 } else if (origPackage.sharedUser != null) {
2917 // Make sure uid is compatible between packages.
2918 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002919 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002920 + " to " + pkg.packageName + ": old uid "
2921 + origPackage.sharedUser.name
2922 + " differs from " + pkg.mSharedUserId);
2923 origPackage = null;
2924 continue;
2925 }
2926 } else {
2927 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2928 + pkg.packageName + " to old name " + origPackage.name);
2929 }
2930 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002931 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002932 }
2933 }
2934 }
2935
2936 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002937 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002938 + " was transferred to another, but its .apk remains");
2939 }
2940
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002941 // Just create the setting, don't add it yet. For already existing packages
2942 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002943 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 destResourceFile, pkg.applicationInfo.flags, true, false);
2945 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002946 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2948 return null;
2949 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002950
2951 if (pkgSetting.origPackage != null) {
2952 // If we are first transitioning from an original package,
2953 // fix up the new package's name now. We need to do this after
2954 // looking up the package under its new name, so getPackageLP
2955 // can take care of fiddling things correctly.
2956 pkg.setPackageName(origPackage.name);
2957
2958 // File a report about this.
2959 String msg = "New package " + pkgSetting.realName
2960 + " renamed to replace old package " + pkgSetting.name;
2961 reportSettingsProblem(Log.WARN, msg);
2962
2963 // Make a note of it.
2964 mTransferedPackages.add(origPackage.name);
2965
2966 // No longer need to retain this.
2967 pkgSetting.origPackage = null;
2968 }
2969
2970 if (realName != null) {
2971 // Make a note of it.
2972 mTransferedPackages.add(pkg.packageName);
2973 }
2974
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002975 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2977 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 pkg.applicationInfo.uid = pkgSetting.userId;
2980 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002981
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002982 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002983 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 return null;
2985 }
2986 // The signature has changed, but this package is in the system
2987 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002988 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 // However... if this package is part of a shared user, but it
2990 // doesn't match the signature of the shared user, let's fail.
2991 // What this means is that you can't change the signatures
2992 // associated with an overall shared user, which doesn't seem all
2993 // that unreasonable.
2994 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002995 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2996 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2997 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2999 return null;
3000 }
3001 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003002 // File a report about this.
3003 String msg = "System package " + pkg.packageName
3004 + " signature changed; retaining data.";
3005 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003007
The Android Open Source Project10592532009-03-18 17:39:46 -07003008 // Verify that this new package doesn't have any content providers
3009 // that conflict with existing packages. Only do this if the
3010 // package isn't already installed, since we don't want to break
3011 // things that are installed.
3012 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3013 int N = pkg.providers.size();
3014 int i;
3015 for (i=0; i<N; i++) {
3016 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003017 if (p.info.authority != null) {
3018 String names[] = p.info.authority.split(";");
3019 for (int j = 0; j < names.length; j++) {
3020 if (mProviders.containsKey(names[j])) {
3021 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003022 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003023 " (in package " + pkg.applicationInfo.packageName +
3024 ") is already used by "
3025 + ((other != null && other.getComponentName() != null)
3026 ? other.getComponentName().getPackageName() : "?"));
3027 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3028 return null;
3029 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003030 }
3031 }
3032 }
3033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 }
3035
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003036 final String pkgName = pkg.packageName;
3037
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003038 if (pkg.mAdoptPermissions != null) {
3039 // This package wants to adopt ownership of permissions from
3040 // another package.
3041 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3042 String origName = pkg.mAdoptPermissions.get(i);
3043 PackageSetting orig = mSettings.peekPackageLP(origName);
3044 if (orig != null) {
3045 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003046 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003047 + origName + " to " + pkg.packageName);
3048 mSettings.transferPermissions(origName, pkg.packageName);
3049 }
3050 }
3051 }
3052 }
3053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 long scanFileTime = scanFile.lastModified();
3055 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3056 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3057 pkg.applicationInfo.processName = fixProcessName(
3058 pkg.applicationInfo.packageName,
3059 pkg.applicationInfo.processName,
3060 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061
3062 File dataPath;
3063 if (mPlatformPackage == pkg) {
3064 // The system package is special.
3065 dataPath = new File (Environment.getDataDirectory(), "system");
3066 pkg.applicationInfo.dataDir = dataPath.getPath();
3067 } else {
3068 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003069 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003070
3071 boolean uidError = false;
3072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 if (dataPath.exists()) {
3074 mOutPermissions[1] = 0;
3075 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3076 if (mOutPermissions[1] == pkg.applicationInfo.uid
3077 || !Process.supportsProcesses()) {
3078 pkg.applicationInfo.dataDir = dataPath.getPath();
3079 } else {
3080 boolean recovered = false;
3081 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3082 // If this is a system app, we can at least delete its
3083 // current data so the application will still work.
3084 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003085 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003086 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 // Old data gone!
3088 String msg = "System package " + pkg.packageName
3089 + " has changed from uid: "
3090 + mOutPermissions[1] + " to "
3091 + pkg.applicationInfo.uid + "; old data erased";
3092 reportSettingsProblem(Log.WARN, msg);
3093 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003096 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 pkg.applicationInfo.uid);
3098 if (ret == -1) {
3099 // Ack should not happen!
3100 msg = "System package " + pkg.packageName
3101 + " could not have data directory re-created after delete.";
3102 reportSettingsProblem(Log.WARN, msg);
3103 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3104 return null;
3105 }
3106 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 if (!recovered) {
3109 mHasSystemUidErrors = true;
3110 }
3111 }
3112 if (!recovered) {
3113 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3114 + pkg.applicationInfo.uid + "/fs_"
3115 + mOutPermissions[1];
3116 String msg = "Package " + pkg.packageName
3117 + " has mismatched uid: "
3118 + mOutPermissions[1] + " on disk, "
3119 + pkg.applicationInfo.uid + " in settings";
3120 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003121 mSettings.mReadMessages.append(msg);
3122 mSettings.mReadMessages.append('\n');
3123 uidError = true;
3124 if (!pkgSetting.uidError) {
3125 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 }
3128 }
3129 }
3130 pkg.applicationInfo.dataDir = dataPath.getPath();
3131 } else {
3132 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3133 Log.v(TAG, "Want this data dir: " + dataPath);
3134 //invoke installer to do the actual installation
3135 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003136 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 pkg.applicationInfo.uid);
3138 if(ret < 0) {
3139 // Error from installer
3140 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3141 return null;
3142 }
3143 } else {
3144 dataPath.mkdirs();
3145 if (dataPath.exists()) {
3146 FileUtils.setPermissions(
3147 dataPath.toString(),
3148 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3149 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3150 }
3151 }
3152 if (dataPath.exists()) {
3153 pkg.applicationInfo.dataDir = dataPath.getPath();
3154 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003155 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 pkg.applicationInfo.dataDir = null;
3157 }
3158 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003159
3160 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
3162
3163 // Perform shared library installation and dex validation and
3164 // optimization, if this is not a system app.
3165 if (mInstaller != null) {
3166 String path = scanFile.getPath();
3167 if (scanFileNewer) {
3168 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003169 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3170 if (err != PackageManager.INSTALL_SUCCEEDED) {
3171 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 return null;
3173 }
3174 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003175 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003177 if ((scanMode&SCAN_NO_DEX) == 0) {
3178 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3180 return null;
3181 }
3182 }
3183 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 if (mFactoryTest && pkg.requestedPermissions.contains(
3186 android.Manifest.permission.FACTORY_TEST)) {
3187 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3188 }
3189
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003190 // Request the ActivityManager to kill the process(only for existing packages)
3191 // so that we do not end up in a confused state while the user is still using the older
3192 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003193 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003194 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003195 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003196 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003199 // We don't expect installation to fail beyond this point,
3200 if ((scanMode&SCAN_MONITOR) != 0) {
3201 mAppDirs.put(pkg.mPath, pkg);
3202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003204 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003206 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003207 // Make sure we don't accidentally delete its data.
3208 mSettings.mPackagesToBeCleaned.remove(pkgName);
3209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 int N = pkg.providers.size();
3211 StringBuilder r = null;
3212 int i;
3213 for (i=0; i<N; i++) {
3214 PackageParser.Provider p = pkg.providers.get(i);
3215 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3216 p.info.processName, pkg.applicationInfo.uid);
3217 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3218 p.info.name), p);
3219 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003220 if (p.info.authority != null) {
3221 String names[] = p.info.authority.split(";");
3222 p.info.authority = null;
3223 for (int j = 0; j < names.length; j++) {
3224 if (j == 1 && p.syncable) {
3225 // We only want the first authority for a provider to possibly be
3226 // syncable, so if we already added this provider using a different
3227 // authority clear the syncable flag. We copy the provider before
3228 // changing it because the mProviders object contains a reference
3229 // to a provider that we don't want to change.
3230 // Only do this for the second authority since the resulting provider
3231 // object can be the same for all future authorities for this provider.
3232 p = new PackageParser.Provider(p);
3233 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003235 if (!mProviders.containsKey(names[j])) {
3236 mProviders.put(names[j], p);
3237 if (p.info.authority == null) {
3238 p.info.authority = names[j];
3239 } else {
3240 p.info.authority = p.info.authority + ";" + names[j];
3241 }
3242 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3243 Log.d(TAG, "Registered content provider: " + names[j] +
3244 ", className = " + p.info.name +
3245 ", isSyncable = " + p.info.isSyncable);
3246 } else {
3247 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003248 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003249 " (in package " + pkg.applicationInfo.packageName +
3250 "): name already used by "
3251 + ((other != null && other.getComponentName() != null)
3252 ? other.getComponentName().getPackageName() : "?"));
3253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
3255 }
3256 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3257 if (r == null) {
3258 r = new StringBuilder(256);
3259 } else {
3260 r.append(' ');
3261 }
3262 r.append(p.info.name);
3263 }
3264 }
3265 if (r != null) {
3266 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 N = pkg.services.size();
3270 r = null;
3271 for (i=0; i<N; i++) {
3272 PackageParser.Service s = pkg.services.get(i);
3273 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3274 s.info.processName, pkg.applicationInfo.uid);
3275 mServices.addService(s);
3276 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3277 if (r == null) {
3278 r = new StringBuilder(256);
3279 } else {
3280 r.append(' ');
3281 }
3282 r.append(s.info.name);
3283 }
3284 }
3285 if (r != null) {
3286 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3287 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 N = pkg.receivers.size();
3290 r = null;
3291 for (i=0; i<N; i++) {
3292 PackageParser.Activity a = pkg.receivers.get(i);
3293 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3294 a.info.processName, pkg.applicationInfo.uid);
3295 mReceivers.addActivity(a, "receiver");
3296 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3297 if (r == null) {
3298 r = new StringBuilder(256);
3299 } else {
3300 r.append(' ');
3301 }
3302 r.append(a.info.name);
3303 }
3304 }
3305 if (r != null) {
3306 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 N = pkg.activities.size();
3310 r = null;
3311 for (i=0; i<N; i++) {
3312 PackageParser.Activity a = pkg.activities.get(i);
3313 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3314 a.info.processName, pkg.applicationInfo.uid);
3315 mActivities.addActivity(a, "activity");
3316 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3317 if (r == null) {
3318 r = new StringBuilder(256);
3319 } else {
3320 r.append(' ');
3321 }
3322 r.append(a.info.name);
3323 }
3324 }
3325 if (r != null) {
3326 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3327 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 N = pkg.permissionGroups.size();
3330 r = null;
3331 for (i=0; i<N; i++) {
3332 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3333 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3334 if (cur == null) {
3335 mPermissionGroups.put(pg.info.name, pg);
3336 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3337 if (r == null) {
3338 r = new StringBuilder(256);
3339 } else {
3340 r.append(' ');
3341 }
3342 r.append(pg.info.name);
3343 }
3344 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003345 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 + pg.info.packageName + " ignored: original from "
3347 + cur.info.packageName);
3348 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3349 if (r == null) {
3350 r = new StringBuilder(256);
3351 } else {
3352 r.append(' ');
3353 }
3354 r.append("DUP:");
3355 r.append(pg.info.name);
3356 }
3357 }
3358 }
3359 if (r != null) {
3360 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3361 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 N = pkg.permissions.size();
3364 r = null;
3365 for (i=0; i<N; i++) {
3366 PackageParser.Permission p = pkg.permissions.get(i);
3367 HashMap<String, BasePermission> permissionMap =
3368 p.tree ? mSettings.mPermissionTrees
3369 : mSettings.mPermissions;
3370 p.group = mPermissionGroups.get(p.info.group);
3371 if (p.info.group == null || p.group != null) {
3372 BasePermission bp = permissionMap.get(p.info.name);
3373 if (bp == null) {
3374 bp = new BasePermission(p.info.name, p.info.packageName,
3375 BasePermission.TYPE_NORMAL);
3376 permissionMap.put(p.info.name, bp);
3377 }
3378 if (bp.perm == null) {
3379 if (bp.sourcePackage == null
3380 || bp.sourcePackage.equals(p.info.packageName)) {
3381 BasePermission tree = findPermissionTreeLP(p.info.name);
3382 if (tree == null
3383 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003384 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 bp.perm = p;
3386 bp.uid = pkg.applicationInfo.uid;
3387 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3388 if (r == null) {
3389 r = new StringBuilder(256);
3390 } else {
3391 r.append(' ');
3392 }
3393 r.append(p.info.name);
3394 }
3395 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003396 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 + p.info.packageName + " ignored: base tree "
3398 + tree.name + " is from package "
3399 + tree.sourcePackage);
3400 }
3401 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003402 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 + p.info.packageName + " ignored: original from "
3404 + bp.sourcePackage);
3405 }
3406 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3407 if (r == null) {
3408 r = new StringBuilder(256);
3409 } else {
3410 r.append(' ');
3411 }
3412 r.append("DUP:");
3413 r.append(p.info.name);
3414 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003415 if (bp.perm == p) {
3416 bp.protectionLevel = p.info.protectionLevel;
3417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003419 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 + p.info.packageName + " ignored: no group "
3421 + p.group);
3422 }
3423 }
3424 if (r != null) {
3425 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 N = pkg.instrumentation.size();
3429 r = null;
3430 for (i=0; i<N; i++) {
3431 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3432 a.info.packageName = pkg.applicationInfo.packageName;
3433 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3434 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3435 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003436 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3438 if (r == null) {
3439 r = new StringBuilder(256);
3440 } else {
3441 r.append(' ');
3442 }
3443 r.append(a.info.name);
3444 }
3445 }
3446 if (r != null) {
3447 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3448 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003449
Dianne Hackborn854060af2009-07-09 18:14:31 -07003450 if (pkg.protectedBroadcasts != null) {
3451 N = pkg.protectedBroadcasts.size();
3452 for (i=0; i<N; i++) {
3453 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3454 }
3455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 pkgSetting.setTimeStamp(scanFileTime);
3458 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 return pkg;
3461 }
3462
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003463 private void killApplication(String pkgName, int uid) {
3464 // Request the ActivityManager to kill the process(only for existing packages)
3465 // so that we do not end up in a confused state while the user is still using the older
3466 // version of the application while the new one gets installed.
3467 IActivityManager am = ActivityManagerNative.getDefault();
3468 if (am != null) {
3469 try {
3470 am.killApplicationWithUid(pkgName, uid);
3471 } catch (RemoteException e) {
3472 }
3473 }
3474 }
3475
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003476 // The following constants are returned by cachePackageSharedLibsForAbiLI
3477 // to indicate if native shared libraries were found in the package.
3478 // Values are:
3479 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3480 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3481 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3482 // in package (and not installed)
3483 //
3484 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3485 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3486 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003488 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3489 // and automatically copy them to /data/data/<appname>/lib if present.
3490 //
3491 // NOTE: this method may throw an IOException if the library cannot
3492 // be copied to its final destination, e.g. if there isn't enough
3493 // room left on the data partition, or a ZipException if the package
3494 // file is malformed.
3495 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003496 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3497 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003498 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3499 final String apkLib = "lib/";
3500 final int apkLibLen = apkLib.length();
3501 final int cpuAbiLen = cpuAbi.length();
3502 final String libPrefix = "lib";
3503 final int libPrefixLen = libPrefix.length();
3504 final String libSuffix = ".so";
3505 final int libSuffixLen = libSuffix.length();
3506 boolean hasNativeLibraries = false;
3507 boolean installedNativeLibraries = false;
3508
3509 // the minimum length of a valid native shared library of the form
3510 // lib/<something>/lib<name>.so.
3511 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3512
3513 ZipFile zipFile = new ZipFile(scanFile);
3514 Enumeration<ZipEntry> entries =
3515 (Enumeration<ZipEntry>) zipFile.entries();
3516
3517 while (entries.hasMoreElements()) {
3518 ZipEntry entry = entries.nextElement();
3519 // skip directories
3520 if (entry.isDirectory()) {
3521 continue;
3522 }
3523 String entryName = entry.getName();
3524
3525 // check that the entry looks like lib/<something>/lib<name>.so
3526 // here, but don't check the ABI just yet.
3527 //
3528 // - must be sufficiently long
3529 // - must end with libSuffix, i.e. ".so"
3530 // - must start with apkLib, i.e. "lib/"
3531 if (entryName.length() < minEntryLen ||
3532 !entryName.endsWith(libSuffix) ||
3533 !entryName.startsWith(apkLib) ) {
3534 continue;
3535 }
3536
3537 // file name must start with libPrefix, i.e. "lib"
3538 int lastSlash = entryName.lastIndexOf('/');
3539
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003540 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003541 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3542 continue;
3543 }
3544
3545 hasNativeLibraries = true;
3546
3547 // check the cpuAbi now, between lib/ and /lib<name>.so
3548 //
3549 if (lastSlash != apkLibLen + cpuAbiLen ||
3550 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3551 continue;
3552
3553 // extract the library file name, ensure it doesn't contain
3554 // weird characters. we're guaranteed here that it doesn't contain
3555 // a directory separator though.
3556 String libFileName = entryName.substring(lastSlash+1);
3557 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3558 continue;
3559 }
3560
3561 installedNativeLibraries = true;
3562
3563 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3564 File.separator + libFileName;
3565 File sharedLibraryFile = new File(sharedLibraryFilePath);
3566 if (! sharedLibraryFile.exists() ||
3567 sharedLibraryFile.length() != entry.getSize() ||
3568 sharedLibraryFile.lastModified() != entry.getTime()) {
3569 if (Config.LOGD) {
3570 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003572 if (mInstaller == null) {
3573 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003574 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003575 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003576 sharedLibraryFile);
3577 }
3578 }
3579 if (!hasNativeLibraries)
3580 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3581
3582 if (!installedNativeLibraries)
3583 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3584
3585 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3586 }
3587
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003588 // Find the gdbserver executable program in a package at
3589 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3590 //
3591 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3592 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3593 //
3594 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3595 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3596 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3597 final String GDBSERVER = "gdbserver";
3598 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3599
3600 ZipFile zipFile = new ZipFile(scanFile);
3601 Enumeration<ZipEntry> entries =
3602 (Enumeration<ZipEntry>) zipFile.entries();
3603
3604 while (entries.hasMoreElements()) {
3605 ZipEntry entry = entries.nextElement();
3606 // skip directories
3607 if (entry.isDirectory()) {
3608 continue;
3609 }
3610 String entryName = entry.getName();
3611
3612 if (!entryName.equals(apkGdbServerPath)) {
3613 continue;
3614 }
3615
3616 String installGdbServerPath = installGdbServerDir.getPath() +
3617 "/" + GDBSERVER;
3618 File installGdbServerFile = new File(installGdbServerPath);
3619 if (! installGdbServerFile.exists() ||
3620 installGdbServerFile.length() != entry.getSize() ||
3621 installGdbServerFile.lastModified() != entry.getTime()) {
3622 if (Config.LOGD) {
3623 Log.d(TAG, "Caching gdbserver " + entry.getName());
3624 }
3625 if (mInstaller == null) {
3626 installGdbServerDir.mkdir();
3627 }
3628 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3629 installGdbServerFile);
3630 }
3631 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3632 }
3633 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3634 }
3635
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003636 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3637 // and copy them to /data/data/<appname>/lib.
3638 //
3639 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3640 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3641 // one if ro.product.cpu.abi2 is defined.
3642 //
3643 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3644 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003645 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003646 try {
3647 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3648
3649 // some architectures are capable of supporting several CPU ABIs
3650 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3651 // this is indicated by the definition of the ro.product.cpu.abi2
3652 // system property.
3653 //
3654 // only scan the package twice in case of ABI mismatch
3655 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003656 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003657 if (cpuAbi2 != null) {
3658 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003660
3661 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003662 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003663 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003665
3666 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3667 cpuAbi = cpuAbi2;
3668 }
3669 }
3670
3671 // for debuggable packages, also extract gdbserver from lib/<abi>
3672 // into /data/data/<appname>/lib too.
3673 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3674 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3675 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3676 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3677 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003680 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003681 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003682 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003684 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003685 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003687 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 }
3689
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003690 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003692 File binaryDir,
3693 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 InputStream inputStream = zipFile.getInputStream(entry);
3695 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003696 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003698 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 // now need to be left as world readable and owned by the system.
3700 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3701 ! tempFile.setLastModified(entry.getTime()) ||
3702 FileUtils.setPermissions(tempFilePath,
3703 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003704 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003706 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 // Failed to properly write file.
3708 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003709 throw new IOException("Couldn't create cached binary "
3710 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 }
3712 } finally {
3713 inputStream.close();
3714 }
3715 }
3716
3717 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3718 if (chatty && Config.LOGD) Log.d(
3719 TAG, "Removing package " + pkg.applicationInfo.packageName );
3720
3721 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 mPackages.remove(pkg.applicationInfo.packageName);
3725 if (pkg.mPath != null) {
3726 mAppDirs.remove(pkg.mPath);
3727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 PackageSetting ps = (PackageSetting)pkg.mExtras;
3730 if (ps != null && ps.sharedUser != null) {
3731 // XXX don't do this until the data is removed.
3732 if (false) {
3733 ps.sharedUser.packages.remove(ps);
3734 if (ps.sharedUser.packages.size() == 0) {
3735 // Remove.
3736 }
3737 }
3738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 int N = pkg.providers.size();
3741 StringBuilder r = null;
3742 int i;
3743 for (i=0; i<N; i++) {
3744 PackageParser.Provider p = pkg.providers.get(i);
3745 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3746 p.info.name));
3747 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 /* The is another ContentProvider with this authority when
3750 * this app was installed so this authority is null,
3751 * Ignore it as we don't have to unregister the provider.
3752 */
3753 continue;
3754 }
3755 String names[] = p.info.authority.split(";");
3756 for (int j = 0; j < names.length; j++) {
3757 if (mProviders.get(names[j]) == p) {
3758 mProviders.remove(names[j]);
3759 if (chatty && Config.LOGD) Log.d(
3760 TAG, "Unregistered content provider: " + names[j] +
3761 ", className = " + p.info.name +
3762 ", isSyncable = " + p.info.isSyncable);
3763 }
3764 }
3765 if (chatty) {
3766 if (r == null) {
3767 r = new StringBuilder(256);
3768 } else {
3769 r.append(' ');
3770 }
3771 r.append(p.info.name);
3772 }
3773 }
3774 if (r != null) {
3775 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 N = pkg.services.size();
3779 r = null;
3780 for (i=0; i<N; i++) {
3781 PackageParser.Service s = pkg.services.get(i);
3782 mServices.removeService(s);
3783 if (chatty) {
3784 if (r == null) {
3785 r = new StringBuilder(256);
3786 } else {
3787 r.append(' ');
3788 }
3789 r.append(s.info.name);
3790 }
3791 }
3792 if (r != null) {
3793 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3794 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 N = pkg.receivers.size();
3797 r = null;
3798 for (i=0; i<N; i++) {
3799 PackageParser.Activity a = pkg.receivers.get(i);
3800 mReceivers.removeActivity(a, "receiver");
3801 if (chatty) {
3802 if (r == null) {
3803 r = new StringBuilder(256);
3804 } else {
3805 r.append(' ');
3806 }
3807 r.append(a.info.name);
3808 }
3809 }
3810 if (r != null) {
3811 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3812 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 N = pkg.activities.size();
3815 r = null;
3816 for (i=0; i<N; i++) {
3817 PackageParser.Activity a = pkg.activities.get(i);
3818 mActivities.removeActivity(a, "activity");
3819 if (chatty) {
3820 if (r == null) {
3821 r = new StringBuilder(256);
3822 } else {
3823 r.append(' ');
3824 }
3825 r.append(a.info.name);
3826 }
3827 }
3828 if (r != null) {
3829 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 N = pkg.permissions.size();
3833 r = null;
3834 for (i=0; i<N; i++) {
3835 PackageParser.Permission p = pkg.permissions.get(i);
3836 boolean tree = false;
3837 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3838 if (bp == null) {
3839 tree = true;
3840 bp = mSettings.mPermissionTrees.get(p.info.name);
3841 }
3842 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003843 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 if (chatty) {
3845 if (r == null) {
3846 r = new StringBuilder(256);
3847 } else {
3848 r.append(' ');
3849 }
3850 r.append(p.info.name);
3851 }
3852 }
3853 }
3854 if (r != null) {
3855 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 N = pkg.instrumentation.size();
3859 r = null;
3860 for (i=0; i<N; i++) {
3861 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003862 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 if (chatty) {
3864 if (r == null) {
3865 r = new StringBuilder(256);
3866 } else {
3867 r.append(' ');
3868 }
3869 r.append(a.info.name);
3870 }
3871 }
3872 if (r != null) {
3873 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3874 }
3875 }
3876 }
3877
3878 private static final boolean isPackageFilename(String name) {
3879 return name != null && name.endsWith(".apk");
3880 }
3881
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003882 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3883 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3884 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3885 return true;
3886 }
3887 }
3888 return false;
3889 }
3890
3891 private void updatePermissionsLP(String changingPkg,
3892 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 // Make sure there are no dangling permission trees.
3894 Iterator<BasePermission> it = mSettings.mPermissionTrees
3895 .values().iterator();
3896 while (it.hasNext()) {
3897 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003898 if (bp.packageSetting == null) {
3899 // We may not yet have parsed the package, so just see if
3900 // we still know about its settings.
3901 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3902 }
3903 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003904 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 + " from package " + bp.sourcePackage);
3906 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003907 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3908 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3909 Slog.i(TAG, "Removing old permission tree: " + bp.name
3910 + " from package " + bp.sourcePackage);
3911 grantPermissions = true;
3912 it.remove();
3913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 }
3915 }
3916
3917 // Make sure all dynamic permissions have been assigned to a package,
3918 // and make sure there are no dangling permissions.
3919 it = mSettings.mPermissions.values().iterator();
3920 while (it.hasNext()) {
3921 BasePermission bp = it.next();
3922 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3923 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3924 + bp.name + " pkg=" + bp.sourcePackage
3925 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 BasePermission tree = findPermissionTreeLP(bp.name);
3928 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003929 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 bp.perm = new PackageParser.Permission(tree.perm.owner,
3931 new PermissionInfo(bp.pendingInfo));
3932 bp.perm.info.packageName = tree.perm.info.packageName;
3933 bp.perm.info.name = bp.name;
3934 bp.uid = tree.uid;
3935 }
3936 }
3937 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003938 if (bp.packageSetting == null) {
3939 // We may not yet have parsed the package, so just see if
3940 // we still know about its settings.
3941 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3942 }
3943 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003944 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 + " from package " + bp.sourcePackage);
3946 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003947 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3948 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3949 Slog.i(TAG, "Removing old permission: " + bp.name
3950 + " from package " + bp.sourcePackage);
3951 grantPermissions = true;
3952 it.remove();
3953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 }
3955 }
3956
3957 // Now update the permissions for all packages, in particular
3958 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003959 if (grantPermissions) {
3960 for (PackageParser.Package pkg : mPackages.values()) {
3961 if (pkg != pkgInfo) {
3962 grantPermissionsLP(pkg, false);
3963 }
3964 }
3965 }
3966
3967 if (pkgInfo != null) {
3968 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 }
3970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3973 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3974 if (ps == null) {
3975 return;
3976 }
3977 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003978 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 if (replace) {
3981 ps.permissionsFixed = false;
3982 if (gp == ps) {
3983 gp.grantedPermissions.clear();
3984 gp.gids = mGlobalGids;
3985 }
3986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 if (gp.gids == null) {
3989 gp.gids = mGlobalGids;
3990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 final int N = pkg.requestedPermissions.size();
3993 for (int i=0; i<N; i++) {
3994 String name = pkg.requestedPermissions.get(i);
3995 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 if (false) {
3997 if (gp != ps) {
3998 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003999 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
4001 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004002 if (bp != null && bp.packageSetting != null) {
4003 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004005 boolean allowedSig = false;
4006 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4007 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004009 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4010 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4011 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004013 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004015 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4017 // For updated system applications, the signatureOrSystem permission
4018 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004019 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4021 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4022 if(sysPs.grantedPermissions.contains(perm)) {
4023 allowed = true;
4024 } else {
4025 allowed = false;
4026 }
4027 } else {
4028 allowed = true;
4029 }
4030 }
4031 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004032 if (allowed) {
4033 allowedSig = true;
4034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 } else {
4036 allowed = false;
4037 }
4038 if (false) {
4039 if (gp != ps) {
4040 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4041 }
4042 }
4043 if (allowed) {
4044 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4045 && ps.permissionsFixed) {
4046 // If this is an existing, non-system package, then
4047 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004048 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004050 // Except... if this is a permission that was added
4051 // to the platform (note: need to only do this when
4052 // updating the platform).
4053 final int NP = PackageParser.NEW_PERMISSIONS.length;
4054 for (int ip=0; ip<NP; ip++) {
4055 final PackageParser.NewPermissionInfo npi
4056 = PackageParser.NEW_PERMISSIONS[ip];
4057 if (npi.name.equals(perm)
4058 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4059 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004060 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004061 + pkg.packageName);
4062 break;
4063 }
4064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 }
4066 }
4067 if (allowed) {
4068 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004069 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 gp.grantedPermissions.add(perm);
4071 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004072 } else if (!ps.haveGids) {
4073 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 }
4075 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004076 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 + " to package " + pkg.packageName
4078 + " because it was previously installed without");
4079 }
4080 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004081 if (gp.grantedPermissions.remove(perm)) {
4082 changedPermission = true;
4083 gp.gids = removeInts(gp.gids, bp.gids);
4084 Slog.i(TAG, "Un-granting permission " + perm
4085 + " from package " + pkg.packageName
4086 + " (protectionLevel=" + bp.protectionLevel
4087 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4088 + ")");
4089 } else {
4090 Slog.w(TAG, "Not granting permission " + perm
4091 + " to package " + pkg.packageName
4092 + " (protectionLevel=" + bp.protectionLevel
4093 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4094 + ")");
4095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 }
4097 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004098 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 + " in package " + pkg.packageName);
4100 }
4101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004102
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004103 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004104 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4105 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 // This is the first that we have heard about this package, so the
4107 // permissions we have now selected are fixed until explicitly
4108 // changed.
4109 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004111 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 private final class ActivityIntentResolver
4115 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004116 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004118 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 }
4120
Mihai Preda074edef2009-05-18 17:13:31 +02004121 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004123 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4125 }
4126
Mihai Predaeae850c2009-05-13 10:13:48 +02004127 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4128 ArrayList<PackageParser.Activity> packageActivities) {
4129 if (packageActivities == null) {
4130 return null;
4131 }
4132 mFlags = flags;
4133 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4134 int N = packageActivities.size();
4135 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4136 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004137
4138 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004139 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004140 intentFilters = packageActivities.get(i).intents;
4141 if (intentFilters != null && intentFilters.size() > 0) {
4142 listCut.add(intentFilters);
4143 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004144 }
4145 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4146 }
4147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004149 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 if (SHOW_INFO || Config.LOGV) Log.v(
4151 TAG, " " + type + " " +
4152 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4153 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4154 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004155 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4157 if (SHOW_INFO || Config.LOGV) {
4158 Log.v(TAG, " IntentFilter:");
4159 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4160 }
4161 if (!intent.debugCheck()) {
4162 Log.w(TAG, "==> For Activity " + a.info.name);
4163 }
4164 addFilter(intent);
4165 }
4166 }
4167
4168 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004169 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 if (SHOW_INFO || Config.LOGV) Log.v(
4171 TAG, " " + type + " " +
4172 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4173 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4174 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004175 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4177 if (SHOW_INFO || Config.LOGV) {
4178 Log.v(TAG, " IntentFilter:");
4179 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4180 }
4181 removeFilter(intent);
4182 }
4183 }
4184
4185 @Override
4186 protected boolean allowFilterResult(
4187 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4188 ActivityInfo filterAi = filter.activity.info;
4189 for (int i=dest.size()-1; i>=0; i--) {
4190 ActivityInfo destAi = dest.get(i).activityInfo;
4191 if (destAi.name == filterAi.name
4192 && destAi.packageName == filterAi.packageName) {
4193 return false;
4194 }
4195 }
4196 return true;
4197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004200 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4201 return info.activity.owner.packageName;
4202 }
4203
4204 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4206 int match) {
4207 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4208 return null;
4209 }
4210 final PackageParser.Activity activity = info.activity;
4211 if (mSafeMode && (activity.info.applicationInfo.flags
4212 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4213 return null;
4214 }
4215 final ResolveInfo res = new ResolveInfo();
4216 res.activityInfo = PackageParser.generateActivityInfo(activity,
4217 mFlags);
4218 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4219 res.filter = info;
4220 }
4221 res.priority = info.getPriority();
4222 res.preferredOrder = activity.owner.mPreferredOrder;
4223 //System.out.println("Result: " + res.activityInfo.className +
4224 // " = " + res.priority);
4225 res.match = match;
4226 res.isDefault = info.hasDefault;
4227 res.labelRes = info.labelRes;
4228 res.nonLocalizedLabel = info.nonLocalizedLabel;
4229 res.icon = info.icon;
4230 return res;
4231 }
4232
4233 @Override
4234 protected void sortResults(List<ResolveInfo> results) {
4235 Collections.sort(results, mResolvePrioritySorter);
4236 }
4237
4238 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004239 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004241 out.print(prefix); out.print(
4242 Integer.toHexString(System.identityHashCode(filter.activity)));
4243 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004244 out.print(filter.activity.getComponentShortName());
4245 out.print(" filter ");
4246 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 }
4248
4249// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4250// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4251// final List<ResolveInfo> retList = Lists.newArrayList();
4252// while (i.hasNext()) {
4253// final ResolveInfo resolveInfo = i.next();
4254// if (isEnabledLP(resolveInfo.activityInfo)) {
4255// retList.add(resolveInfo);
4256// }
4257// }
4258// return retList;
4259// }
4260
4261 // Keys are String (activity class name), values are Activity.
4262 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4263 = new HashMap<ComponentName, PackageParser.Activity>();
4264 private int mFlags;
4265 }
4266
4267 private final class ServiceIntentResolver
4268 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004269 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004271 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 }
4273
Mihai Preda074edef2009-05-18 17:13:31 +02004274 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004276 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004277 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4278 }
4279
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004280 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4281 ArrayList<PackageParser.Service> packageServices) {
4282 if (packageServices == null) {
4283 return null;
4284 }
4285 mFlags = flags;
4286 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4287 int N = packageServices.size();
4288 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4289 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4290
4291 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4292 for (int i = 0; i < N; ++i) {
4293 intentFilters = packageServices.get(i).intents;
4294 if (intentFilters != null && intentFilters.size() > 0) {
4295 listCut.add(intentFilters);
4296 }
4297 }
4298 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4299 }
4300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004302 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 if (SHOW_INFO || Config.LOGV) Log.v(
4304 TAG, " " + (s.info.nonLocalizedLabel != null
4305 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4306 if (SHOW_INFO || Config.LOGV) Log.v(
4307 TAG, " Class=" + s.info.name);
4308 int NI = s.intents.size();
4309 int j;
4310 for (j=0; j<NI; j++) {
4311 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4312 if (SHOW_INFO || Config.LOGV) {
4313 Log.v(TAG, " IntentFilter:");
4314 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4315 }
4316 if (!intent.debugCheck()) {
4317 Log.w(TAG, "==> For Service " + s.info.name);
4318 }
4319 addFilter(intent);
4320 }
4321 }
4322
4323 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004324 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 if (SHOW_INFO || Config.LOGV) Log.v(
4326 TAG, " " + (s.info.nonLocalizedLabel != null
4327 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4328 if (SHOW_INFO || Config.LOGV) Log.v(
4329 TAG, " Class=" + s.info.name);
4330 int NI = s.intents.size();
4331 int j;
4332 for (j=0; j<NI; j++) {
4333 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4334 if (SHOW_INFO || Config.LOGV) {
4335 Log.v(TAG, " IntentFilter:");
4336 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4337 }
4338 removeFilter(intent);
4339 }
4340 }
4341
4342 @Override
4343 protected boolean allowFilterResult(
4344 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4345 ServiceInfo filterSi = filter.service.info;
4346 for (int i=dest.size()-1; i>=0; i--) {
4347 ServiceInfo destAi = dest.get(i).serviceInfo;
4348 if (destAi.name == filterSi.name
4349 && destAi.packageName == filterSi.packageName) {
4350 return false;
4351 }
4352 }
4353 return true;
4354 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004357 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4358 return info.service.owner.packageName;
4359 }
4360
4361 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4363 int match) {
4364 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4365 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4366 return null;
4367 }
4368 final PackageParser.Service service = info.service;
4369 if (mSafeMode && (service.info.applicationInfo.flags
4370 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4371 return null;
4372 }
4373 final ResolveInfo res = new ResolveInfo();
4374 res.serviceInfo = PackageParser.generateServiceInfo(service,
4375 mFlags);
4376 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4377 res.filter = filter;
4378 }
4379 res.priority = info.getPriority();
4380 res.preferredOrder = service.owner.mPreferredOrder;
4381 //System.out.println("Result: " + res.activityInfo.className +
4382 // " = " + res.priority);
4383 res.match = match;
4384 res.isDefault = info.hasDefault;
4385 res.labelRes = info.labelRes;
4386 res.nonLocalizedLabel = info.nonLocalizedLabel;
4387 res.icon = info.icon;
4388 return res;
4389 }
4390
4391 @Override
4392 protected void sortResults(List<ResolveInfo> results) {
4393 Collections.sort(results, mResolvePrioritySorter);
4394 }
4395
4396 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004397 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004399 out.print(prefix); out.print(
4400 Integer.toHexString(System.identityHashCode(filter.service)));
4401 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004402 out.print(filter.service.getComponentShortName());
4403 out.print(" filter ");
4404 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 }
4406
4407// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4408// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4409// final List<ResolveInfo> retList = Lists.newArrayList();
4410// while (i.hasNext()) {
4411// final ResolveInfo resolveInfo = (ResolveInfo) i;
4412// if (isEnabledLP(resolveInfo.serviceInfo)) {
4413// retList.add(resolveInfo);
4414// }
4415// }
4416// return retList;
4417// }
4418
4419 // Keys are String (activity class name), values are Activity.
4420 private final HashMap<ComponentName, PackageParser.Service> mServices
4421 = new HashMap<ComponentName, PackageParser.Service>();
4422 private int mFlags;
4423 };
4424
4425 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4426 new Comparator<ResolveInfo>() {
4427 public int compare(ResolveInfo r1, ResolveInfo r2) {
4428 int v1 = r1.priority;
4429 int v2 = r2.priority;
4430 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4431 if (v1 != v2) {
4432 return (v1 > v2) ? -1 : 1;
4433 }
4434 v1 = r1.preferredOrder;
4435 v2 = r2.preferredOrder;
4436 if (v1 != v2) {
4437 return (v1 > v2) ? -1 : 1;
4438 }
4439 if (r1.isDefault != r2.isDefault) {
4440 return r1.isDefault ? -1 : 1;
4441 }
4442 v1 = r1.match;
4443 v2 = r2.match;
4444 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4445 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4446 }
4447 };
4448
4449 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4450 new Comparator<ProviderInfo>() {
4451 public int compare(ProviderInfo p1, ProviderInfo p2) {
4452 final int v1 = p1.initOrder;
4453 final int v2 = p2.initOrder;
4454 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4455 }
4456 };
4457
4458 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4459 IActivityManager am = ActivityManagerNative.getDefault();
4460 if (am != null) {
4461 try {
4462 final Intent intent = new Intent(action,
4463 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4464 if (extras != null) {
4465 intent.putExtras(extras);
4466 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004467 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 am.broadcastIntent(
4469 null, intent,
4470 null, null, 0, null, null, null, false, false);
4471 } catch (RemoteException ex) {
4472 }
4473 }
4474 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004475
4476 public String nextPackageToClean(String lastPackage) {
4477 synchronized (mPackages) {
4478 if (!mMediaMounted) {
4479 // If the external storage is no longer mounted at this point,
4480 // the caller may not have been able to delete all of this
4481 // packages files and can not delete any more. Bail.
4482 return null;
4483 }
4484 if (lastPackage != null) {
4485 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4486 }
4487 return mSettings.mPackagesToBeCleaned.size() > 0
4488 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4489 }
4490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004492 void schedulePackageCleaning(String packageName) {
4493 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4494 }
4495
4496 void startCleaningPackages() {
4497 synchronized (mPackages) {
4498 if (!mMediaMounted) {
4499 return;
4500 }
4501 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4502 return;
4503 }
4504 }
4505 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4506 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4507 IActivityManager am = ActivityManagerNative.getDefault();
4508 if (am != null) {
4509 try {
4510 am.startService(null, intent, null);
4511 } catch (RemoteException e) {
4512 }
4513 }
4514 }
4515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 private final class AppDirObserver extends FileObserver {
4517 public AppDirObserver(String path, int mask, boolean isrom) {
4518 super(path, mask);
4519 mRootDir = path;
4520 mIsRom = isrom;
4521 }
4522
4523 public void onEvent(int event, String path) {
4524 String removedPackage = null;
4525 int removedUid = -1;
4526 String addedPackage = null;
4527 int addedUid = -1;
4528
4529 synchronized (mInstallLock) {
4530 String fullPathStr = null;
4531 File fullPath = null;
4532 if (path != null) {
4533 fullPath = new File(mRootDir, path);
4534 fullPathStr = fullPath.getPath();
4535 }
4536
4537 if (Config.LOGV) Log.v(
4538 TAG, "File " + fullPathStr + " changed: "
4539 + Integer.toHexString(event));
4540
4541 if (!isPackageFilename(path)) {
4542 if (Config.LOGV) Log.v(
4543 TAG, "Ignoring change of non-package file: " + fullPathStr);
4544 return;
4545 }
4546
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004547 // Ignore packages that are being installed or
4548 // have just been installed.
4549 if (ignoreCodePath(fullPathStr)) {
4550 return;
4551 }
4552 PackageParser.Package p = null;
4553 synchronized (mPackages) {
4554 p = mAppDirs.get(fullPathStr);
4555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004557 if (p != null) {
4558 removePackageLI(p, true);
4559 removedPackage = p.applicationInfo.packageName;
4560 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
4562 }
4563
4564 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004566 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004567 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4568 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 PackageParser.PARSE_CHATTY |
4570 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004571 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 if (p != null) {
4573 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004574 updatePermissionsLP(p.packageName, p,
4575 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 }
4577 addedPackage = p.applicationInfo.packageName;
4578 addedUid = p.applicationInfo.uid;
4579 }
4580 }
4581 }
4582
4583 synchronized (mPackages) {
4584 mSettings.writeLP();
4585 }
4586 }
4587
4588 if (removedPackage != null) {
4589 Bundle extras = new Bundle(1);
4590 extras.putInt(Intent.EXTRA_UID, removedUid);
4591 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4592 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4593 }
4594 if (addedPackage != null) {
4595 Bundle extras = new Bundle(1);
4596 extras.putInt(Intent.EXTRA_UID, addedUid);
4597 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4598 }
4599 }
4600
4601 private final String mRootDir;
4602 private final boolean mIsRom;
4603 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004605 /* Called when a downloaded package installation has been confirmed by the user */
4606 public void installPackage(
4607 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004608 installPackage(packageURI, observer, flags, null);
4609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004610
Jacek Surazski65e13172009-04-28 15:26:38 +02004611 /* Called when a downloaded package installation has been confirmed by the user */
4612 public void installPackage(
4613 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4614 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 mContext.enforceCallingOrSelfPermission(
4616 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004617
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004618 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004619 msg.obj = new InstallParams(packageURI, observer, flags,
4620 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004621 mHandler.sendMessage(msg);
4622 }
4623
Christopher Tate1bb69062010-02-19 17:02:12 -08004624 public void finishPackageInstall(int token) {
4625 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4626 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4627 mHandler.sendMessage(msg);
4628 }
4629
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004630 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 // Queue up an async operation since the package installation may take a little while.
4632 mHandler.post(new Runnable() {
4633 public void run() {
4634 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004635 // Result object to be returned
4636 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004637 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004638 res.uid = -1;
4639 res.pkg = null;
4640 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004641 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004642 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004643 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004644 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004645 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004646 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004648
4649 // A restore should be performed at this point if (a) the install
4650 // succeeded, (b) the operation is not an update, and (c) the new
4651 // package has a backupAgent defined.
4652 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004653 boolean doRestore = (!update
4654 && res.pkg != null
4655 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004656
4657 // Set up the post-install work request bookkeeping. This will be used
4658 // and cleaned up by the post-install event handling regardless of whether
4659 // there's a restore pass performed. Token values are >= 1.
4660 int token;
4661 if (mNextInstallToken < 0) mNextInstallToken = 1;
4662 token = mNextInstallToken++;
4663
4664 PostInstallData data = new PostInstallData(args, res);
4665 mRunningInstalls.put(token, data);
4666 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4667
4668 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4669 // Pass responsibility to the Backup Manager. It will perform a
4670 // restore if appropriate, then pass responsibility back to the
4671 // Package Manager to run the post-install observer callbacks
4672 // and broadcasts.
4673 IBackupManager bm = IBackupManager.Stub.asInterface(
4674 ServiceManager.getService(Context.BACKUP_SERVICE));
4675 if (bm != null) {
4676 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4677 + " to BM for possible restore");
4678 try {
4679 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4680 } catch (RemoteException e) {
4681 // can't happen; the backup manager is local
4682 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004683 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004684 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004685 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004686 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004687 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004688 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004691
4692 if (!doRestore) {
4693 // No restore possible, or the Backup Manager was mysteriously not
4694 // available -- just fire the post-install work request directly.
4695 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4696 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4697 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 }
4700 });
4701 }
4702
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004703 abstract class HandlerParams {
4704 final static int MAX_RETRIES = 4;
4705 int retry = 0;
4706 final void startCopy() {
4707 try {
4708 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4709 retry++;
4710 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004711 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004712 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4713 handleServiceError();
4714 return;
4715 } else {
4716 handleStartCopy();
4717 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4718 mHandler.sendEmptyMessage(MCS_UNBIND);
4719 }
4720 } catch (RemoteException e) {
4721 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4722 mHandler.sendEmptyMessage(MCS_RECONNECT);
4723 }
4724 handleReturnCode();
4725 }
4726
4727 final void serviceError() {
4728 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4729 handleServiceError();
4730 handleReturnCode();
4731 }
4732 abstract void handleStartCopy() throws RemoteException;
4733 abstract void handleServiceError();
4734 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004735 }
4736
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004737 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004738 final IPackageInstallObserver observer;
4739 int flags;
4740 final Uri packageURI;
4741 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004742 private InstallArgs mArgs;
4743 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004744 InstallParams(Uri packageURI,
4745 IPackageInstallObserver observer, int flags,
4746 String installerPackageName) {
4747 this.packageURI = packageURI;
4748 this.flags = flags;
4749 this.observer = observer;
4750 this.installerPackageName = installerPackageName;
4751 }
4752
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004753 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4754 String packageName = pkgLite.packageName;
4755 int installLocation = pkgLite.installLocation;
4756 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4757 synchronized (mPackages) {
4758 PackageParser.Package pkg = mPackages.get(packageName);
4759 if (pkg != null) {
4760 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4761 // Check for updated system application.
4762 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4763 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004764 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004765 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4766 }
4767 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4768 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004769 if (onSd) {
4770 // Install flag overrides everything.
4771 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4772 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004773 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004774 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4775 // Application explicitly specified internal.
4776 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4777 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4778 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004779 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004780 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004781 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4782 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4783 }
4784 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004785 }
4786 }
4787 } else {
4788 // Invalid install. Return error code
4789 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4790 }
4791 }
4792 }
4793 // All the special cases have been taken care of.
4794 // Return result based on recommended install location.
4795 if (onSd) {
4796 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4797 }
4798 return pkgLite.recommendedInstallLocation;
4799 }
4800
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004801 /*
4802 * Invoke remote method to get package information and install
4803 * location values. Override install location based on default
4804 * policy if needed and then create install arguments based
4805 * on the install location.
4806 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004807 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004808 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004809 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4810 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004811 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4812 if (onInt && onSd) {
4813 // Check if both bits are set.
4814 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4815 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4816 } else if (fwdLocked && onSd) {
4817 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004818 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004819 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004820 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004821 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004822 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004823 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004824 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4825 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4826 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4827 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4828 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004829 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4830 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4831 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004832 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4833 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004834 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004835 // Override with defaults if needed.
4836 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004837 if (!onSd && !onInt) {
4838 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004839 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4840 // Set the flag to install on external media.
4841 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004842 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004843 } else {
4844 // Make sure the flag for installing on external
4845 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004846 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004847 flags &= ~PackageManager.INSTALL_EXTERNAL;
4848 }
4849 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004850 }
4851 }
4852 // Create the file args now.
4853 mArgs = createInstallArgs(this);
4854 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4855 // Create copy only if we are not in an erroneous state.
4856 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004857 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 }
4859 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004860 }
4861
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004862 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 void handleReturnCode() {
4864 processPendingInstall(mArgs, mRet);
4865 }
4866
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004867 @Override
4868 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004869 mArgs = createInstallArgs(this);
4870 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004872 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004873
4874 /*
4875 * Utility class used in movePackage api.
4876 * srcArgs and targetArgs are not set for invalid flags and make
4877 * sure to do null checks when invoking methods on them.
4878 * We probably want to return ErrorPrams for both failed installs
4879 * and moves.
4880 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004881 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 final IPackageMoveObserver observer;
4883 final int flags;
4884 final String packageName;
4885 final InstallArgs srcArgs;
4886 final InstallArgs targetArgs;
4887 int mRet;
4888 MoveParams(InstallArgs srcArgs,
4889 IPackageMoveObserver observer,
4890 int flags, String packageName) {
4891 this.srcArgs = srcArgs;
4892 this.observer = observer;
4893 this.flags = flags;
4894 this.packageName = packageName;
4895 if (srcArgs != null) {
4896 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4897 targetArgs = createInstallArgs(packageUri, flags, packageName);
4898 } else {
4899 targetArgs = null;
4900 }
4901 }
4902
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004903 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004904 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4905 // Check for storage space on target medium
4906 if (!targetArgs.checkFreeStorage(mContainerService)) {
4907 Log.w(TAG, "Insufficient storage to install");
4908 return;
4909 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004910 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004911 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004912 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004913 if (DEBUG_SD_INSTALL) {
4914 StringBuilder builder = new StringBuilder();
4915 if (srcArgs != null) {
4916 builder.append("src: ");
4917 builder.append(srcArgs.getCodePath());
4918 }
4919 if (targetArgs != null) {
4920 builder.append(" target : ");
4921 builder.append(targetArgs.getCodePath());
4922 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004923 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004924 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004925 }
4926
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004927 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004928 void handleReturnCode() {
4929 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004930 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4931 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4932 currentStatus = PackageManager.MOVE_SUCCEEDED;
4933 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4934 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4935 }
4936 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004937 }
4938
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004939 @Override
4940 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004941 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004942 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004943 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004944
4945 private InstallArgs createInstallArgs(InstallParams params) {
4946 if (installOnSd(params.flags)) {
4947 return new SdInstallArgs(params);
4948 } else {
4949 return new FileInstallArgs(params);
4950 }
4951 }
4952
4953 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4954 if (installOnSd(flags)) {
4955 return new SdInstallArgs(fullCodePath, fullResourcePath);
4956 } else {
4957 return new FileInstallArgs(fullCodePath, fullResourcePath);
4958 }
4959 }
4960
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4962 if (installOnSd(flags)) {
4963 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4964 return new SdInstallArgs(packageURI, cid);
4965 } else {
4966 return new FileInstallArgs(packageURI, pkgName);
4967 }
4968 }
4969
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 static abstract class InstallArgs {
4971 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004973 final int flags;
4974 final Uri packageURI;
4975 final String installerPackageName;
4976
4977 InstallArgs(Uri packageURI,
4978 IPackageInstallObserver observer, int flags,
4979 String installerPackageName) {
4980 this.packageURI = packageURI;
4981 this.flags = flags;
4982 this.observer = observer;
4983 this.installerPackageName = installerPackageName;
4984 }
4985
4986 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004987 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004988 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004990 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 abstract String getCodePath();
4992 abstract String getResourcePath();
4993 // Need installer lock especially for dex file removal.
4994 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004995 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004996 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 }
4998
4999 class FileInstallArgs extends InstallArgs {
5000 File installDir;
5001 String codeFileName;
5002 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005003 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005004
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005005 FileInstallArgs(InstallParams params) {
5006 super(params.packageURI, params.observer,
5007 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005008 }
5009
5010 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5011 super(null, null, 0, null);
5012 File codeFile = new File(fullCodePath);
5013 installDir = codeFile.getParentFile();
5014 codeFileName = fullCodePath;
5015 resourceFileName = fullResourcePath;
5016 }
5017
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 FileInstallArgs(Uri packageURI, String pkgName) {
5019 super(packageURI, null, 0, null);
5020 boolean fwdLocked = isFwdLocked(flags);
5021 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5022 String apkName = getNextCodePath(null, pkgName, ".apk");
5023 codeFileName = new File(installDir, apkName + ".apk").getPath();
5024 resourceFileName = getResourcePathFromCodePath();
5025 }
5026
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005027 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5028 return imcs.checkFreeStorage(false, packageURI);
5029 }
5030
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005031 String getCodePath() {
5032 return codeFileName;
5033 }
5034
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005035 void createCopyFile() {
5036 boolean fwdLocked = isFwdLocked(flags);
5037 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5038 codeFileName = createTempPackageFile(installDir).getPath();
5039 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005041 }
5042
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005043 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005044 if (temp) {
5045 // Generate temp file name
5046 createCopyFile();
5047 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005048 // Get a ParcelFileDescriptor to write to the output file
5049 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005050 if (!created) {
5051 try {
5052 codeFile.createNewFile();
5053 // Set permissions
5054 if (!setPermissions()) {
5055 // Failed setting permissions.
5056 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5057 }
5058 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005059 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005060 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5061 }
5062 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 ParcelFileDescriptor out = null;
5064 try {
5065 out = ParcelFileDescriptor.open(codeFile,
5066 ParcelFileDescriptor.MODE_READ_WRITE);
5067 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005068 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005069 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5070 }
5071 // Copy the resource now
5072 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5073 try {
5074 if (imcs.copyResource(packageURI, out)) {
5075 ret = PackageManager.INSTALL_SUCCEEDED;
5076 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005077 } finally {
5078 try { if (out != null) out.close(); } catch (IOException e) {}
5079 }
5080 return ret;
5081 }
5082
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005083 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005084 if (status != PackageManager.INSTALL_SUCCEEDED) {
5085 cleanUp();
5086 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005087 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 }
5089
5090 boolean doRename(int status, final String pkgName, String oldCodePath) {
5091 if (status != PackageManager.INSTALL_SUCCEEDED) {
5092 cleanUp();
5093 return false;
5094 } else {
5095 // Rename based on packageName
5096 File codeFile = new File(getCodePath());
5097 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5098 File desFile = new File(installDir, apkName + ".apk");
5099 if (!codeFile.renameTo(desFile)) {
5100 return false;
5101 }
5102 // Reset paths since the file has been renamed.
5103 codeFileName = desFile.getPath();
5104 resourceFileName = getResourcePathFromCodePath();
5105 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005106 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 // Failed setting permissions.
5108 return false;
5109 }
5110 return true;
5111 }
5112 }
5113
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005114 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005115 if (status != PackageManager.INSTALL_SUCCEEDED) {
5116 cleanUp();
5117 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005118 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005119 }
5120
5121 String getResourcePath() {
5122 return resourceFileName;
5123 }
5124
5125 String getResourcePathFromCodePath() {
5126 String codePath = getCodePath();
5127 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5128 String apkNameOnly = getApkName(codePath);
5129 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5130 } else {
5131 return codePath;
5132 }
5133 }
5134
5135 private boolean cleanUp() {
5136 boolean ret = true;
5137 String sourceDir = getCodePath();
5138 String publicSourceDir = getResourcePath();
5139 if (sourceDir != null) {
5140 File sourceFile = new File(sourceDir);
5141 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005142 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005143 ret = false;
5144 }
5145 // Delete application's code and resources
5146 sourceFile.delete();
5147 }
5148 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5149 final File publicSourceFile = new File(publicSourceDir);
5150 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005151 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005152 }
5153 if (publicSourceFile.exists()) {
5154 publicSourceFile.delete();
5155 }
5156 }
5157 return ret;
5158 }
5159
5160 void cleanUpResourcesLI() {
5161 String sourceDir = getCodePath();
5162 if (cleanUp() && mInstaller != null) {
5163 int retCode = mInstaller.rmdex(sourceDir);
5164 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005165 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005166 + " at location "
5167 + sourceDir + ", retcode=" + retCode);
5168 // we don't consider this to be a failure of the core package deletion
5169 }
5170 }
5171 }
5172
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005173 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005174 // TODO Do this in a more elegant way later on. for now just a hack
5175 if (!isFwdLocked(flags)) {
5176 final int filePermissions =
5177 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5178 |FileUtils.S_IROTH;
5179 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5180 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005181 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005182 getCodePath()
5183 + ". The return code was: " + retCode);
5184 // TODO Define new internal error
5185 return false;
5186 }
5187 return true;
5188 }
5189 return true;
5190 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005191
5192 boolean doPostDeleteLI(boolean delete) {
5193 cleanUpResourcesLI();
5194 return true;
5195 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005196 }
5197
5198 class SdInstallArgs extends InstallArgs {
5199 String cid;
5200 String cachePath;
5201 static final String RES_FILE_NAME = "pkg.apk";
5202
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005203 SdInstallArgs(InstallParams params) {
5204 super(params.packageURI, params.observer,
5205 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 }
5207
5208 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005209 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 // Extract cid from fullCodePath
5211 int eidx = fullCodePath.lastIndexOf("/");
5212 String subStr1 = fullCodePath.substring(0, eidx);
5213 int sidx = subStr1.lastIndexOf("/");
5214 cid = subStr1.substring(sidx+1, eidx);
5215 cachePath = subStr1;
5216 }
5217
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005218 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005219 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5220 this.cid = cid;
5221 }
5222
5223 SdInstallArgs(Uri packageURI, String cid) {
5224 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005225 this.cid = cid;
5226 }
5227
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005228 void createCopyFile() {
5229 cid = getTempContainerId();
5230 }
5231
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005232 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5233 return imcs.checkFreeStorage(true, packageURI);
5234 }
5235
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005236 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005237 if (temp) {
5238 createCopyFile();
5239 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005240 cachePath = imcs.copyResourceToContainer(
5241 packageURI, cid,
5242 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005243 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5244 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005245 }
5246
5247 @Override
5248 String getCodePath() {
5249 return cachePath + "/" + RES_FILE_NAME;
5250 }
5251
5252 @Override
5253 String getResourcePath() {
5254 return cachePath + "/" + RES_FILE_NAME;
5255 }
5256
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005257 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005258 if (status != PackageManager.INSTALL_SUCCEEDED) {
5259 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005260 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005261 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005262 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005263 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005264 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005265 if (cachePath == null) {
5266 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5267 }
5268 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005269 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005270 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005271 }
5272
5273 boolean doRename(int status, final String pkgName,
5274 String oldCodePath) {
5275 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005276 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005277 if (PackageHelper.isContainerMounted(cid)) {
5278 // Unmount the container
5279 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005280 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005281 return false;
5282 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005283 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005284 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005285 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5286 " which might be stale. Will try to clean up.");
5287 // Clean up the stale container and proceed to recreate.
5288 if (!PackageHelper.destroySdDir(newCacheId)) {
5289 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5290 return false;
5291 }
5292 // Successfully cleaned up stale container. Try to rename again.
5293 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5294 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5295 + " inspite of cleaning it up.");
5296 return false;
5297 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005298 }
5299 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005300 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005301 newCachePath = PackageHelper.mountSdDir(newCacheId,
5302 getEncryptKey(), Process.SYSTEM_UID);
5303 } else {
5304 newCachePath = PackageHelper.getSdDir(newCacheId);
5305 }
5306 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005307 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005308 return false;
5309 }
5310 Log.i(TAG, "Succesfully renamed " + cid +
5311 " at path: " + cachePath + " to " + newCacheId +
5312 " at new path: " + newCachePath);
5313 cid = newCacheId;
5314 cachePath = newCachePath;
5315 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005316 }
5317
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005318 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005319 if (status != PackageManager.INSTALL_SUCCEEDED) {
5320 cleanUp();
5321 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005322 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005323 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005324 PackageHelper.mountSdDir(cid,
5325 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005326 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005328 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005329 }
5330
5331 private void cleanUp() {
5332 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005333 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005334 }
5335
5336 void cleanUpResourcesLI() {
5337 String sourceFile = getCodePath();
5338 // Remove dex file
5339 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005340 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005342 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 + " at location "
5344 + sourceFile.toString() + ", retcode=" + retCode);
5345 // we don't consider this to be a failure of the core package deletion
5346 }
5347 }
5348 cleanUp();
5349 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005350
5351 boolean matchContainer(String app) {
5352 if (cid.startsWith(app)) {
5353 return true;
5354 }
5355 return false;
5356 }
5357
5358 String getPackageName() {
5359 int idx = cid.lastIndexOf("-");
5360 if (idx == -1) {
5361 return cid;
5362 }
5363 return cid.substring(0, idx);
5364 }
5365
5366 boolean doPostDeleteLI(boolean delete) {
5367 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005368 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005369 if (mounted) {
5370 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005371 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 }
5373 if (ret && delete) {
5374 cleanUpResourcesLI();
5375 }
5376 return ret;
5377 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005378 };
5379
5380 // Utility method used to create code paths based on package name and available index.
5381 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5382 String idxStr = "";
5383 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005384 // Fall back to default value of idx=1 if prefix is not
5385 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005387 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005388 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005389 if (subStr.endsWith(suffix)) {
5390 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005391 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005392 // If oldCodePath already contains prefix find out the
5393 // ending index to either increment or decrement.
5394 int sidx = subStr.lastIndexOf(prefix);
5395 if (sidx != -1) {
5396 subStr = subStr.substring(sidx + prefix.length());
5397 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005398 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5399 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005400 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005401 try {
5402 idx = Integer.parseInt(subStr);
5403 if (idx <= 1) {
5404 idx++;
5405 } else {
5406 idx--;
5407 }
5408 } catch(NumberFormatException e) {
5409 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005410 }
5411 }
5412 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005413 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005414 return prefix + idxStr;
5415 }
5416
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005417 // Utility method used to ignore ADD/REMOVE events
5418 // by directory observer.
5419 private static boolean ignoreCodePath(String fullPathStr) {
5420 String apkName = getApkName(fullPathStr);
5421 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5422 if (idx != -1 && ((idx+1) < apkName.length())) {
5423 // Make sure the package ends with a numeral
5424 String version = apkName.substring(idx+1);
5425 try {
5426 Integer.parseInt(version);
5427 return true;
5428 } catch (NumberFormatException e) {}
5429 }
5430 return false;
5431 }
5432
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005433 // Utility method that returns the relative package path with respect
5434 // to the installation directory. Like say for /data/data/com.test-1.apk
5435 // string com.test-1 is returned.
5436 static String getApkName(String codePath) {
5437 if (codePath == null) {
5438 return null;
5439 }
5440 int sidx = codePath.lastIndexOf("/");
5441 int eidx = codePath.lastIndexOf(".");
5442 if (eidx == -1) {
5443 eidx = codePath.length();
5444 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005445 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005446 return null;
5447 }
5448 return codePath.substring(sidx+1, eidx);
5449 }
5450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005451 class PackageInstalledInfo {
5452 String name;
5453 int uid;
5454 PackageParser.Package pkg;
5455 int returnCode;
5456 PackageRemovedInfo removedInfo;
5457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 /*
5460 * Install a non-existing package.
5461 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005462 private void installNewPackageLI(PackageParser.Package pkg,
5463 int parseFlags,
5464 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005465 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005467 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005468
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005469 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 res.name = pkgName;
5471 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005472 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5473 // A package with the same name is already installed, though
5474 // it has been renamed to an older name. The package we
5475 // are trying to install should be installed as an update to
5476 // the existing one, but that has not been requested, so bail.
5477 Slog.w(TAG, "Attempt to re-install " + pkgName
5478 + " without first uninstalling package running as "
5479 + mSettings.mRenamedPackages.get(pkgName));
5480 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5481 return;
5482 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005483 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005485 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 + " without first uninstalling.");
5487 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5488 return;
5489 }
5490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005491 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005492 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005494 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5496 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5497 }
5498 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005499 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005500 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 res);
5502 // delete the partially installed application. the data directory will have to be
5503 // restored if it was already existing
5504 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5505 // remove package from internal structures. Note that we want deletePackageX to
5506 // delete the package data and cache directories that it created in
5507 // scanPackageLocked, unless those directories existed before we even tried to
5508 // install.
5509 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005510 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5512 res.removedInfo);
5513 }
5514 }
5515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005516
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005517 private void replacePackageLI(PackageParser.Package pkg,
5518 int parseFlags,
5519 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005520 String installerPackageName, PackageInstalledInfo res) {
5521
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005522 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005523 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 // First find the old package info and check signatures
5525 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005526 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005527 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005528 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5530 return;
5531 }
5532 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005533 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005534 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005535 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 }
5539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005542 PackageParser.Package pkg,
5543 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 PackageParser.Package newPackage = null;
5546 String pkgName = deletedPackage.packageName;
5547 boolean deletedPkg = true;
5548 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005549
Jacek Surazski65e13172009-04-28 15:26:38 +02005550 String oldInstallerPackageName = null;
5551 synchronized (mPackages) {
5552 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005556 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 res.removedInfo)) {
5558 // If the existing package was'nt successfully deleted
5559 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5560 deletedPkg = false;
5561 } else {
5562 // Successfully deleted the old package. Now proceed with re-installation
5563 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005564 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005566 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5568 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005569 }
5570 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005572 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 res);
5574 updatedSettings = true;
5575 }
5576 }
5577
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005578 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 // remove package from internal structures. Note that we want deletePackageX to
5580 // delete the package data and cache directories that it created in
5581 // scanPackageLocked, unless those directories existed before we even tried to
5582 // install.
5583 if(updatedSettings) {
5584 deletePackageLI(
5585 pkgName, true,
5586 PackageManager.DONT_DELETE_DATA,
5587 res.removedInfo);
5588 }
5589 // Since we failed to install the new package we need to restore the old
5590 // package that we deleted.
5591 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005592 File restoreFile = new File(deletedPackage.mPath);
5593 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005594 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005595 return;
5596 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005597 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005598 boolean oldOnSd = isExternal(deletedPackage);
5599 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5600 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5601 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5602 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5603 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5604 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5605 return;
5606 }
5607 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005608 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005609 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5610 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005611 mSettings.writeLP();
5612 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005613 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 }
5615 }
5616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005619 PackageParser.Package pkg,
5620 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005621 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 PackageParser.Package newPackage = null;
5623 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005624 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 PackageParser.PARSE_IS_SYSTEM;
5626 String packageName = deletedPackage.packageName;
5627 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5628 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005629 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 return;
5631 }
5632 PackageParser.Package oldPkg;
5633 PackageSetting oldPkgSetting;
5634 synchronized (mPackages) {
5635 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005636 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5638 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005639 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 return;
5641 }
5642 }
5643 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5644 res.removedInfo.removedPackage = packageName;
5645 // Remove existing system package
5646 removePackageLI(oldPkg, true);
5647 synchronized (mPackages) {
5648 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5649 }
5650
5651 // Successfully disabled the old package. Now proceed with re-installation
5652 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5653 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005654 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005656 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5658 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5659 }
5660 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005661 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005662 updatedSettings = true;
5663 }
5664
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005665 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 // Re installation failed. Restore old information
5667 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005668 if (newPackage != null) {
5669 removePackageLI(newPackage, true);
5670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005672 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005674 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 // Restore the old system information in Settings
5676 synchronized(mPackages) {
5677 if(updatedSettings) {
5678 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005679 mSettings.setInstallerPackageName(packageName,
5680 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 }
5682 mSettings.writeLP();
5683 }
5684 }
5685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005686
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005687 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005688 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005689 int retCode;
5690 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5691 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5692 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005693 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005694 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5695 }
5696 }
5697 return PackageManager.INSTALL_SUCCEEDED;
5698 }
5699
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005700 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005701 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005702 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 synchronized (mPackages) {
5704 //write settings. the installStatus will be incomplete at this stage.
5705 //note that the new package setting would have already been
5706 //added to mPackages. It hasn't been persisted yet.
5707 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5708 mSettings.writeLP();
5709 }
5710
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005711 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005712 != PackageManager.INSTALL_SUCCEEDED) {
5713 // Discontinue if moving dex files failed.
5714 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005716 if((res.returnCode = setPermissionsLI(newPackage))
5717 != PackageManager.INSTALL_SUCCEEDED) {
5718 if (mInstaller != null) {
5719 mInstaller.rmdex(newPackage.mScanPath);
5720 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005721 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005723 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005726 updatePermissionsLP(newPackage.packageName, newPackage,
5727 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 res.name = pkgName;
5729 res.uid = newPackage.applicationInfo.uid;
5730 res.pkg = newPackage;
5731 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005732 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5734 //to update install status
5735 mSettings.writeLP();
5736 }
5737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005738
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005739 private void installPackageLI(InstallArgs args,
5740 boolean newInstall, PackageInstalledInfo res) {
5741 int pFlags = args.flags;
5742 String installerPackageName = args.installerPackageName;
5743 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005744 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005745 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005746 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005747 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005748 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005749 // Result object to be returned
5750 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5751
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005752 // Retrieve PackageSettings and parse package
5753 int parseFlags = PackageParser.PARSE_CHATTY |
5754 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5755 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5756 parseFlags |= mDefParseFlags;
5757 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5758 pp.setSeparateProcesses(mSeparateProcesses);
5759 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5760 null, mMetrics, parseFlags);
5761 if (pkg == null) {
5762 res.returnCode = pp.getParseError();
5763 return;
5764 }
5765 String pkgName = res.name = pkg.packageName;
5766 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5767 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5768 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5769 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005771 }
5772 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5773 res.returnCode = pp.getParseError();
5774 return;
5775 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005776 // Get rid of all references to package scan path via parser.
5777 pp = null;
5778 String oldCodePath = null;
5779 boolean systemApp = false;
5780 synchronized (mPackages) {
5781 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005782 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5783 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005784 if (pkg.mOriginalPackages != null
5785 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005786 && mPackages.containsKey(oldName)) {
5787 // This package is derived from an original package,
5788 // and this device has been updating from that original
5789 // name. We must continue using the original name, so
5790 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005791 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005792 pkgName = pkg.packageName;
5793 replace = true;
5794 } else if (mPackages.containsKey(pkgName)) {
5795 // This package, under its official name, already exists
5796 // on the device; we should replace it.
5797 replace = true;
5798 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005799 }
5800 PackageSetting ps = mSettings.mPackages.get(pkgName);
5801 if (ps != null) {
5802 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5803 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5804 systemApp = (ps.pkg.applicationInfo.flags &
5805 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005806 }
5807 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005809
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005810 if (systemApp && onSd) {
5811 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005812 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005813 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5814 return;
5815 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005816
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005817 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5818 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5819 return;
5820 }
5821 // Set application objects path explicitly after the rename
5822 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005823 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005824 replacePackageLI(pkg, parseFlags, scanMode,
5825 installerPackageName, res);
5826 } else {
5827 installNewPackageLI(pkg, parseFlags, scanMode,
5828 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 }
5830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005831
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005832 private int setPermissionsLI(PackageParser.Package newPackage) {
5833 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005834 int retCode = 0;
5835 // TODO Gross hack but fix later. Ideally move this to be a post installation
5836 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005837 if ((newPackage.applicationInfo.flags
5838 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5839 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 try {
5841 extractPublicFiles(newPackage, destResourceFile);
5842 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005843 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 -08005844 " forward-locked app.");
5845 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5846 } finally {
5847 //TODO clean up the extracted public files
5848 }
5849 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005850 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 newPackage.applicationInfo.uid);
5852 } else {
5853 final int filePermissions =
5854 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005855 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 newPackage.applicationInfo.uid);
5857 }
5858 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005859 // The permissions on the resource file was set when it was copied for
5860 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005864 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005865 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005867 // TODO Define new internal error
5868 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 }
5870 return PackageManager.INSTALL_SUCCEEDED;
5871 }
5872
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005873 private boolean isForwardLocked(PackageParser.Package pkg) {
5874 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 }
5876
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005877 private boolean isExternal(PackageParser.Package pkg) {
5878 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5879 }
5880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 private void extractPublicFiles(PackageParser.Package newPackage,
5882 File publicZipFile) throws IOException {
5883 final ZipOutputStream publicZipOutStream =
5884 new ZipOutputStream(new FileOutputStream(publicZipFile));
5885 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5886
5887 // Copy manifest, resources.arsc and res directory to public zip
5888
5889 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5890 while (privateZipEntries.hasMoreElements()) {
5891 final ZipEntry zipEntry = privateZipEntries.nextElement();
5892 final String zipEntryName = zipEntry.getName();
5893 if ("AndroidManifest.xml".equals(zipEntryName)
5894 || "resources.arsc".equals(zipEntryName)
5895 || zipEntryName.startsWith("res/")) {
5896 try {
5897 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5898 } catch (IOException e) {
5899 try {
5900 publicZipOutStream.close();
5901 throw e;
5902 } finally {
5903 publicZipFile.delete();
5904 }
5905 }
5906 }
5907 }
5908
5909 publicZipOutStream.close();
5910 FileUtils.setPermissions(
5911 publicZipFile.getAbsolutePath(),
5912 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5913 -1, -1);
5914 }
5915
5916 private static void copyZipEntry(ZipEntry zipEntry,
5917 ZipFile inZipFile,
5918 ZipOutputStream outZipStream) throws IOException {
5919 byte[] buffer = new byte[4096];
5920 int num;
5921
5922 ZipEntry newEntry;
5923 if (zipEntry.getMethod() == ZipEntry.STORED) {
5924 // Preserve the STORED method of the input entry.
5925 newEntry = new ZipEntry(zipEntry);
5926 } else {
5927 // Create a new entry so that the compressed len is recomputed.
5928 newEntry = new ZipEntry(zipEntry.getName());
5929 }
5930 outZipStream.putNextEntry(newEntry);
5931
5932 InputStream data = inZipFile.getInputStream(zipEntry);
5933 while ((num = data.read(buffer)) > 0) {
5934 outZipStream.write(buffer, 0, num);
5935 }
5936 outZipStream.flush();
5937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 private void deleteTempPackageFiles() {
5940 FilenameFilter filter = new FilenameFilter() {
5941 public boolean accept(File dir, String name) {
5942 return name.startsWith("vmdl") && name.endsWith(".tmp");
5943 }
5944 };
5945 String tmpFilesList[] = mAppInstallDir.list(filter);
5946 if(tmpFilesList == null) {
5947 return;
5948 }
5949 for(int i = 0; i < tmpFilesList.length; i++) {
5950 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5951 tmpFile.delete();
5952 }
5953 }
5954
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005955 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 File tmpPackageFile;
5957 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005958 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005960 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 return null;
5962 }
5963 try {
5964 FileUtils.setPermissions(
5965 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5966 -1, -1);
5967 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005968 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 return null;
5970 }
5971 return tmpPackageFile;
5972 }
5973
5974 public void deletePackage(final String packageName,
5975 final IPackageDeleteObserver observer,
5976 final int flags) {
5977 mContext.enforceCallingOrSelfPermission(
5978 android.Manifest.permission.DELETE_PACKAGES, null);
5979 // Queue up an async operation since the package deletion may take a little while.
5980 mHandler.post(new Runnable() {
5981 public void run() {
5982 mHandler.removeCallbacks(this);
5983 final boolean succeded = deletePackageX(packageName, true, true, flags);
5984 if (observer != null) {
5985 try {
5986 observer.packageDeleted(succeded);
5987 } catch (RemoteException e) {
5988 Log.i(TAG, "Observer no longer exists.");
5989 } //end catch
5990 } //end if
5991 } //end run
5992 });
5993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 /**
5996 * This method is an internal method that could be get invoked either
5997 * to delete an installed package or to clean up a failed installation.
5998 * After deleting an installed package, a broadcast is sent to notify any
5999 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 * installation wouldn't have sent the initial broadcast either
6002 * The key steps in deleting a package are
6003 * deleting the package information in internal structures like mPackages,
6004 * deleting the packages base directories through installd
6005 * updating mSettings to reflect current status
6006 * persisting settings for later use
6007 * sending a broadcast if necessary
6008 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6010 boolean deleteCodeAndResources, int flags) {
6011 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006012 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006014 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6015 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6016 try {
6017 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006018 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006019 return false;
6020 }
6021 } catch (RemoteException e) {
6022 }
6023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 synchronized (mInstallLock) {
6025 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006029 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6030 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6031
6032 // If the removed package was a system update, the old system packaged
6033 // was re-enabled; we need to broadcast this information
6034 if (systemUpdate) {
6035 Bundle extras = new Bundle(1);
6036 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6037 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6038
6039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
6040 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
6041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006043 // Force a gc here.
6044 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006045 // Delete the resources here after sending the broadcast to let
6046 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006047 if (info.args != null) {
6048 synchronized (mInstallLock) {
6049 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006050 }
6051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 return res;
6053 }
6054
6055 static class PackageRemovedInfo {
6056 String removedPackage;
6057 int uid = -1;
6058 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006059 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006060 // Clean up resources deleted packages.
6061 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 void sendBroadcast(boolean fullRemove, boolean replacing) {
6064 Bundle extras = new Bundle(1);
6065 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6066 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6067 if (replacing) {
6068 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6069 }
6070 if (removedPackage != null) {
6071 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6072 }
6073 if (removedUid >= 0) {
6074 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6075 }
6076 }
6077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 /*
6080 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6081 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006082 * 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 -08006083 * delete a partially installed application.
6084 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006085 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 int flags) {
6087 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006088 if (outInfo != null) {
6089 outInfo.removedPackage = packageName;
6090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 removePackageLI(p, true);
6092 // Retrieve object to delete permissions for shared user later on
6093 PackageSetting deletedPs;
6094 synchronized (mPackages) {
6095 deletedPs = mSettings.mPackages.get(packageName);
6096 }
6097 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6098 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006099 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006101 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 + packageName + ", retcode=" + retCode);
6103 // we don't consider this to be a failure of the core package deletion
6104 }
6105 } else {
6106 //for emulator
6107 PackageParser.Package pkg = mPackages.get(packageName);
6108 File dataDir = new File(pkg.applicationInfo.dataDir);
6109 dataDir.delete();
6110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 }
6112 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006113 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006114 schedulePackageCleaning(packageName);
6115
6116 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6117 if (outInfo != null) {
6118 outInfo.removedUid = mSettings.removePackageLP(packageName);
6119 }
6120 if (deletedPs != null) {
6121 updatePermissionsLP(deletedPs.name, null, false, false);
6122 if (deletedPs.sharedUser != null) {
6123 // remove permissions associated with package
6124 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6125 }
6126 }
6127 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006128 // remove from preferred activities.
6129 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6130 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6131 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6132 removed.add(pa);
6133 }
6134 }
6135 for (PreferredActivity pa : removed) {
6136 mSettings.mPreferredActivities.removeFilter(pa);
6137 }
6138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006140 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 }
6142 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 /*
6145 * Tries to delete system package.
6146 */
6147 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006148 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 ApplicationInfo applicationInfo = p.applicationInfo;
6150 //applicable for non-partially installed applications only
6151 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006152 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 return false;
6154 }
6155 PackageSetting ps = null;
6156 // Confirm if the system package has been updated
6157 // An updated system app can be deleted. This will also have to restore
6158 // the system pkg from system partition
6159 synchronized (mPackages) {
6160 ps = mSettings.getDisabledSystemPkg(p.packageName);
6161 }
6162 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006163 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 return false;
6165 } else {
6166 Log.i(TAG, "Deleting system pkg from data partition");
6167 }
6168 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006169 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006170 boolean deleteCodeAndResources = false;
6171 if (ps.versionCode < p.mVersionCode) {
6172 // Delete code and resources for downgrades
6173 deleteCodeAndResources = true;
6174 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6175 flags &= ~PackageManager.DONT_DELETE_DATA;
6176 }
6177 } else {
6178 // Preserve data by setting flag
6179 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6180 flags |= PackageManager.DONT_DELETE_DATA;
6181 }
6182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6184 if (!ret) {
6185 return false;
6186 }
6187 synchronized (mPackages) {
6188 // Reinstate the old system package
6189 mSettings.enableSystemPackageLP(p.packageName);
6190 }
6191 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006192 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006194 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006197 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 return false;
6199 }
6200 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006201 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 mSettings.writeLP();
6203 }
6204 return true;
6205 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6208 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6209 ApplicationInfo applicationInfo = p.applicationInfo;
6210 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006211 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 return false;
6213 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006214 if (outInfo != null) {
6215 outInfo.uid = applicationInfo.uid;
6216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217
6218 // Delete package data from internal structures and also remove data if flag is set
6219 removePackageDataLI(p, outInfo, flags);
6220
6221 // Delete application code and resources
6222 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006223 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006224 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006225 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006226 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6227 PackageManager.INSTALL_FORWARD_LOCK : 0;
6228 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006229 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 }
6231 return true;
6232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 /*
6235 * This method handles package deletion in general
6236 */
6237 private boolean deletePackageLI(String packageName,
6238 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6239 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006240 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 return false;
6242 }
6243 PackageParser.Package p;
6244 boolean dataOnly = false;
6245 synchronized (mPackages) {
6246 p = mPackages.get(packageName);
6247 if (p == null) {
6248 //this retrieves partially installed apps
6249 dataOnly = true;
6250 PackageSetting ps = mSettings.mPackages.get(packageName);
6251 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006252 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 return false;
6254 }
6255 p = ps.pkg;
6256 }
6257 }
6258 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006259 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 return false;
6261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 if (dataOnly) {
6264 // Delete application data first
6265 removePackageDataLI(p, outInfo, flags);
6266 return true;
6267 }
6268 // At this point the package should have ApplicationInfo associated with it
6269 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006270 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 return false;
6272 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006273 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6275 Log.i(TAG, "Removing system package:"+p.packageName);
6276 // When an updated system application is deleted we delete the existing resources as well and
6277 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006278 ret = deleteSystemPackageLI(p, flags, outInfo);
6279 } else {
6280 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006281 // Kill application pre-emptively especially for apps on sd.
6282 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006283 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006285 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 public void clearApplicationUserData(final String packageName,
6289 final IPackageDataObserver observer) {
6290 mContext.enforceCallingOrSelfPermission(
6291 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6292 // Queue up an async operation since the package deletion may take a little while.
6293 mHandler.post(new Runnable() {
6294 public void run() {
6295 mHandler.removeCallbacks(this);
6296 final boolean succeeded;
6297 synchronized (mInstallLock) {
6298 succeeded = clearApplicationUserDataLI(packageName);
6299 }
6300 if (succeeded) {
6301 // invoke DeviceStorageMonitor's update method to clear any notifications
6302 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6303 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6304 if (dsm != null) {
6305 dsm.updateMemory();
6306 }
6307 }
6308 if(observer != null) {
6309 try {
6310 observer.onRemoveCompleted(packageName, succeeded);
6311 } catch (RemoteException e) {
6312 Log.i(TAG, "Observer no longer exists.");
6313 }
6314 } //end if observer
6315 } //end run
6316 });
6317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 private boolean clearApplicationUserDataLI(String packageName) {
6320 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006321 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 return false;
6323 }
6324 PackageParser.Package p;
6325 boolean dataOnly = false;
6326 synchronized (mPackages) {
6327 p = mPackages.get(packageName);
6328 if(p == null) {
6329 dataOnly = true;
6330 PackageSetting ps = mSettings.mPackages.get(packageName);
6331 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006332 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 return false;
6334 }
6335 p = ps.pkg;
6336 }
6337 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 if(!dataOnly) {
6340 //need to check this only for fully installed applications
6341 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006342 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 return false;
6344 }
6345 final ApplicationInfo applicationInfo = p.applicationInfo;
6346 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006347 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 return false;
6349 }
6350 }
6351 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006352 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006354 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 + packageName);
6356 return false;
6357 }
6358 }
6359 return true;
6360 }
6361
6362 public void deleteApplicationCacheFiles(final String packageName,
6363 final IPackageDataObserver observer) {
6364 mContext.enforceCallingOrSelfPermission(
6365 android.Manifest.permission.DELETE_CACHE_FILES, null);
6366 // Queue up an async operation since the package deletion may take a little while.
6367 mHandler.post(new Runnable() {
6368 public void run() {
6369 mHandler.removeCallbacks(this);
6370 final boolean succeded;
6371 synchronized (mInstallLock) {
6372 succeded = deleteApplicationCacheFilesLI(packageName);
6373 }
6374 if(observer != null) {
6375 try {
6376 observer.onRemoveCompleted(packageName, succeded);
6377 } catch (RemoteException e) {
6378 Log.i(TAG, "Observer no longer exists.");
6379 }
6380 } //end if observer
6381 } //end run
6382 });
6383 }
6384
6385 private boolean deleteApplicationCacheFilesLI(String packageName) {
6386 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006387 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 return false;
6389 }
6390 PackageParser.Package p;
6391 synchronized (mPackages) {
6392 p = mPackages.get(packageName);
6393 }
6394 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006395 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 return false;
6397 }
6398 final ApplicationInfo applicationInfo = p.applicationInfo;
6399 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006400 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 return false;
6402 }
6403 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006404 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006406 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 + packageName);
6408 return false;
6409 }
6410 }
6411 return true;
6412 }
6413
6414 public void getPackageSizeInfo(final String packageName,
6415 final IPackageStatsObserver observer) {
6416 mContext.enforceCallingOrSelfPermission(
6417 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6418 // Queue up an async operation since the package deletion may take a little while.
6419 mHandler.post(new Runnable() {
6420 public void run() {
6421 mHandler.removeCallbacks(this);
6422 PackageStats lStats = new PackageStats(packageName);
6423 final boolean succeded;
6424 synchronized (mInstallLock) {
6425 succeded = getPackageSizeInfoLI(packageName, lStats);
6426 }
6427 if(observer != null) {
6428 try {
6429 observer.onGetStatsCompleted(lStats, succeded);
6430 } catch (RemoteException e) {
6431 Log.i(TAG, "Observer no longer exists.");
6432 }
6433 } //end if observer
6434 } //end run
6435 });
6436 }
6437
6438 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6439 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006440 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 return false;
6442 }
6443 PackageParser.Package p;
6444 boolean dataOnly = false;
6445 synchronized (mPackages) {
6446 p = mPackages.get(packageName);
6447 if(p == null) {
6448 dataOnly = true;
6449 PackageSetting ps = mSettings.mPackages.get(packageName);
6450 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006451 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 return false;
6453 }
6454 p = ps.pkg;
6455 }
6456 }
6457 String publicSrcDir = null;
6458 if(!dataOnly) {
6459 final ApplicationInfo applicationInfo = p.applicationInfo;
6460 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006461 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 return false;
6463 }
6464 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6465 }
6466 if (mInstaller != null) {
6467 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006468 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 if (res < 0) {
6470 return false;
6471 } else {
6472 return true;
6473 }
6474 }
6475 return true;
6476 }
6477
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 public void addPackageToPreferred(String packageName) {
6480 mContext.enforceCallingOrSelfPermission(
6481 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006482 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 }
6484
6485 public void removePackageFromPreferred(String packageName) {
6486 mContext.enforceCallingOrSelfPermission(
6487 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006488 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 }
6490
6491 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006492 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006495 int getUidTargetSdkVersionLockedLP(int uid) {
6496 Object obj = mSettings.getUserIdLP(uid);
6497 if (obj instanceof SharedUserSetting) {
6498 SharedUserSetting sus = (SharedUserSetting)obj;
6499 final int N = sus.packages.size();
6500 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6501 Iterator<PackageSetting> it = sus.packages.iterator();
6502 int i=0;
6503 while (it.hasNext()) {
6504 PackageSetting ps = it.next();
6505 if (ps.pkg != null) {
6506 int v = ps.pkg.applicationInfo.targetSdkVersion;
6507 if (v < vers) vers = v;
6508 }
6509 }
6510 return vers;
6511 } else if (obj instanceof PackageSetting) {
6512 PackageSetting ps = (PackageSetting)obj;
6513 if (ps.pkg != null) {
6514 return ps.pkg.applicationInfo.targetSdkVersion;
6515 }
6516 }
6517 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6518 }
6519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 public void addPreferredActivity(IntentFilter filter, int match,
6521 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006523 if (mContext.checkCallingOrSelfPermission(
6524 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6525 != PackageManager.PERMISSION_GRANTED) {
6526 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6527 < Build.VERSION_CODES.FROYO) {
6528 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6529 + Binder.getCallingUid());
6530 return;
6531 }
6532 mContext.enforceCallingOrSelfPermission(
6533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6534 }
6535
6536 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6538 mSettings.mPreferredActivities.addFilter(
6539 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006540 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
6542 }
6543
Satish Sampath8dbe6122009-06-02 23:35:54 +01006544 public void replacePreferredActivity(IntentFilter filter, int match,
6545 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006546 if (filter.countActions() != 1) {
6547 throw new IllegalArgumentException(
6548 "replacePreferredActivity expects filter to have only 1 action.");
6549 }
6550 if (filter.countCategories() != 1) {
6551 throw new IllegalArgumentException(
6552 "replacePreferredActivity expects filter to have only 1 category.");
6553 }
6554 if (filter.countDataAuthorities() != 0
6555 || filter.countDataPaths() != 0
6556 || filter.countDataSchemes() != 0
6557 || filter.countDataTypes() != 0) {
6558 throw new IllegalArgumentException(
6559 "replacePreferredActivity expects filter to have no data authorities, " +
6560 "paths, schemes or types.");
6561 }
6562 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006563 if (mContext.checkCallingOrSelfPermission(
6564 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6565 != PackageManager.PERMISSION_GRANTED) {
6566 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6567 < Build.VERSION_CODES.FROYO) {
6568 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6569 + Binder.getCallingUid());
6570 return;
6571 }
6572 mContext.enforceCallingOrSelfPermission(
6573 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6574 }
6575
Satish Sampath8dbe6122009-06-02 23:35:54 +01006576 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6577 String action = filter.getAction(0);
6578 String category = filter.getCategory(0);
6579 while (it.hasNext()) {
6580 PreferredActivity pa = it.next();
6581 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6582 it.remove();
6583 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6584 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6585 }
6586 }
6587 addPreferredActivity(filter, match, set, activity);
6588 }
6589 }
6590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006593 int uid = Binder.getCallingUid();
6594 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006595 if (pkg == null || pkg.applicationInfo.uid != uid) {
6596 if (mContext.checkCallingOrSelfPermission(
6597 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6598 != PackageManager.PERMISSION_GRANTED) {
6599 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6600 < Build.VERSION_CODES.FROYO) {
6601 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6602 + Binder.getCallingUid());
6603 return;
6604 }
6605 mContext.enforceCallingOrSelfPermission(
6606 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6607 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006608 }
6609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006611 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 }
6613 }
6614 }
6615
6616 boolean clearPackagePreferredActivitiesLP(String packageName) {
6617 boolean changed = false;
6618 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6619 while (it.hasNext()) {
6620 PreferredActivity pa = it.next();
6621 if (pa.mActivity.getPackageName().equals(packageName)) {
6622 it.remove();
6623 changed = true;
6624 }
6625 }
6626 return changed;
6627 }
6628
6629 public int getPreferredActivities(List<IntentFilter> outFilters,
6630 List<ComponentName> outActivities, String packageName) {
6631
6632 int num = 0;
6633 synchronized (mPackages) {
6634 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6635 while (it.hasNext()) {
6636 PreferredActivity pa = it.next();
6637 if (packageName == null
6638 || pa.mActivity.getPackageName().equals(packageName)) {
6639 if (outFilters != null) {
6640 outFilters.add(new IntentFilter(pa));
6641 }
6642 if (outActivities != null) {
6643 outActivities.add(pa.mActivity);
6644 }
6645 }
6646 }
6647 }
6648
6649 return num;
6650 }
6651
6652 public void setApplicationEnabledSetting(String appPackageName,
6653 int newState, int flags) {
6654 setEnabledSetting(appPackageName, null, newState, flags);
6655 }
6656
6657 public void setComponentEnabledSetting(ComponentName componentName,
6658 int newState, int flags) {
6659 setEnabledSetting(componentName.getPackageName(),
6660 componentName.getClassName(), newState, flags);
6661 }
6662
6663 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006664 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6666 || newState == COMPONENT_ENABLED_STATE_ENABLED
6667 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6668 throw new IllegalArgumentException("Invalid new component state: "
6669 + newState);
6670 }
6671 PackageSetting pkgSetting;
6672 final int uid = Binder.getCallingUid();
6673 final int permission = mContext.checkCallingPermission(
6674 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6675 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006676 boolean sendNow = false;
6677 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006678 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006680 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006682 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006684 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006686 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 }
6688 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006689 "Unknown component: " + packageName
6690 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 }
6692 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6693 throw new SecurityException(
6694 "Permission Denial: attempt to change component state from pid="
6695 + Binder.getCallingPid()
6696 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6697 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006698 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006700 if (pkgSetting.enabled == newState) {
6701 // Nothing to do
6702 return;
6703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 pkgSetting.enabled = newState;
6705 } else {
6706 // We're dealing with a component level state change
6707 switch (newState) {
6708 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006709 if (!pkgSetting.enableComponentLP(className)) {
6710 return;
6711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 break;
6713 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006714 if (!pkgSetting.disableComponentLP(className)) {
6715 return;
6716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 break;
6718 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006719 if (!pkgSetting.restoreComponentLP(className)) {
6720 return;
6721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 break;
6723 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006724 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006725 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 }
6727 }
6728 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006729 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006730 components = mPendingBroadcasts.get(packageName);
6731 boolean newPackage = components == null;
6732 if (newPackage) {
6733 components = new ArrayList<String>();
6734 }
6735 if (!components.contains(componentName)) {
6736 components.add(componentName);
6737 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006738 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6739 sendNow = true;
6740 // Purge entry from pending broadcast list if another one exists already
6741 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006742 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006743 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006744 if (newPackage) {
6745 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006746 }
6747 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6748 // Schedule a message
6749 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6750 }
6751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 long callingId = Binder.clearCallingIdentity();
6755 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006756 if (sendNow) {
6757 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006758 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 } finally {
6761 Binder.restoreCallingIdentity(callingId);
6762 }
6763 }
6764
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006765 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006766 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6767 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6768 + " components=" + componentNames);
6769 Bundle extras = new Bundle(4);
6770 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6771 String nameList[] = new String[componentNames.size()];
6772 componentNames.toArray(nameList);
6773 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006774 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6775 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006776 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006777 }
6778
Jacek Surazski65e13172009-04-28 15:26:38 +02006779 public String getInstallerPackageName(String packageName) {
6780 synchronized (mPackages) {
6781 PackageSetting pkg = mSettings.mPackages.get(packageName);
6782 if (pkg == null) {
6783 throw new IllegalArgumentException("Unknown package: " + packageName);
6784 }
6785 return pkg.installerPackageName;
6786 }
6787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 public int getApplicationEnabledSetting(String appPackageName) {
6790 synchronized (mPackages) {
6791 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6792 if (pkg == null) {
6793 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6794 }
6795 return pkg.enabled;
6796 }
6797 }
6798
6799 public int getComponentEnabledSetting(ComponentName componentName) {
6800 synchronized (mPackages) {
6801 final String packageNameStr = componentName.getPackageName();
6802 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6803 if (pkg == null) {
6804 throw new IllegalArgumentException("Unknown component: " + componentName);
6805 }
6806 final String classNameStr = componentName.getClassName();
6807 return pkg.currentEnabledStateLP(classNameStr);
6808 }
6809 }
6810
6811 public void enterSafeMode() {
6812 if (!mSystemReady) {
6813 mSafeMode = true;
6814 }
6815 }
6816
6817 public void systemReady() {
6818 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006819
6820 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006821 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006822 mContext.getContentResolver(),
6823 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006824 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006825 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006826 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 }
6829
6830 public boolean isSafeMode() {
6831 return mSafeMode;
6832 }
6833
6834 public boolean hasSystemUidErrors() {
6835 return mHasSystemUidErrors;
6836 }
6837
6838 static String arrayToString(int[] array) {
6839 StringBuffer buf = new StringBuffer(128);
6840 buf.append('[');
6841 if (array != null) {
6842 for (int i=0; i<array.length; i++) {
6843 if (i > 0) buf.append(", ");
6844 buf.append(array[i]);
6845 }
6846 }
6847 buf.append(']');
6848 return buf.toString();
6849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006851 @Override
6852 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6853 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6854 != PackageManager.PERMISSION_GRANTED) {
6855 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6856 + Binder.getCallingPid()
6857 + ", uid=" + Binder.getCallingUid()
6858 + " without permission "
6859 + android.Manifest.permission.DUMP);
6860 return;
6861 }
6862
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006863 String packageName = null;
6864
6865 int opti = 0;
6866 while (opti < args.length) {
6867 String opt = args[opti];
6868 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6869 break;
6870 }
6871 opti++;
6872 if ("-a".equals(opt)) {
6873 // Right now we only know how to print all.
6874 } else if ("-h".equals(opt)) {
6875 pw.println("Package manager dump options:");
6876 pw.println(" [-h] [cmd] ...");
6877 pw.println(" cmd may be one of:");
6878 pw.println(" [package.name]: info about given package");
6879 return;
6880 } else {
6881 pw.println("Unknown argument: " + opt + "; use -h for help");
6882 }
6883 }
6884
6885 // Is the caller requesting to dump a particular piece of data?
6886 if (opti < args.length) {
6887 String cmd = args[opti];
6888 opti++;
6889 // Is this a package name?
6890 if ("android".equals(cmd) || cmd.contains(".")) {
6891 packageName = cmd;
6892 }
6893 }
6894
6895 boolean printedTitle = false;
6896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006898 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6899 printedTitle = true;
6900 }
6901 if (mReceivers.dump(pw, printedTitle
6902 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6903 " ", packageName)) {
6904 printedTitle = true;
6905 }
6906 if (mServices.dump(pw, printedTitle
6907 ? "\nService Resolver Table:" : "Service Resolver Table:",
6908 " ", packageName)) {
6909 printedTitle = true;
6910 }
6911 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6912 ? "\nPreferred Activities:" : "Preferred Activities:",
6913 " ", packageName)) {
6914 printedTitle = true;
6915 }
6916 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 {
6918 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006919 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6920 continue;
6921 }
6922 if (!printedSomething) {
6923 if (printedTitle) pw.println(" ");
6924 pw.println("Permissions:");
6925 printedSomething = true;
6926 printedTitle = true;
6927 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006928 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6929 pw.print(Integer.toHexString(System.identityHashCode(p)));
6930 pw.println("):");
6931 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6932 pw.print(" uid="); pw.print(p.uid);
6933 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006934 pw.print(" type="); pw.print(p.type);
6935 pw.print(" prot="); pw.println(p.protectionLevel);
6936 if (p.packageSetting != null) {
6937 pw.print(" packageSetting="); pw.println(p.packageSetting);
6938 }
6939 if (p.perm != null) {
6940 pw.print(" perm="); pw.println(p.perm);
6941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 }
6943 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006944 printedSomething = false;
6945 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 {
6947 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006948 if (packageName != null && !packageName.equals(ps.realName)
6949 && !packageName.equals(ps.name)) {
6950 continue;
6951 }
6952 if (!printedSomething) {
6953 if (printedTitle) pw.println(" ");
6954 pw.println("Packages:");
6955 printedSomething = true;
6956 printedTitle = true;
6957 }
6958 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006959 pw.print(" Package [");
6960 pw.print(ps.realName != null ? ps.realName : ps.name);
6961 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006962 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6963 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006964 if (ps.realName != null) {
6965 pw.print(" compat name="); pw.println(ps.name);
6966 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006967 pw.print(" userId="); pw.print(ps.userId);
6968 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6969 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6970 pw.print(" pkg="); pw.println(ps.pkg);
6971 pw.print(" codePath="); pw.println(ps.codePathString);
6972 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006974 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006975 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006976 pw.print(" supportsScreens=[");
6977 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006978 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006979 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006980 if (!first) pw.print(", ");
6981 first = false;
6982 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006984 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006985 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006986 if (!first) pw.print(", ");
6987 first = false;
6988 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006990 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006991 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006992 if (!first) pw.print(", ");
6993 first = false;
6994 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006996 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006997 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006998 if (!first) pw.print(", ");
6999 first = false;
7000 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007002 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007003 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7004 if (!first) pw.print(", ");
7005 first = false;
7006 pw.print("anyDensity");
7007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007009 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007010 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7011 pw.print(" signatures="); pw.println(ps.signatures);
7012 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007013 pw.print(" haveGids="); pw.println(ps.haveGids);
7014 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007015 pw.print(" installStatus="); pw.print(ps.installStatus);
7016 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 if (ps.disabledComponents.size() > 0) {
7018 pw.println(" disabledComponents:");
7019 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007020 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 }
7022 }
7023 if (ps.enabledComponents.size() > 0) {
7024 pw.println(" enabledComponents:");
7025 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007026 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 }
7028 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007029 if (ps.grantedPermissions.size() > 0) {
7030 pw.println(" grantedPermissions:");
7031 for (String s : ps.grantedPermissions) {
7032 pw.print(" "); pw.println(s);
7033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
7036 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007037 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007038 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007039 for (HashMap.Entry<String, String> e
7040 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007041 if (packageName != null && !packageName.equals(e.getKey())
7042 && !packageName.equals(e.getValue())) {
7043 continue;
7044 }
7045 if (!printedSomething) {
7046 if (printedTitle) pw.println(" ");
7047 pw.println("Renamed packages:");
7048 printedSomething = true;
7049 printedTitle = true;
7050 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007051 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7052 pw.println(e.getValue());
7053 }
7054 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007055 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007056 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007057 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007058 if (packageName != null && !packageName.equals(ps.realName)
7059 && !packageName.equals(ps.name)) {
7060 continue;
7061 }
7062 if (!printedSomething) {
7063 if (printedTitle) pw.println(" ");
7064 pw.println("Hidden system packages:");
7065 printedSomething = true;
7066 printedTitle = true;
7067 }
7068 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007069 pw.print(ps.realName != null ? ps.realName : ps.name);
7070 pw.print("] (");
7071 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7072 pw.println("):");
7073 if (ps.realName != null) {
7074 pw.print(" compat name="); pw.println(ps.name);
7075 }
7076 pw.print(" userId="); pw.println(ps.userId);
7077 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7078 pw.print(" codePath="); pw.println(ps.codePathString);
7079 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7080 }
7081 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007082 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 {
7084 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007085 if (packageName != null && su != packageSharedUser) {
7086 continue;
7087 }
7088 if (!printedSomething) {
7089 if (printedTitle) pw.println(" ");
7090 pw.println("Shared users:");
7091 printedSomething = true;
7092 printedTitle = true;
7093 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007094 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7095 pw.print(Integer.toHexString(System.identityHashCode(su)));
7096 pw.println("):");
7097 pw.print(" userId="); pw.print(su.userId);
7098 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 pw.println(" grantedPermissions:");
7100 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007101 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 }
7104 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007105
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007106 if (packageName == null) {
7107 if (printedTitle) pw.println(" ");
7108 printedTitle = true;
7109 pw.println("Settings parse messages:");
7110 pw.println(mSettings.mReadMessages.toString());
7111
7112 pw.println(" ");
7113 pw.println("Package warning messages:");
7114 File fname = getSettingsProblemFile();
7115 FileInputStream in;
7116 try {
7117 in = new FileInputStream(fname);
7118 int avail = in.available();
7119 byte[] data = new byte[avail];
7120 in.read(data);
7121 pw.println(new String(data));
7122 } catch (FileNotFoundException e) {
7123 } catch (IOException e) {
7124 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007127
7128 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007129 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007130 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007131 if (packageName != null && !packageName.equals(p.info.packageName)) {
7132 continue;
7133 }
7134 if (!printedSomething) {
7135 if (printedTitle) pw.println(" ");
7136 pw.println("Registered ContentProviders:");
7137 printedSomething = true;
7138 printedTitle = true;
7139 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007140 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007141 pw.println(p.toString());
7142 }
7143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007144 }
7145
7146 static final class BasePermission {
7147 final static int TYPE_NORMAL = 0;
7148 final static int TYPE_BUILTIN = 1;
7149 final static int TYPE_DYNAMIC = 2;
7150
7151 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007152 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007153 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007155 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 PackageParser.Permission perm;
7157 PermissionInfo pendingInfo;
7158 int uid;
7159 int[] gids;
7160
7161 BasePermission(String _name, String _sourcePackage, int _type) {
7162 name = _name;
7163 sourcePackage = _sourcePackage;
7164 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007165 // Default to most conservative protection level.
7166 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7167 }
7168
7169 public String toString() {
7170 return "BasePermission{"
7171 + Integer.toHexString(System.identityHashCode(this))
7172 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174 }
7175
7176 static class PackageSignatures {
7177 private Signature[] mSignatures;
7178
7179 PackageSignatures(Signature[] sigs) {
7180 assignSignatures(sigs);
7181 }
7182
7183 PackageSignatures() {
7184 }
7185
7186 void writeXml(XmlSerializer serializer, String tagName,
7187 ArrayList<Signature> pastSignatures) throws IOException {
7188 if (mSignatures == null) {
7189 return;
7190 }
7191 serializer.startTag(null, tagName);
7192 serializer.attribute(null, "count",
7193 Integer.toString(mSignatures.length));
7194 for (int i=0; i<mSignatures.length; i++) {
7195 serializer.startTag(null, "cert");
7196 final Signature sig = mSignatures[i];
7197 final int sigHash = sig.hashCode();
7198 final int numPast = pastSignatures.size();
7199 int j;
7200 for (j=0; j<numPast; j++) {
7201 Signature pastSig = pastSignatures.get(j);
7202 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7203 serializer.attribute(null, "index", Integer.toString(j));
7204 break;
7205 }
7206 }
7207 if (j >= numPast) {
7208 pastSignatures.add(sig);
7209 serializer.attribute(null, "index", Integer.toString(numPast));
7210 serializer.attribute(null, "key", sig.toCharsString());
7211 }
7212 serializer.endTag(null, "cert");
7213 }
7214 serializer.endTag(null, tagName);
7215 }
7216
7217 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7218 throws IOException, XmlPullParserException {
7219 String countStr = parser.getAttributeValue(null, "count");
7220 if (countStr == null) {
7221 reportSettingsProblem(Log.WARN,
7222 "Error in package manager settings: <signatures> has"
7223 + " no count at " + parser.getPositionDescription());
7224 XmlUtils.skipCurrentTag(parser);
7225 }
7226 final int count = Integer.parseInt(countStr);
7227 mSignatures = new Signature[count];
7228 int pos = 0;
7229
7230 int outerDepth = parser.getDepth();
7231 int type;
7232 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7233 && (type != XmlPullParser.END_TAG
7234 || parser.getDepth() > outerDepth)) {
7235 if (type == XmlPullParser.END_TAG
7236 || type == XmlPullParser.TEXT) {
7237 continue;
7238 }
7239
7240 String tagName = parser.getName();
7241 if (tagName.equals("cert")) {
7242 if (pos < count) {
7243 String index = parser.getAttributeValue(null, "index");
7244 if (index != null) {
7245 try {
7246 int idx = Integer.parseInt(index);
7247 String key = parser.getAttributeValue(null, "key");
7248 if (key == null) {
7249 if (idx >= 0 && idx < pastSignatures.size()) {
7250 Signature sig = pastSignatures.get(idx);
7251 if (sig != null) {
7252 mSignatures[pos] = pastSignatures.get(idx);
7253 pos++;
7254 } else {
7255 reportSettingsProblem(Log.WARN,
7256 "Error in package manager settings: <cert> "
7257 + "index " + index + " is not defined at "
7258 + parser.getPositionDescription());
7259 }
7260 } else {
7261 reportSettingsProblem(Log.WARN,
7262 "Error in package manager settings: <cert> "
7263 + "index " + index + " is out of bounds at "
7264 + parser.getPositionDescription());
7265 }
7266 } else {
7267 while (pastSignatures.size() <= idx) {
7268 pastSignatures.add(null);
7269 }
7270 Signature sig = new Signature(key);
7271 pastSignatures.set(idx, sig);
7272 mSignatures[pos] = sig;
7273 pos++;
7274 }
7275 } catch (NumberFormatException e) {
7276 reportSettingsProblem(Log.WARN,
7277 "Error in package manager settings: <cert> "
7278 + "index " + index + " is not a number at "
7279 + parser.getPositionDescription());
7280 }
7281 } else {
7282 reportSettingsProblem(Log.WARN,
7283 "Error in package manager settings: <cert> has"
7284 + " no index at " + parser.getPositionDescription());
7285 }
7286 } else {
7287 reportSettingsProblem(Log.WARN,
7288 "Error in package manager settings: too "
7289 + "many <cert> tags, expected " + count
7290 + " at " + parser.getPositionDescription());
7291 }
7292 } else {
7293 reportSettingsProblem(Log.WARN,
7294 "Unknown element under <cert>: "
7295 + parser.getName());
7296 }
7297 XmlUtils.skipCurrentTag(parser);
7298 }
7299
7300 if (pos < count) {
7301 // Should never happen -- there is an error in the written
7302 // settings -- but if it does we don't want to generate
7303 // a bad array.
7304 Signature[] newSigs = new Signature[pos];
7305 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7306 mSignatures = newSigs;
7307 }
7308 }
7309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 private void assignSignatures(Signature[] sigs) {
7311 if (sigs == null) {
7312 mSignatures = null;
7313 return;
7314 }
7315 mSignatures = new Signature[sigs.length];
7316 for (int i=0; i<sigs.length; i++) {
7317 mSignatures[i] = sigs[i];
7318 }
7319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 @Override
7322 public String toString() {
7323 StringBuffer buf = new StringBuffer(128);
7324 buf.append("PackageSignatures{");
7325 buf.append(Integer.toHexString(System.identityHashCode(this)));
7326 buf.append(" [");
7327 if (mSignatures != null) {
7328 for (int i=0; i<mSignatures.length; i++) {
7329 if (i > 0) buf.append(", ");
7330 buf.append(Integer.toHexString(
7331 System.identityHashCode(mSignatures[i])));
7332 }
7333 }
7334 buf.append("]}");
7335 return buf.toString();
7336 }
7337 }
7338
7339 static class PreferredActivity extends IntentFilter {
7340 final int mMatch;
7341 final String[] mSetPackages;
7342 final String[] mSetClasses;
7343 final String[] mSetComponents;
7344 final ComponentName mActivity;
7345 final String mShortActivity;
7346 String mParseError;
7347
7348 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7349 ComponentName activity) {
7350 super(filter);
7351 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7352 mActivity = activity;
7353 mShortActivity = activity.flattenToShortString();
7354 mParseError = null;
7355 if (set != null) {
7356 final int N = set.length;
7357 String[] myPackages = new String[N];
7358 String[] myClasses = new String[N];
7359 String[] myComponents = new String[N];
7360 for (int i=0; i<N; i++) {
7361 ComponentName cn = set[i];
7362 if (cn == null) {
7363 mSetPackages = null;
7364 mSetClasses = null;
7365 mSetComponents = null;
7366 return;
7367 }
7368 myPackages[i] = cn.getPackageName().intern();
7369 myClasses[i] = cn.getClassName().intern();
7370 myComponents[i] = cn.flattenToShortString().intern();
7371 }
7372 mSetPackages = myPackages;
7373 mSetClasses = myClasses;
7374 mSetComponents = myComponents;
7375 } else {
7376 mSetPackages = null;
7377 mSetClasses = null;
7378 mSetComponents = null;
7379 }
7380 }
7381
7382 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7383 IOException {
7384 mShortActivity = parser.getAttributeValue(null, "name");
7385 mActivity = ComponentName.unflattenFromString(mShortActivity);
7386 if (mActivity == null) {
7387 mParseError = "Bad activity name " + mShortActivity;
7388 }
7389 String matchStr = parser.getAttributeValue(null, "match");
7390 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7391 String setCountStr = parser.getAttributeValue(null, "set");
7392 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7393
7394 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7395 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7396 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7397
7398 int setPos = 0;
7399
7400 int outerDepth = parser.getDepth();
7401 int type;
7402 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7403 && (type != XmlPullParser.END_TAG
7404 || parser.getDepth() > outerDepth)) {
7405 if (type == XmlPullParser.END_TAG
7406 || type == XmlPullParser.TEXT) {
7407 continue;
7408 }
7409
7410 String tagName = parser.getName();
7411 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7412 // + parser.getDepth() + " tag=" + tagName);
7413 if (tagName.equals("set")) {
7414 String name = parser.getAttributeValue(null, "name");
7415 if (name == null) {
7416 if (mParseError == null) {
7417 mParseError = "No name in set tag in preferred activity "
7418 + mShortActivity;
7419 }
7420 } else if (setPos >= setCount) {
7421 if (mParseError == null) {
7422 mParseError = "Too many set tags in preferred activity "
7423 + mShortActivity;
7424 }
7425 } else {
7426 ComponentName cn = ComponentName.unflattenFromString(name);
7427 if (cn == null) {
7428 if (mParseError == null) {
7429 mParseError = "Bad set name " + name + " in preferred activity "
7430 + mShortActivity;
7431 }
7432 } else {
7433 myPackages[setPos] = cn.getPackageName();
7434 myClasses[setPos] = cn.getClassName();
7435 myComponents[setPos] = name;
7436 setPos++;
7437 }
7438 }
7439 XmlUtils.skipCurrentTag(parser);
7440 } else if (tagName.equals("filter")) {
7441 //Log.i(TAG, "Starting to parse filter...");
7442 readFromXml(parser);
7443 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7444 // + parser.getDepth() + " tag=" + parser.getName());
7445 } else {
7446 reportSettingsProblem(Log.WARN,
7447 "Unknown element under <preferred-activities>: "
7448 + parser.getName());
7449 XmlUtils.skipCurrentTag(parser);
7450 }
7451 }
7452
7453 if (setPos != setCount) {
7454 if (mParseError == null) {
7455 mParseError = "Not enough set tags (expected " + setCount
7456 + " but found " + setPos + ") in " + mShortActivity;
7457 }
7458 }
7459
7460 mSetPackages = myPackages;
7461 mSetClasses = myClasses;
7462 mSetComponents = myComponents;
7463 }
7464
7465 public void writeToXml(XmlSerializer serializer) throws IOException {
7466 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7467 serializer.attribute(null, "name", mShortActivity);
7468 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7469 serializer.attribute(null, "set", Integer.toString(NS));
7470 for (int s=0; s<NS; s++) {
7471 serializer.startTag(null, "set");
7472 serializer.attribute(null, "name", mSetComponents[s]);
7473 serializer.endTag(null, "set");
7474 }
7475 serializer.startTag(null, "filter");
7476 super.writeToXml(serializer);
7477 serializer.endTag(null, "filter");
7478 }
7479
7480 boolean sameSet(List<ResolveInfo> query, int priority) {
7481 if (mSetPackages == null) return false;
7482 final int NQ = query.size();
7483 final int NS = mSetPackages.length;
7484 int numMatch = 0;
7485 for (int i=0; i<NQ; i++) {
7486 ResolveInfo ri = query.get(i);
7487 if (ri.priority != priority) continue;
7488 ActivityInfo ai = ri.activityInfo;
7489 boolean good = false;
7490 for (int j=0; j<NS; j++) {
7491 if (mSetPackages[j].equals(ai.packageName)
7492 && mSetClasses[j].equals(ai.name)) {
7493 numMatch++;
7494 good = true;
7495 break;
7496 }
7497 }
7498 if (!good) return false;
7499 }
7500 return numMatch == NS;
7501 }
7502 }
7503
7504 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007505 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 HashSet<String> grantedPermissions = new HashSet<String>();
7508 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007511 setFlags(pkgFlags);
7512 }
7513
7514 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007515 this.pkgFlags = pkgFlags & (
7516 ApplicationInfo.FLAG_SYSTEM |
7517 ApplicationInfo.FLAG_FORWARD_LOCK |
7518 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 }
7520 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 /**
7523 * Settings base class for pending and resolved classes.
7524 */
7525 static class PackageSettingBase extends GrantedPermissions {
7526 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007527 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007528 File codePath;
7529 String codePathString;
7530 File resourcePath;
7531 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 private long timeStamp;
7533 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007534 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007536 boolean uidError;
7537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 PackageSignatures signatures = new PackageSignatures();
7539
7540 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007541 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 /* Explicitly disabled components */
7544 HashSet<String> disabledComponents = new HashSet<String>(0);
7545 /* Explicitly enabled components */
7546 HashSet<String> enabledComponents = new HashSet<String>(0);
7547 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7548 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007549
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007550 PackageSettingBase origPackage;
7551
Jacek Surazski65e13172009-04-28 15:26:38 +02007552 /* package name of the app that installed this package */
7553 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007555 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007556 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 super(pkgFlags);
7558 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007559 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007560 init(codePath, resourcePath, pVersionCode);
7561 }
7562
7563 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 this.codePath = codePath;
7565 this.codePathString = codePath.toString();
7566 this.resourcePath = resourcePath;
7567 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007568 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007570
Jacek Surazski65e13172009-04-28 15:26:38 +02007571 public void setInstallerPackageName(String packageName) {
7572 installerPackageName = packageName;
7573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007574
Jacek Surazski65e13172009-04-28 15:26:38 +02007575 String getInstallerPackageName() {
7576 return installerPackageName;
7577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 public void setInstallStatus(int newStatus) {
7580 installStatus = newStatus;
7581 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 public int getInstallStatus() {
7584 return installStatus;
7585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 public void setTimeStamp(long newStamp) {
7588 if (newStamp != timeStamp) {
7589 timeStamp = newStamp;
7590 timeStampString = Long.toString(newStamp);
7591 }
7592 }
7593
7594 public void setTimeStamp(long newStamp, String newStampStr) {
7595 timeStamp = newStamp;
7596 timeStampString = newStampStr;
7597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 public long getTimeStamp() {
7600 return timeStamp;
7601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 public String getTimeStampStr() {
7604 return timeStampString;
7605 }
7606
7607 public void copyFrom(PackageSettingBase base) {
7608 grantedPermissions = base.grantedPermissions;
7609 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 timeStamp = base.timeStamp;
7612 timeStampString = base.timeStampString;
7613 signatures = base.signatures;
7614 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007615 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 disabledComponents = base.disabledComponents;
7617 enabledComponents = base.enabledComponents;
7618 enabled = base.enabled;
7619 installStatus = base.installStatus;
7620 }
7621
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007622 boolean enableComponentLP(String componentClassName) {
7623 boolean changed = disabledComponents.remove(componentClassName);
7624 changed |= enabledComponents.add(componentClassName);
7625 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 }
7627
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007628 boolean disableComponentLP(String componentClassName) {
7629 boolean changed = enabledComponents.remove(componentClassName);
7630 changed |= disabledComponents.add(componentClassName);
7631 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 }
7633
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007634 boolean restoreComponentLP(String componentClassName) {
7635 boolean changed = enabledComponents.remove(componentClassName);
7636 changed |= disabledComponents.remove(componentClassName);
7637 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 }
7639
7640 int currentEnabledStateLP(String componentName) {
7641 if (enabledComponents.contains(componentName)) {
7642 return COMPONENT_ENABLED_STATE_ENABLED;
7643 } else if (disabledComponents.contains(componentName)) {
7644 return COMPONENT_ENABLED_STATE_DISABLED;
7645 } else {
7646 return COMPONENT_ENABLED_STATE_DEFAULT;
7647 }
7648 }
7649 }
7650
7651 /**
7652 * Settings data for a particular package we know about.
7653 */
7654 static final class PackageSetting extends PackageSettingBase {
7655 int userId;
7656 PackageParser.Package pkg;
7657 SharedUserSetting sharedUser;
7658
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007659 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007660 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007661 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 @Override
7665 public String toString() {
7666 return "PackageSetting{"
7667 + Integer.toHexString(System.identityHashCode(this))
7668 + " " + name + "/" + userId + "}";
7669 }
7670 }
7671
7672 /**
7673 * Settings data for a particular shared user ID we know about.
7674 */
7675 static final class SharedUserSetting extends GrantedPermissions {
7676 final String name;
7677 int userId;
7678 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7679 final PackageSignatures signatures = new PackageSignatures();
7680
7681 SharedUserSetting(String _name, int _pkgFlags) {
7682 super(_pkgFlags);
7683 name = _name;
7684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007686 @Override
7687 public String toString() {
7688 return "SharedUserSetting{"
7689 + Integer.toHexString(System.identityHashCode(this))
7690 + " " + name + "/" + userId + "}";
7691 }
7692 }
7693
7694 /**
7695 * Holds information about dynamic settings.
7696 */
7697 private static final class Settings {
7698 private final File mSettingsFilename;
7699 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007700 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 private final HashMap<String, PackageSetting> mPackages =
7702 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 // List of replaced system applications
7704 final HashMap<String, PackageSetting> mDisabledSysPackages =
7705 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 // The user's preferred activities associated with particular intent
7708 // filters.
7709 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7710 new IntentResolver<PreferredActivity, PreferredActivity>() {
7711 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007712 protected String packageForFilter(PreferredActivity filter) {
7713 return filter.mActivity.getPackageName();
7714 }
7715 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007716 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007718 out.print(prefix); out.print(
7719 Integer.toHexString(System.identityHashCode(filter)));
7720 out.print(' ');
7721 out.print(filter.mActivity.flattenToShortString());
7722 out.print(" match=0x");
7723 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007725 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007727 out.print(prefix); out.print(" ");
7728 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 }
7730 }
7731 }
7732 };
7733 private final HashMap<String, SharedUserSetting> mSharedUsers =
7734 new HashMap<String, SharedUserSetting>();
7735 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7736 private final SparseArray<Object> mOtherUserIds =
7737 new SparseArray<Object>();
7738
7739 // For reading/writing settings file.
7740 private final ArrayList<Signature> mPastSignatures =
7741 new ArrayList<Signature>();
7742
7743 // Mapping from permission names to info about them.
7744 final HashMap<String, BasePermission> mPermissions =
7745 new HashMap<String, BasePermission>();
7746
7747 // Mapping from permission tree names to info about them.
7748 final HashMap<String, BasePermission> mPermissionTrees =
7749 new HashMap<String, BasePermission>();
7750
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007751 // Packages that have been uninstalled and still need their external
7752 // storage data deleted.
7753 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7754
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007755 // Packages that have been renamed since they were first installed.
7756 // Keys are the new names of the packages, values are the original
7757 // names. The packages appear everwhere else under their original
7758 // names.
7759 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 private final StringBuilder mReadMessages = new StringBuilder();
7762
7763 private static final class PendingPackage extends PackageSettingBase {
7764 final int sharedId;
7765
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007766 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007767 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007768 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 this.sharedId = sharedId;
7770 }
7771 }
7772 private final ArrayList<PendingPackage> mPendingPackages
7773 = new ArrayList<PendingPackage>();
7774
7775 Settings() {
7776 File dataDir = Environment.getDataDirectory();
7777 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007778 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 systemDir.mkdirs();
7780 FileUtils.setPermissions(systemDir.toString(),
7781 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7782 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7783 -1, -1);
7784 mSettingsFilename = new File(systemDir, "packages.xml");
7785 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007786 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 }
7788
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007789 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007790 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 int pkgFlags, boolean create, boolean add) {
7792 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007793 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007794 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 return p;
7796 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007797
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007798 PackageSetting peekPackageLP(String name) {
7799 return mPackages.get(name);
7800 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 PackageSetting p = mPackages.get(name);
7802 if (p != null && p.codePath.getPath().equals(codePath)) {
7803 return p;
7804 }
7805 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007806 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 void setInstallStatus(String pkgName, int status) {
7810 PackageSetting p = mPackages.get(pkgName);
7811 if(p != null) {
7812 if(p.getInstallStatus() != status) {
7813 p.setInstallStatus(status);
7814 }
7815 }
7816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007817
Jacek Surazski65e13172009-04-28 15:26:38 +02007818 void setInstallerPackageName(String pkgName,
7819 String installerPkgName) {
7820 PackageSetting p = mPackages.get(pkgName);
7821 if(p != null) {
7822 p.setInstallerPackageName(installerPkgName);
7823 }
7824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007825
Jacek Surazski65e13172009-04-28 15:26:38 +02007826 String getInstallerPackageName(String pkgName) {
7827 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007828 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007829 }
7830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831 int getInstallStatus(String pkgName) {
7832 PackageSetting p = mPackages.get(pkgName);
7833 if(p != null) {
7834 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 return -1;
7837 }
7838
7839 SharedUserSetting getSharedUserLP(String name,
7840 int pkgFlags, boolean create) {
7841 SharedUserSetting s = mSharedUsers.get(name);
7842 if (s == null) {
7843 if (!create) {
7844 return null;
7845 }
7846 s = new SharedUserSetting(name, pkgFlags);
7847 if (MULTIPLE_APPLICATION_UIDS) {
7848 s.userId = newUserIdLP(s);
7849 } else {
7850 s.userId = FIRST_APPLICATION_UID;
7851 }
7852 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7853 // < 0 means we couldn't assign a userid; fall out and return
7854 // s, which is currently null
7855 if (s.userId >= 0) {
7856 mSharedUsers.put(name, s);
7857 }
7858 }
7859
7860 return s;
7861 }
7862
7863 int disableSystemPackageLP(String name) {
7864 PackageSetting p = mPackages.get(name);
7865 if(p == null) {
7866 Log.w(TAG, "Package:"+name+" is not an installed package");
7867 return -1;
7868 }
7869 PackageSetting dp = mDisabledSysPackages.get(name);
7870 // always make sure the system package code and resource paths dont change
7871 if(dp == null) {
7872 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7873 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7874 }
7875 mDisabledSysPackages.put(name, p);
7876 }
7877 return removePackageLP(name);
7878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880 PackageSetting enableSystemPackageLP(String name) {
7881 PackageSetting p = mDisabledSysPackages.get(name);
7882 if(p == null) {
7883 Log.w(TAG, "Package:"+name+" is not disabled");
7884 return null;
7885 }
7886 // Reset flag in ApplicationInfo object
7887 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7888 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7889 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007890 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007891 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 mDisabledSysPackages.remove(name);
7893 return ret;
7894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007895
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007896 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007897 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 PackageSetting p = mPackages.get(name);
7899 if (p != null) {
7900 if (p.userId == uid) {
7901 return p;
7902 }
7903 reportSettingsProblem(Log.ERROR,
7904 "Adding duplicate package, keeping first: " + name);
7905 return null;
7906 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007907 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 p.userId = uid;
7909 if (addUserIdLP(uid, p, name)) {
7910 mPackages.put(name, p);
7911 return p;
7912 }
7913 return null;
7914 }
7915
7916 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7917 SharedUserSetting s = mSharedUsers.get(name);
7918 if (s != null) {
7919 if (s.userId == uid) {
7920 return s;
7921 }
7922 reportSettingsProblem(Log.ERROR,
7923 "Adding duplicate shared user, keeping first: " + name);
7924 return null;
7925 }
7926 s = new SharedUserSetting(name, pkgFlags);
7927 s.userId = uid;
7928 if (addUserIdLP(uid, s, name)) {
7929 mSharedUsers.put(name, s);
7930 return s;
7931 }
7932 return null;
7933 }
7934
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007935 // Transfer ownership of permissions from one package to another.
7936 private void transferPermissions(String origPkg, String newPkg) {
7937 // Transfer ownership of permissions to the new package.
7938 for (int i=0; i<2; i++) {
7939 HashMap<String, BasePermission> permissions =
7940 i == 0 ? mPermissionTrees : mPermissions;
7941 for (BasePermission bp : permissions.values()) {
7942 if (origPkg.equals(bp.sourcePackage)) {
7943 if (DEBUG_UPGRADE) Log.v(TAG,
7944 "Moving permission " + bp.name
7945 + " from pkg " + bp.sourcePackage
7946 + " to " + newPkg);
7947 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007948 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007949 bp.perm = null;
7950 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007951 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007952 }
7953 bp.uid = 0;
7954 bp.gids = null;
7955 }
7956 }
7957 }
7958 }
7959
7960 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007961 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007962 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 PackageSetting p = mPackages.get(name);
7964 if (p != null) {
7965 if (!p.codePath.equals(codePath)) {
7966 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007967 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007968 // This is an updated system app with versions in both system
7969 // and data partition. Just let the most recent version
7970 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007971 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007972 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007973 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007974 // Just a change in the code path is not an issue, but
7975 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007976 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007977 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007979 }
7980 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 reportSettingsProblem(Log.WARN,
7982 "Package " + name + " shared user changed from "
7983 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7984 + " to "
7985 + (sharedUser != null ? sharedUser.name : "<nothing>")
7986 + "; replacing with new");
7987 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007988 } else {
7989 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7990 // If what we are scanning is a system package, then
7991 // make it so, regardless of whether it was previously
7992 // installed only in the data partition.
7993 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 }
7996 }
7997 if (p == null) {
7998 // Create a new PackageSettings entry. this can end up here because
7999 // of code path mismatch or user id mismatch of an updated system partition
8000 if (!create) {
8001 return null;
8002 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008003 if (origPackage != null) {
8004 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008005 p = new PackageSetting(origPackage.name, name, codePath,
8006 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008007 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8008 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008009 // Note that we will retain the new package's signature so
8010 // that we can keep its data.
8011 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008012 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008013 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008014 p.sharedUser = origPackage.sharedUser;
8015 p.userId = origPackage.userId;
8016 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008017 mRenamedPackages.put(name, origPackage.name);
8018 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008019 // Update new package state.
8020 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008022 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008023 p.setTimeStamp(codePath.lastModified());
8024 p.sharedUser = sharedUser;
8025 if (sharedUser != null) {
8026 p.userId = sharedUser.userId;
8027 } else if (MULTIPLE_APPLICATION_UIDS) {
8028 // Clone the setting here for disabled system packages
8029 PackageSetting dis = mDisabledSysPackages.get(name);
8030 if (dis != null) {
8031 // For disabled packages a new setting is created
8032 // from the existing user id. This still has to be
8033 // added to list of user id's
8034 // Copy signatures from previous setting
8035 if (dis.signatures.mSignatures != null) {
8036 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8037 }
8038 p.userId = dis.userId;
8039 // Clone permissions
8040 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008041 // Clone component info
8042 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8043 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8044 // Add new setting to list of user ids
8045 addUserIdLP(p.userId, p, name);
8046 } else {
8047 // Assign new user id
8048 p.userId = newUserIdLP(p);
8049 }
8050 } else {
8051 p.userId = FIRST_APPLICATION_UID;
8052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 }
8054 if (p.userId < 0) {
8055 reportSettingsProblem(Log.WARN,
8056 "Package " + name + " could not be assigned a valid uid");
8057 return null;
8058 }
8059 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008060 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008062 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 }
8064 }
8065 return p;
8066 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008067
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008068 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008069 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008070 String codePath = pkg.applicationInfo.sourceDir;
8071 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008072 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008073 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008074 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008075 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008076 p.codePath = new File(codePath);
8077 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008078 }
8079 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008080 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008081 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008082 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008083 p.resourcePath = new File(resourcePath);
8084 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008085 }
8086 // Update version code if needed
8087 if (pkg.mVersionCode != p.versionCode) {
8088 p.versionCode = pkg.mVersionCode;
8089 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008090 // Update signatures if needed.
8091 if (p.signatures.mSignatures == null) {
8092 p.signatures.assignSignatures(pkg.mSignatures);
8093 }
8094 // If this app defines a shared user id initialize
8095 // the shared user signatures as well.
8096 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8097 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8098 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008099 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8100 }
8101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 // Utility method that adds a PackageSetting to mPackages and
8103 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008104 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 SharedUserSetting sharedUser) {
8106 mPackages.put(name, p);
8107 if (sharedUser != null) {
8108 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8109 reportSettingsProblem(Log.ERROR,
8110 "Package " + p.name + " was user "
8111 + p.sharedUser + " but is now " + sharedUser
8112 + "; I am not changing its files so it will probably fail!");
8113 p.sharedUser.packages.remove(p);
8114 } else if (p.userId != sharedUser.userId) {
8115 reportSettingsProblem(Log.ERROR,
8116 "Package " + p.name + " was user id " + p.userId
8117 + " but is now user " + sharedUser
8118 + " with id " + sharedUser.userId
8119 + "; I am not changing its files so it will probably fail!");
8120 }
8121
8122 sharedUser.packages.add(p);
8123 p.sharedUser = sharedUser;
8124 p.userId = sharedUser.userId;
8125 }
8126 }
8127
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008128 /*
8129 * Update the shared user setting when a package using
8130 * specifying the shared user id is removed. The gids
8131 * associated with each permission of the deleted package
8132 * are removed from the shared user's gid list only if its
8133 * not in use by other permissions of packages in the
8134 * shared user setting.
8135 */
8136 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008138 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 return;
8140 }
8141 // No sharedUserId
8142 if (deletedPs.sharedUser == null) {
8143 return;
8144 }
8145 SharedUserSetting sus = deletedPs.sharedUser;
8146 // Update permissions
8147 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8148 boolean used = false;
8149 if (!sus.grantedPermissions.contains (eachPerm)) {
8150 continue;
8151 }
8152 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008153 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008154 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008155 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 used = true;
8157 break;
8158 }
8159 }
8160 if (!used) {
8161 // can safely delete this permission from list
8162 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 }
8164 }
8165 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008166 int newGids[] = globalGids;
8167 for (String eachPerm : sus.grantedPermissions) {
8168 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008169 if (bp != null) {
8170 newGids = appendInts(newGids, bp.gids);
8171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 }
8173 sus.gids = newGids;
8174 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 private int removePackageLP(String name) {
8177 PackageSetting p = mPackages.get(name);
8178 if (p != null) {
8179 mPackages.remove(name);
8180 if (p.sharedUser != null) {
8181 p.sharedUser.packages.remove(p);
8182 if (p.sharedUser.packages.size() == 0) {
8183 mSharedUsers.remove(p.sharedUser.name);
8184 removeUserIdLP(p.sharedUser.userId);
8185 return p.sharedUser.userId;
8186 }
8187 } else {
8188 removeUserIdLP(p.userId);
8189 return p.userId;
8190 }
8191 }
8192 return -1;
8193 }
8194
8195 private boolean addUserIdLP(int uid, Object obj, Object name) {
8196 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8197 return false;
8198 }
8199
8200 if (uid >= FIRST_APPLICATION_UID) {
8201 int N = mUserIds.size();
8202 final int index = uid - FIRST_APPLICATION_UID;
8203 while (index >= N) {
8204 mUserIds.add(null);
8205 N++;
8206 }
8207 if (mUserIds.get(index) != null) {
8208 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008209 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008210 + " name=" + name);
8211 return false;
8212 }
8213 mUserIds.set(index, obj);
8214 } else {
8215 if (mOtherUserIds.get(uid) != null) {
8216 reportSettingsProblem(Log.ERROR,
8217 "Adding duplicate shared id: " + uid
8218 + " name=" + name);
8219 return false;
8220 }
8221 mOtherUserIds.put(uid, obj);
8222 }
8223 return true;
8224 }
8225
8226 public Object getUserIdLP(int uid) {
8227 if (uid >= FIRST_APPLICATION_UID) {
8228 int N = mUserIds.size();
8229 final int index = uid - FIRST_APPLICATION_UID;
8230 return index < N ? mUserIds.get(index) : null;
8231 } else {
8232 return mOtherUserIds.get(uid);
8233 }
8234 }
8235
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008236 private Set<String> findPackagesWithFlag(int flag) {
8237 Set<String> ret = new HashSet<String>();
8238 for (PackageSetting ps : mPackages.values()) {
8239 // Has to match atleast all the flag bits set on flag
8240 if ((ps.pkgFlags & flag) == flag) {
8241 ret.add(ps.name);
8242 }
8243 }
8244 return ret;
8245 }
8246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008247 private void removeUserIdLP(int uid) {
8248 if (uid >= FIRST_APPLICATION_UID) {
8249 int N = mUserIds.size();
8250 final int index = uid - FIRST_APPLICATION_UID;
8251 if (index < N) mUserIds.set(index, null);
8252 } else {
8253 mOtherUserIds.remove(uid);
8254 }
8255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 void writeLP() {
8258 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8259
8260 // Keep the old settings around until we know the new ones have
8261 // been successfully written.
8262 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008263 // Presence of backup settings file indicates that we failed
8264 // to persist settings earlier. So preserve the older
8265 // backup for future reference since the current settings
8266 // might have been corrupted.
8267 if (!mBackupSettingsFilename.exists()) {
8268 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008269 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008270 return;
8271 }
8272 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008273 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008274 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 }
8277
8278 mPastSignatures.clear();
8279
8280 try {
8281 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8282
8283 //XmlSerializer serializer = XmlUtils.serializerInstance();
8284 XmlSerializer serializer = new FastXmlSerializer();
8285 serializer.setOutput(str, "utf-8");
8286 serializer.startDocument(null, true);
8287 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8288
8289 serializer.startTag(null, "packages");
8290
8291 serializer.startTag(null, "permission-trees");
8292 for (BasePermission bp : mPermissionTrees.values()) {
8293 writePermission(serializer, bp);
8294 }
8295 serializer.endTag(null, "permission-trees");
8296
8297 serializer.startTag(null, "permissions");
8298 for (BasePermission bp : mPermissions.values()) {
8299 writePermission(serializer, bp);
8300 }
8301 serializer.endTag(null, "permissions");
8302
8303 for (PackageSetting pkg : mPackages.values()) {
8304 writePackage(serializer, pkg);
8305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008307 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8308 writeDisabledSysPackage(serializer, pkg);
8309 }
8310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008311 serializer.startTag(null, "preferred-activities");
8312 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8313 serializer.startTag(null, "item");
8314 pa.writeToXml(serializer);
8315 serializer.endTag(null, "item");
8316 }
8317 serializer.endTag(null, "preferred-activities");
8318
8319 for (SharedUserSetting usr : mSharedUsers.values()) {
8320 serializer.startTag(null, "shared-user");
8321 serializer.attribute(null, "name", usr.name);
8322 serializer.attribute(null, "userId",
8323 Integer.toString(usr.userId));
8324 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8325 serializer.startTag(null, "perms");
8326 for (String name : usr.grantedPermissions) {
8327 serializer.startTag(null, "item");
8328 serializer.attribute(null, "name", name);
8329 serializer.endTag(null, "item");
8330 }
8331 serializer.endTag(null, "perms");
8332 serializer.endTag(null, "shared-user");
8333 }
8334
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008335 if (mPackagesToBeCleaned.size() > 0) {
8336 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8337 serializer.startTag(null, "cleaning-package");
8338 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8339 serializer.endTag(null, "cleaning-package");
8340 }
8341 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008342
8343 if (mRenamedPackages.size() > 0) {
8344 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8345 serializer.startTag(null, "renamed-package");
8346 serializer.attribute(null, "new", e.getKey());
8347 serializer.attribute(null, "old", e.getValue());
8348 serializer.endTag(null, "renamed-package");
8349 }
8350 }
8351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 serializer.endTag(null, "packages");
8353
8354 serializer.endDocument();
8355
8356 str.flush();
8357 str.close();
8358
8359 // New settings successfully written, old ones are no longer
8360 // needed.
8361 mBackupSettingsFilename.delete();
8362 FileUtils.setPermissions(mSettingsFilename.toString(),
8363 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8364 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8365 |FileUtils.S_IROTH,
8366 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008367
8368 // Write package list file now, use a JournaledFile.
8369 //
8370 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8371 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8372
8373 str = new FileOutputStream(journal.chooseForWrite());
8374 try {
8375 StringBuilder sb = new StringBuilder();
8376 for (PackageSetting pkg : mPackages.values()) {
8377 ApplicationInfo ai = pkg.pkg.applicationInfo;
8378 String dataPath = ai.dataDir;
8379 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8380
8381 // Avoid any application that has a space in its path
8382 // or that is handled by the system.
8383 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8384 continue;
8385
8386 // we store on each line the following information for now:
8387 //
8388 // pkgName - package name
8389 // userId - application-specific user id
8390 // debugFlag - 0 or 1 if the package is debuggable.
8391 // dataPath - path to package's data path
8392 //
8393 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8394 //
8395 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8396 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8397 // system/core/run-as/run-as.c
8398 //
8399 sb.setLength(0);
8400 sb.append(ai.packageName);
8401 sb.append(" ");
8402 sb.append((int)ai.uid);
8403 sb.append(isDebug ? " 1 " : " 0 ");
8404 sb.append(dataPath);
8405 sb.append("\n");
8406 str.write(sb.toString().getBytes());
8407 }
8408 str.flush();
8409 str.close();
8410 journal.commit();
8411 }
8412 catch (Exception e) {
8413 journal.rollback();
8414 }
8415
8416 FileUtils.setPermissions(mPackageListFilename.toString(),
8417 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8418 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8419 |FileUtils.S_IROTH,
8420 -1, -1);
8421
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008422 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423
8424 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008425 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 -08008426 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008427 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 -08008428 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008429 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008430 if (mSettingsFilename.exists()) {
8431 if (!mSettingsFilename.delete()) {
8432 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8433 }
8434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 //Debug.stopMethodTracing();
8436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008437
8438 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008439 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008440 serializer.startTag(null, "updated-package");
8441 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008442 if (pkg.realName != null) {
8443 serializer.attribute(null, "realName", pkg.realName);
8444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 serializer.attribute(null, "codePath", pkg.codePathString);
8446 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008447 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008448 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8449 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8450 }
8451 if (pkg.sharedUser == null) {
8452 serializer.attribute(null, "userId",
8453 Integer.toString(pkg.userId));
8454 } else {
8455 serializer.attribute(null, "sharedUserId",
8456 Integer.toString(pkg.userId));
8457 }
8458 serializer.startTag(null, "perms");
8459 if (pkg.sharedUser == null) {
8460 // If this is a shared user, the permissions will
8461 // be written there. We still need to write an
8462 // empty permissions list so permissionsFixed will
8463 // be set.
8464 for (final String name : pkg.grantedPermissions) {
8465 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008466 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 // We only need to write signature or system permissions but this wont
8468 // match the semantics of grantedPermissions. So write all permissions.
8469 serializer.startTag(null, "item");
8470 serializer.attribute(null, "name", name);
8471 serializer.endTag(null, "item");
8472 }
8473 }
8474 }
8475 serializer.endTag(null, "perms");
8476 serializer.endTag(null, "updated-package");
8477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008478
8479 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008480 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 serializer.startTag(null, "package");
8482 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008483 if (pkg.realName != null) {
8484 serializer.attribute(null, "realName", pkg.realName);
8485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 serializer.attribute(null, "codePath", pkg.codePathString);
8487 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8488 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8489 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008490 serializer.attribute(null, "flags",
8491 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008492 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008493 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 if (pkg.sharedUser == null) {
8495 serializer.attribute(null, "userId",
8496 Integer.toString(pkg.userId));
8497 } else {
8498 serializer.attribute(null, "sharedUserId",
8499 Integer.toString(pkg.userId));
8500 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008501 if (pkg.uidError) {
8502 serializer.attribute(null, "uidError", "true");
8503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8505 serializer.attribute(null, "enabled",
8506 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8507 ? "true" : "false");
8508 }
8509 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8510 serializer.attribute(null, "installStatus", "false");
8511 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008512 if (pkg.installerPackageName != null) {
8513 serializer.attribute(null, "installer", pkg.installerPackageName);
8514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8516 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8517 serializer.startTag(null, "perms");
8518 if (pkg.sharedUser == null) {
8519 // If this is a shared user, the permissions will
8520 // be written there. We still need to write an
8521 // empty permissions list so permissionsFixed will
8522 // be set.
8523 for (final String name : pkg.grantedPermissions) {
8524 serializer.startTag(null, "item");
8525 serializer.attribute(null, "name", name);
8526 serializer.endTag(null, "item");
8527 }
8528 }
8529 serializer.endTag(null, "perms");
8530 }
8531 if (pkg.disabledComponents.size() > 0) {
8532 serializer.startTag(null, "disabled-components");
8533 for (final String name : pkg.disabledComponents) {
8534 serializer.startTag(null, "item");
8535 serializer.attribute(null, "name", name);
8536 serializer.endTag(null, "item");
8537 }
8538 serializer.endTag(null, "disabled-components");
8539 }
8540 if (pkg.enabledComponents.size() > 0) {
8541 serializer.startTag(null, "enabled-components");
8542 for (final String name : pkg.enabledComponents) {
8543 serializer.startTag(null, "item");
8544 serializer.attribute(null, "name", name);
8545 serializer.endTag(null, "item");
8546 }
8547 serializer.endTag(null, "enabled-components");
8548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 serializer.endTag(null, "package");
8551 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 void writePermission(XmlSerializer serializer, BasePermission bp)
8554 throws XmlPullParserException, java.io.IOException {
8555 if (bp.type != BasePermission.TYPE_BUILTIN
8556 && bp.sourcePackage != null) {
8557 serializer.startTag(null, "item");
8558 serializer.attribute(null, "name", bp.name);
8559 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008560 if (bp.protectionLevel !=
8561 PermissionInfo.PROTECTION_NORMAL) {
8562 serializer.attribute(null, "protection",
8563 Integer.toString(bp.protectionLevel));
8564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 if (DEBUG_SETTINGS) Log.v(TAG,
8566 "Writing perm: name=" + bp.name + " type=" + bp.type);
8567 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8568 PermissionInfo pi = bp.perm != null ? bp.perm.info
8569 : bp.pendingInfo;
8570 if (pi != null) {
8571 serializer.attribute(null, "type", "dynamic");
8572 if (pi.icon != 0) {
8573 serializer.attribute(null, "icon",
8574 Integer.toString(pi.icon));
8575 }
8576 if (pi.nonLocalizedLabel != null) {
8577 serializer.attribute(null, "label",
8578 pi.nonLocalizedLabel.toString());
8579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 }
8581 }
8582 serializer.endTag(null, "item");
8583 }
8584 }
8585
8586 String getReadMessagesLP() {
8587 return mReadMessages.toString();
8588 }
8589
Oscar Montemayora8529f62009-11-18 10:14:20 -08008590 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8592 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008593 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008594 while(its.hasNext()) {
8595 String key = its.next();
8596 PackageSetting ps = mPackages.get(key);
8597 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008598 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 }
8600 }
8601 return ret;
8602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008604 boolean readLP() {
8605 FileInputStream str = null;
8606 if (mBackupSettingsFilename.exists()) {
8607 try {
8608 str = new FileInputStream(mBackupSettingsFilename);
8609 mReadMessages.append("Reading from backup settings file\n");
8610 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008611 if (mSettingsFilename.exists()) {
8612 // If both the backup and settings file exist, we
8613 // ignore the settings since it might have been
8614 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008615 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008616 mSettingsFilename.delete();
8617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 } catch (java.io.IOException e) {
8619 // We'll try for the normal settings file.
8620 }
8621 }
8622
8623 mPastSignatures.clear();
8624
8625 try {
8626 if (str == null) {
8627 if (!mSettingsFilename.exists()) {
8628 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008629 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 return false;
8631 }
8632 str = new FileInputStream(mSettingsFilename);
8633 }
8634 XmlPullParser parser = Xml.newPullParser();
8635 parser.setInput(str, null);
8636
8637 int type;
8638 while ((type=parser.next()) != XmlPullParser.START_TAG
8639 && type != XmlPullParser.END_DOCUMENT) {
8640 ;
8641 }
8642
8643 if (type != XmlPullParser.START_TAG) {
8644 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008645 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 return false;
8647 }
8648
8649 int outerDepth = parser.getDepth();
8650 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8651 && (type != XmlPullParser.END_TAG
8652 || parser.getDepth() > outerDepth)) {
8653 if (type == XmlPullParser.END_TAG
8654 || type == XmlPullParser.TEXT) {
8655 continue;
8656 }
8657
8658 String tagName = parser.getName();
8659 if (tagName.equals("package")) {
8660 readPackageLP(parser);
8661 } else if (tagName.equals("permissions")) {
8662 readPermissionsLP(mPermissions, parser);
8663 } else if (tagName.equals("permission-trees")) {
8664 readPermissionsLP(mPermissionTrees, parser);
8665 } else if (tagName.equals("shared-user")) {
8666 readSharedUserLP(parser);
8667 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008668 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 } else if (tagName.equals("preferred-activities")) {
8670 readPreferredActivitiesLP(parser);
8671 } else if(tagName.equals("updated-package")) {
8672 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008673 } else if (tagName.equals("cleaning-package")) {
8674 String name = parser.getAttributeValue(null, "name");
8675 if (name != null) {
8676 mPackagesToBeCleaned.add(name);
8677 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008678 } else if (tagName.equals("renamed-package")) {
8679 String nname = parser.getAttributeValue(null, "new");
8680 String oname = parser.getAttributeValue(null, "old");
8681 if (nname != null && oname != null) {
8682 mRenamedPackages.put(nname, oname);
8683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008685 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 + parser.getName());
8687 XmlUtils.skipCurrentTag(parser);
8688 }
8689 }
8690
8691 str.close();
8692
8693 } catch(XmlPullParserException e) {
8694 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008695 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696
8697 } catch(java.io.IOException e) {
8698 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008699 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700
8701 }
8702
8703 int N = mPendingPackages.size();
8704 for (int i=0; i<N; i++) {
8705 final PendingPackage pp = mPendingPackages.get(i);
8706 Object idObj = getUserIdLP(pp.sharedId);
8707 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008708 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008710 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008712 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 + pp.name);
8714 continue;
8715 }
8716 p.copyFrom(pp);
8717 } else if (idObj != null) {
8718 String msg = "Bad package setting: package " + pp.name
8719 + " has shared uid " + pp.sharedId
8720 + " that is not a shared uid\n";
8721 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008722 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 } else {
8724 String msg = "Bad package setting: package " + pp.name
8725 + " has shared uid " + pp.sharedId
8726 + " that is not defined\n";
8727 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008728 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 }
8730 }
8731 mPendingPackages.clear();
8732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 mReadMessages.append("Read completed successfully: "
8734 + mPackages.size() + " packages, "
8735 + mSharedUsers.size() + " shared uids\n");
8736
8737 return true;
8738 }
8739
8740 private int readInt(XmlPullParser parser, String ns, String name,
8741 int defValue) {
8742 String v = parser.getAttributeValue(ns, name);
8743 try {
8744 if (v == null) {
8745 return defValue;
8746 }
8747 return Integer.parseInt(v);
8748 } catch (NumberFormatException e) {
8749 reportSettingsProblem(Log.WARN,
8750 "Error in package manager settings: attribute " +
8751 name + " has bad integer value " + v + " at "
8752 + parser.getPositionDescription());
8753 }
8754 return defValue;
8755 }
8756
8757 private void readPermissionsLP(HashMap<String, BasePermission> out,
8758 XmlPullParser parser)
8759 throws IOException, XmlPullParserException {
8760 int outerDepth = parser.getDepth();
8761 int type;
8762 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8763 && (type != XmlPullParser.END_TAG
8764 || parser.getDepth() > outerDepth)) {
8765 if (type == XmlPullParser.END_TAG
8766 || type == XmlPullParser.TEXT) {
8767 continue;
8768 }
8769
8770 String tagName = parser.getName();
8771 if (tagName.equals("item")) {
8772 String name = parser.getAttributeValue(null, "name");
8773 String sourcePackage = parser.getAttributeValue(null, "package");
8774 String ptype = parser.getAttributeValue(null, "type");
8775 if (name != null && sourcePackage != null) {
8776 boolean dynamic = "dynamic".equals(ptype);
8777 BasePermission bp = new BasePermission(name, sourcePackage,
8778 dynamic
8779 ? BasePermission.TYPE_DYNAMIC
8780 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008781 bp.protectionLevel = readInt(parser, null, "protection",
8782 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 if (dynamic) {
8784 PermissionInfo pi = new PermissionInfo();
8785 pi.packageName = sourcePackage.intern();
8786 pi.name = name.intern();
8787 pi.icon = readInt(parser, null, "icon", 0);
8788 pi.nonLocalizedLabel = parser.getAttributeValue(
8789 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008790 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791 bp.pendingInfo = pi;
8792 }
8793 out.put(bp.name, bp);
8794 } else {
8795 reportSettingsProblem(Log.WARN,
8796 "Error in package manager settings: permissions has"
8797 + " no name at " + parser.getPositionDescription());
8798 }
8799 } else {
8800 reportSettingsProblem(Log.WARN,
8801 "Unknown element reading permissions: "
8802 + parser.getName() + " at "
8803 + parser.getPositionDescription());
8804 }
8805 XmlUtils.skipCurrentTag(parser);
8806 }
8807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008810 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008812 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008813 String codePathStr = parser.getAttributeValue(null, "codePath");
8814 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008815 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 resourcePathStr = codePathStr;
8817 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008818 String version = parser.getAttributeValue(null, "version");
8819 int versionCode = 0;
8820 if (version != null) {
8821 try {
8822 versionCode = Integer.parseInt(version);
8823 } catch (NumberFormatException e) {
8824 }
8825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 int pkgFlags = 0;
8828 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008829 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008830 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008831 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 String timeStampStr = parser.getAttributeValue(null, "ts");
8833 if (timeStampStr != null) {
8834 try {
8835 long timeStamp = Long.parseLong(timeStampStr);
8836 ps.setTimeStamp(timeStamp, timeStampStr);
8837 } catch (NumberFormatException e) {
8838 }
8839 }
8840 String idStr = parser.getAttributeValue(null, "userId");
8841 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8842 if(ps.userId <= 0) {
8843 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8844 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8845 }
8846 int outerDepth = parser.getDepth();
8847 int type;
8848 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8849 && (type != XmlPullParser.END_TAG
8850 || parser.getDepth() > outerDepth)) {
8851 if (type == XmlPullParser.END_TAG
8852 || type == XmlPullParser.TEXT) {
8853 continue;
8854 }
8855
8856 String tagName = parser.getName();
8857 if (tagName.equals("perms")) {
8858 readGrantedPermissionsLP(parser,
8859 ps.grantedPermissions);
8860 } else {
8861 reportSettingsProblem(Log.WARN,
8862 "Unknown element under <updated-package>: "
8863 + parser.getName());
8864 XmlUtils.skipCurrentTag(parser);
8865 }
8866 }
8867 mDisabledSysPackages.put(name, ps);
8868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 private void readPackageLP(XmlPullParser parser)
8871 throws XmlPullParserException, IOException {
8872 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008873 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874 String idStr = null;
8875 String sharedIdStr = null;
8876 String codePathStr = null;
8877 String resourcePathStr = null;
8878 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008879 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008880 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 int pkgFlags = 0;
8882 String timeStampStr;
8883 long timeStamp = 0;
8884 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008885 String version = null;
8886 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 try {
8888 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008889 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008891 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8893 codePathStr = parser.getAttributeValue(null, "codePath");
8894 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008895 version = parser.getAttributeValue(null, "version");
8896 if (version != null) {
8897 try {
8898 versionCode = Integer.parseInt(version);
8899 } catch (NumberFormatException e) {
8900 }
8901 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008902 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008903
8904 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008906 try {
8907 pkgFlags = Integer.parseInt(systemStr);
8908 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008909 }
8910 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008911 // For backward compatibility
8912 systemStr = parser.getAttributeValue(null, "system");
8913 if (systemStr != null) {
8914 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8915 } else {
8916 // Old settings that don't specify system... just treat
8917 // them as system, good enough.
8918 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 }
8921 timeStampStr = parser.getAttributeValue(null, "ts");
8922 if (timeStampStr != null) {
8923 try {
8924 timeStamp = Long.parseLong(timeStampStr);
8925 } catch (NumberFormatException e) {
8926 }
8927 }
8928 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8929 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8930 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8931 if (resourcePathStr == null) {
8932 resourcePathStr = codePathStr;
8933 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008934 if (realName != null) {
8935 realName = realName.intern();
8936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 if (name == null) {
8938 reportSettingsProblem(Log.WARN,
8939 "Error in package manager settings: <package> has no name at "
8940 + parser.getPositionDescription());
8941 } else if (codePathStr == null) {
8942 reportSettingsProblem(Log.WARN,
8943 "Error in package manager settings: <package> has no codePath at "
8944 + parser.getPositionDescription());
8945 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008946 packageSetting = addPackageLP(name.intern(), realName,
8947 new File(codePathStr), new File(resourcePathStr),
8948 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8950 + ": userId=" + userId + " pkg=" + packageSetting);
8951 if (packageSetting == null) {
8952 reportSettingsProblem(Log.ERROR,
8953 "Failure adding uid " + userId
8954 + " while parsing settings at "
8955 + parser.getPositionDescription());
8956 } else {
8957 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8958 }
8959 } else if (sharedIdStr != null) {
8960 userId = sharedIdStr != null
8961 ? Integer.parseInt(sharedIdStr) : 0;
8962 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008963 packageSetting = new PendingPackage(name.intern(), realName,
8964 new File(codePathStr), new File(resourcePathStr),
8965 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8967 mPendingPackages.add((PendingPackage) packageSetting);
8968 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8969 + ": sharedUserId=" + userId + " pkg="
8970 + packageSetting);
8971 } else {
8972 reportSettingsProblem(Log.WARN,
8973 "Error in package manager settings: package "
8974 + name + " has bad sharedId " + sharedIdStr
8975 + " at " + parser.getPositionDescription());
8976 }
8977 } else {
8978 reportSettingsProblem(Log.WARN,
8979 "Error in package manager settings: package "
8980 + name + " has bad userId " + idStr + " at "
8981 + parser.getPositionDescription());
8982 }
8983 } catch (NumberFormatException e) {
8984 reportSettingsProblem(Log.WARN,
8985 "Error in package manager settings: package "
8986 + name + " has bad userId " + idStr + " at "
8987 + parser.getPositionDescription());
8988 }
8989 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008990 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008991 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008992 final String enabledStr = parser.getAttributeValue(null, "enabled");
8993 if (enabledStr != null) {
8994 if (enabledStr.equalsIgnoreCase("true")) {
8995 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8996 } else if (enabledStr.equalsIgnoreCase("false")) {
8997 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8998 } else if (enabledStr.equalsIgnoreCase("default")) {
8999 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9000 } else {
9001 reportSettingsProblem(Log.WARN,
9002 "Error in package manager settings: package "
9003 + name + " has bad enabled value: " + idStr
9004 + " at " + parser.getPositionDescription());
9005 }
9006 } else {
9007 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9008 }
9009 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9010 if (installStatusStr != null) {
9011 if (installStatusStr.equalsIgnoreCase("false")) {
9012 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9013 } else {
9014 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9015 }
9016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018 int outerDepth = parser.getDepth();
9019 int type;
9020 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9021 && (type != XmlPullParser.END_TAG
9022 || parser.getDepth() > outerDepth)) {
9023 if (type == XmlPullParser.END_TAG
9024 || type == XmlPullParser.TEXT) {
9025 continue;
9026 }
9027
9028 String tagName = parser.getName();
9029 if (tagName.equals("disabled-components")) {
9030 readDisabledComponentsLP(packageSetting, parser);
9031 } else if (tagName.equals("enabled-components")) {
9032 readEnabledComponentsLP(packageSetting, parser);
9033 } else if (tagName.equals("sigs")) {
9034 packageSetting.signatures.readXml(parser, mPastSignatures);
9035 } else if (tagName.equals("perms")) {
9036 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009037 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 packageSetting.permissionsFixed = true;
9039 } else {
9040 reportSettingsProblem(Log.WARN,
9041 "Unknown element under <package>: "
9042 + parser.getName());
9043 XmlUtils.skipCurrentTag(parser);
9044 }
9045 }
9046 } else {
9047 XmlUtils.skipCurrentTag(parser);
9048 }
9049 }
9050
9051 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9052 XmlPullParser parser)
9053 throws IOException, XmlPullParserException {
9054 int outerDepth = parser.getDepth();
9055 int type;
9056 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9057 && (type != XmlPullParser.END_TAG
9058 || parser.getDepth() > outerDepth)) {
9059 if (type == XmlPullParser.END_TAG
9060 || type == XmlPullParser.TEXT) {
9061 continue;
9062 }
9063
9064 String tagName = parser.getName();
9065 if (tagName.equals("item")) {
9066 String name = parser.getAttributeValue(null, "name");
9067 if (name != null) {
9068 packageSetting.disabledComponents.add(name.intern());
9069 } else {
9070 reportSettingsProblem(Log.WARN,
9071 "Error in package manager settings: <disabled-components> has"
9072 + " no name at " + parser.getPositionDescription());
9073 }
9074 } else {
9075 reportSettingsProblem(Log.WARN,
9076 "Unknown element under <disabled-components>: "
9077 + parser.getName());
9078 }
9079 XmlUtils.skipCurrentTag(parser);
9080 }
9081 }
9082
9083 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9084 XmlPullParser parser)
9085 throws IOException, XmlPullParserException {
9086 int outerDepth = parser.getDepth();
9087 int type;
9088 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9089 && (type != XmlPullParser.END_TAG
9090 || parser.getDepth() > outerDepth)) {
9091 if (type == XmlPullParser.END_TAG
9092 || type == XmlPullParser.TEXT) {
9093 continue;
9094 }
9095
9096 String tagName = parser.getName();
9097 if (tagName.equals("item")) {
9098 String name = parser.getAttributeValue(null, "name");
9099 if (name != null) {
9100 packageSetting.enabledComponents.add(name.intern());
9101 } else {
9102 reportSettingsProblem(Log.WARN,
9103 "Error in package manager settings: <enabled-components> has"
9104 + " no name at " + parser.getPositionDescription());
9105 }
9106 } else {
9107 reportSettingsProblem(Log.WARN,
9108 "Unknown element under <enabled-components>: "
9109 + parser.getName());
9110 }
9111 XmlUtils.skipCurrentTag(parser);
9112 }
9113 }
9114
9115 private void readSharedUserLP(XmlPullParser parser)
9116 throws XmlPullParserException, IOException {
9117 String name = null;
9118 String idStr = null;
9119 int pkgFlags = 0;
9120 SharedUserSetting su = null;
9121 try {
9122 name = parser.getAttributeValue(null, "name");
9123 idStr = parser.getAttributeValue(null, "userId");
9124 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9125 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9126 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9127 }
9128 if (name == null) {
9129 reportSettingsProblem(Log.WARN,
9130 "Error in package manager settings: <shared-user> has no name at "
9131 + parser.getPositionDescription());
9132 } else if (userId == 0) {
9133 reportSettingsProblem(Log.WARN,
9134 "Error in package manager settings: shared-user "
9135 + name + " has bad userId " + idStr + " at "
9136 + parser.getPositionDescription());
9137 } else {
9138 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9139 reportSettingsProblem(Log.ERROR,
9140 "Occurred while parsing settings at "
9141 + parser.getPositionDescription());
9142 }
9143 }
9144 } catch (NumberFormatException e) {
9145 reportSettingsProblem(Log.WARN,
9146 "Error in package manager settings: package "
9147 + name + " has bad userId " + idStr + " at "
9148 + parser.getPositionDescription());
9149 };
9150
9151 if (su != null) {
9152 int outerDepth = parser.getDepth();
9153 int type;
9154 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9155 && (type != XmlPullParser.END_TAG
9156 || parser.getDepth() > outerDepth)) {
9157 if (type == XmlPullParser.END_TAG
9158 || type == XmlPullParser.TEXT) {
9159 continue;
9160 }
9161
9162 String tagName = parser.getName();
9163 if (tagName.equals("sigs")) {
9164 su.signatures.readXml(parser, mPastSignatures);
9165 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009166 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 } else {
9168 reportSettingsProblem(Log.WARN,
9169 "Unknown element under <shared-user>: "
9170 + parser.getName());
9171 XmlUtils.skipCurrentTag(parser);
9172 }
9173 }
9174
9175 } else {
9176 XmlUtils.skipCurrentTag(parser);
9177 }
9178 }
9179
9180 private void readGrantedPermissionsLP(XmlPullParser parser,
9181 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9182 int outerDepth = parser.getDepth();
9183 int type;
9184 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9185 && (type != XmlPullParser.END_TAG
9186 || parser.getDepth() > outerDepth)) {
9187 if (type == XmlPullParser.END_TAG
9188 || type == XmlPullParser.TEXT) {
9189 continue;
9190 }
9191
9192 String tagName = parser.getName();
9193 if (tagName.equals("item")) {
9194 String name = parser.getAttributeValue(null, "name");
9195 if (name != null) {
9196 outPerms.add(name.intern());
9197 } else {
9198 reportSettingsProblem(Log.WARN,
9199 "Error in package manager settings: <perms> has"
9200 + " no name at " + parser.getPositionDescription());
9201 }
9202 } else {
9203 reportSettingsProblem(Log.WARN,
9204 "Unknown element under <perms>: "
9205 + parser.getName());
9206 }
9207 XmlUtils.skipCurrentTag(parser);
9208 }
9209 }
9210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211 private void readPreferredActivitiesLP(XmlPullParser parser)
9212 throws XmlPullParserException, IOException {
9213 int outerDepth = parser.getDepth();
9214 int type;
9215 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9216 && (type != XmlPullParser.END_TAG
9217 || parser.getDepth() > outerDepth)) {
9218 if (type == XmlPullParser.END_TAG
9219 || type == XmlPullParser.TEXT) {
9220 continue;
9221 }
9222
9223 String tagName = parser.getName();
9224 if (tagName.equals("item")) {
9225 PreferredActivity pa = new PreferredActivity(parser);
9226 if (pa.mParseError == null) {
9227 mPreferredActivities.addFilter(pa);
9228 } else {
9229 reportSettingsProblem(Log.WARN,
9230 "Error in package manager settings: <preferred-activity> "
9231 + pa.mParseError + " at "
9232 + parser.getPositionDescription());
9233 }
9234 } else {
9235 reportSettingsProblem(Log.WARN,
9236 "Unknown element under <preferred-activities>: "
9237 + parser.getName());
9238 XmlUtils.skipCurrentTag(parser);
9239 }
9240 }
9241 }
9242
9243 // Returns -1 if we could not find an available UserId to assign
9244 private int newUserIdLP(Object obj) {
9245 // Let's be stupidly inefficient for now...
9246 final int N = mUserIds.size();
9247 for (int i=0; i<N; i++) {
9248 if (mUserIds.get(i) == null) {
9249 mUserIds.set(i, obj);
9250 return FIRST_APPLICATION_UID + i;
9251 }
9252 }
9253
9254 // None left?
9255 if (N >= MAX_APPLICATION_UIDS) {
9256 return -1;
9257 }
9258
9259 mUserIds.add(obj);
9260 return FIRST_APPLICATION_UID + N;
9261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263 public PackageSetting getDisabledSystemPkg(String name) {
9264 synchronized(mPackages) {
9265 PackageSetting ps = mDisabledSysPackages.get(name);
9266 return ps;
9267 }
9268 }
9269
9270 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9271 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9272 if (Config.LOGV) {
9273 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9274 + " componentName = " + componentInfo.name);
9275 Log.v(TAG, "enabledComponents: "
9276 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9277 Log.v(TAG, "disabledComponents: "
9278 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9279 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009280 if (packageSettings == null) {
9281 if (false) {
9282 Log.w(TAG, "WAITING FOR DEBUGGER");
9283 Debug.waitForDebugger();
9284 Log.i(TAG, "We will crash!");
9285 }
9286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9288 || ((componentInfo.enabled
9289 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9290 || (componentInfo.applicationInfo.enabled
9291 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9292 && !packageSettings.disabledComponents.contains(componentInfo.name))
9293 || packageSettings.enabledComponents.contains(componentInfo.name));
9294 }
9295 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009296
9297 // ------- apps on sdcard specific code -------
9298 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009299 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009300 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009301 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009302 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009303
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009304 private String getEncryptKey() {
9305 try {
9306 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9307 if (sdEncKey == null) {
9308 sdEncKey = SystemKeyStore.getInstance().
9309 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9310 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009311 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009312 return null;
9313 }
9314 }
9315 return sdEncKey;
9316 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009317 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009318 return null;
9319 }
9320 }
9321
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009322 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009323 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009324 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009325 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009326 if (list != null) {
9327 int idx = 0;
9328 int idList[] = new int[MAX_CONTAINERS];
9329 boolean neverFound = true;
9330 for (String name : list) {
9331 // Ignore null entries
9332 if (name == null) {
9333 continue;
9334 }
9335 int sidx = name.indexOf(prefix);
9336 if (sidx == -1) {
9337 // Not a temp file. just ignore
9338 continue;
9339 }
9340 String subStr = name.substring(sidx + prefix.length());
9341 idList[idx] = -1;
9342 if (subStr != null) {
9343 try {
9344 int cid = Integer.parseInt(subStr);
9345 idList[idx++] = cid;
9346 neverFound = false;
9347 } catch (NumberFormatException e) {
9348 }
9349 }
9350 }
9351 if (!neverFound) {
9352 // Sort idList
9353 Arrays.sort(idList);
9354 for (int j = 1; j <= idList.length; j++) {
9355 if (idList[j-1] != j) {
9356 tmpIdx = j;
9357 break;
9358 }
9359 }
9360 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009361 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009362 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009363 }
9364
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009365 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009366 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009367 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009368 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9369 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9370 throw new SecurityException("Media status can only be updated by the system");
9371 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009372 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009373 Log.i(TAG, "Updating external media status from " +
9374 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9375 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009376 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9377 mediaStatus+", mMediaMounted=" + mMediaMounted);
9378 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009379 if (reportStatus) {
9380 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9381 }
9382 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009383 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009384 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009385 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009386 // Queue up an async operation since the package installation may take a little while.
9387 mHandler.post(new Runnable() {
9388 public void run() {
9389 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009390 try {
9391 updateExternalMediaStatusInner(mediaStatus);
9392 } finally {
9393 if (reportStatus) {
9394 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9395 }
9396 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009397 }
9398 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009399 }
9400
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009401 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009402 // If we are up here that means there are packages to be
9403 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009404 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009405 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009406 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009407 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009408 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009409
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009410 int uidList[] = new int[list.length];
9411 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009412 HashSet<String> removeCids = new HashSet<String>();
9413 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009414 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009415 for (String cid : list) {
9416 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009417 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9418 boolean failed = true;
9419 try {
9420 String pkgName = args.getPackageName();
9421 if (pkgName == null) {
9422 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009423 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009424 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9425 PackageSetting ps = mSettings.mPackages.get(pkgName);
9426 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009427 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009428 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9429 " corresponds to pkg : " + pkgName +
9430 " at code path: " + ps.codePathString);
9431 // We do have a valid package installed on sdcard
9432 processCids.put(args, ps.codePathString);
9433 failed = false;
9434 int uid = ps.userId;
9435 if (uid != -1) {
9436 uidList[num++] = uid;
9437 }
9438 }
9439 } finally {
9440 if (failed) {
9441 // Stale container on sdcard. Just delete
9442 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9443 removeCids.add(cid);
9444 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009445 }
9446 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009447 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009448 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009449 int uidArr[] = null;
9450 if (num > 0) {
9451 // Sort uid list
9452 Arrays.sort(uidList, 0, num);
9453 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009454 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009455 uidArr[0] = uidList[0];
9456 int di = 0;
9457 for (int i = 1; i < num; i++) {
9458 if (uidList[i-1] != uidList[i]) {
9459 uidArr[di++] = uidList[i];
9460 }
9461 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009462 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009463 // Process packages with valid entries.
9464 if (mediaStatus) {
9465 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009466 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009467 startCleaningPackages();
9468 } else {
9469 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009470 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009471 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009472 }
9473
9474 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9475 ArrayList<String> pkgList, int uidArr[]) {
9476 int size = pkgList.size();
9477 if (size > 0) {
9478 // Send broadcasts here
9479 Bundle extras = new Bundle();
9480 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9481 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009482 if (uidArr != null) {
9483 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9484 }
9485 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9486 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009487 sendPackageBroadcast(action, null, extras);
9488 }
9489 }
9490
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009491 /*
9492 * Look at potentially valid container ids from processCids
9493 * If package information doesn't match the one on record
9494 * or package scanning fails, the cid is added to list of
9495 * removeCids and cleaned up. Since cleaning up containers
9496 * involves destroying them, we do not want any parse
9497 * references to such stale containers. So force gc's
9498 * to avoid unnecessary crashes.
9499 */
9500 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009501 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009502 ArrayList<String> pkgList = new ArrayList<String>();
9503 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009504 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009505 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009506 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9508 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009509 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009510 try {
9511 // Make sure there are no container errors first.
9512 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9513 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009514 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009515 " when installing from sdcard");
9516 continue;
9517 }
9518 // Check code path here.
9519 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009520 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009521 " does not match one in settings " + codePath);
9522 continue;
9523 }
9524 // Parse package
9525 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009526 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009528 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009529 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9530 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009531 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009532 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009533 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009534 retCode = PackageManager.INSTALL_SUCCEEDED;
9535 pkgList.add(pkg.packageName);
9536 // Post process args
9537 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9538 }
9539 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009540 Slog.i(TAG, "Failed to install pkg from " +
9541 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009542 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009543 }
9544
9545 } finally {
9546 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9547 // Don't destroy container here. Wait till gc clears things up.
9548 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009549 }
9550 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009551 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009552 synchronized (mPackages) {
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009553 // Make sure group IDs have been assigned, and any permission
9554 // changes in other apps are accounted for
9555 updatePermissionsLP(null, null, true, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009556 // Persist settings
9557 mSettings.writeLP();
9558 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009559 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009560 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9562 }
9563 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009564 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009565 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009566 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 if (removeCids != null) {
9568 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009569 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009571 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 }
9573
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009575 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009576 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009577 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009578 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009579 Set<SdInstallArgs> keys = processCids.keySet();
9580 for (SdInstallArgs args : keys) {
9581 String cid = args.cid;
9582 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009583 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009584 // Delete package internally
9585 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9586 synchronized (mInstallLock) {
9587 boolean res = deletePackageLI(pkgName, false,
9588 PackageManager.DONT_DELETE_DATA, outInfo);
9589 if (res) {
9590 pkgList.add(pkgName);
9591 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009592 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009593 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009594 }
9595 }
9596 }
9597 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009598 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009599 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009600 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009601 // Force gc
9602 Runtime.getRuntime().gc();
9603 // Just unmount all valid containers.
9604 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 synchronized (mInstallLock) {
9606 args.doPostDeleteLI(false);
9607 }
9608 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009609 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009610
9611 public void movePackage(final String packageName,
9612 final IPackageMoveObserver observer, final int flags) {
9613 if (packageName == null) {
9614 return;
9615 }
9616 mContext.enforceCallingOrSelfPermission(
9617 android.Manifest.permission.MOVE_PACKAGE, null);
9618 int returnCode = PackageManager.MOVE_SUCCEEDED;
9619 int currFlags = 0;
9620 int newFlags = 0;
9621 synchronized (mPackages) {
9622 PackageParser.Package pkg = mPackages.get(packageName);
9623 if (pkg == null) {
9624 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9625 }
9626 // Disable moving fwd locked apps and system packages
9627 if (pkg.applicationInfo != null &&
9628 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009629 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009630 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9631 } else if (pkg.applicationInfo != null &&
9632 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009633 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009634 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9635 } else {
9636 // Find install location first
9637 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9638 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009639 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009640 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9641 } else {
9642 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9643 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009644 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009645 PackageManager.INSTALL_EXTERNAL : 0;
9646 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009647 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009648 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9649 }
9650 }
9651 }
9652 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9653 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9654 } else {
9655 Message msg = mHandler.obtainMessage(INIT_COPY);
9656 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9657 pkg.applicationInfo.publicSourceDir);
9658 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9659 packageName);
9660 msg.obj = mp;
9661 mHandler.sendMessage(msg);
9662 }
9663 }
9664 }
9665
9666 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9667 // Queue up an async operation since the package deletion may take a little while.
9668 mHandler.post(new Runnable() {
9669 public void run() {
9670 mHandler.removeCallbacks(this);
9671 int returnCode = currentStatus;
9672 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9673 if (moveSucceeded) {
9674 int uid = -1;
9675 synchronized (mPackages) {
9676 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9677 }
9678 ArrayList<String> pkgList = new ArrayList<String>();
9679 pkgList.add(mp.packageName);
9680 int uidArr[] = new int[] { uid };
9681 // Send resources unavailable broadcast
9682 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9683
9684 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009685 synchronized (mInstallLock) {
9686 synchronized (mPackages) {
9687 PackageParser.Package pkg = mPackages.get(mp.packageName);
9688 if (pkg != null) {
9689 String oldCodePath = pkg.mPath;
9690 String newCodePath = mp.targetArgs.getCodePath();
9691 String newResPath = mp.targetArgs.getResourcePath();
9692 pkg.mPath = newCodePath;
9693 // Move dex files around
9694 if (moveDexFilesLI(pkg)
9695 != PackageManager.INSTALL_SUCCEEDED) {
9696 // Moving of dex files failed. Set
9697 // error code and abort move.
9698 pkg.mPath = pkg.mScanPath;
9699 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9700 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009701 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009702 pkg.mScanPath = newCodePath;
9703 pkg.applicationInfo.sourceDir = newCodePath;
9704 pkg.applicationInfo.publicSourceDir = newResPath;
9705 PackageSetting ps = (PackageSetting) pkg.mExtras;
9706 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9707 ps.codePathString = ps.codePath.getPath();
9708 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9709 ps.resourcePathString = ps.resourcePath.getPath();
9710 // Set the application info flag correctly.
9711 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9712 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9713 } else {
9714 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9715 }
9716 ps.setFlags(pkg.applicationInfo.flags);
9717 mAppDirs.remove(oldCodePath);
9718 mAppDirs.put(newCodePath, pkg);
9719 // Persist settings
9720 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009721 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009722 }
9723 }
9724 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009725 // Send resources available broadcast
9726 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009727 }
9728 if (!moveSucceeded){
9729 // Clean up failed installation
9730 if (mp.targetArgs != null) {
9731 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009732 returnCode);
9733 }
9734 } else {
9735 // Force a gc to clear things up.
9736 Runtime.getRuntime().gc();
9737 // Delete older code
9738 synchronized (mInstallLock) {
9739 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009740 }
9741 }
9742 IPackageMoveObserver observer = mp.observer;
9743 if (observer != null) {
9744 try {
9745 observer.packageMoved(mp.packageName, returnCode);
9746 } catch (RemoteException e) {
9747 Log.i(TAG, "Observer no longer exists.");
9748 }
9749 }
9750 }
9751 });
9752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753}