blob: ef1738b025ca185ed4a5dc1d8a8f157117118fa5 [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) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002684 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002685 ret = -1;
2686 }
2687 if (ret < 0) {
2688 //error from installer
2689 return DEX_OPT_FAILED;
2690 }
2691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002692
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002693 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2694 }
2695
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002696 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2697 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002698 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002699 + " to " + newPkg.packageName
2700 + ": old package not in system partition");
2701 return false;
2702 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002703 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002704 + " to " + newPkg.packageName
2705 + ": old package still exists");
2706 return false;
2707 }
2708 return true;
2709 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002710
2711 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002712 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002713 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002714
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002715 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2716 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002717 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002718 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2719 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002720 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002721 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002722 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2723 return null;
2724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 mScanningPath = scanFile;
2726 if (pkg == null) {
2727 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2728 return null;
2729 }
2730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2732 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2733 }
2734
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002735 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 synchronized (mPackages) {
2737 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002738 Slog.w(TAG, "*************************************************");
2739 Slog.w(TAG, "Core android package being redefined. Skipping.");
2740 Slog.w(TAG, " file=" + mScanningPath);
2741 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2743 return null;
2744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 // Set up information for our fall-back user intent resolution
2747 // activity.
2748 mPlatformPackage = pkg;
2749 pkg.mVersionCode = mSdkVersion;
2750 mAndroidApplication = pkg.applicationInfo;
2751 mResolveActivity.applicationInfo = mAndroidApplication;
2752 mResolveActivity.name = ResolverActivity.class.getName();
2753 mResolveActivity.packageName = mAndroidApplication.packageName;
2754 mResolveActivity.processName = mAndroidApplication.processName;
2755 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2756 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2757 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2758 mResolveActivity.exported = true;
2759 mResolveActivity.enabled = true;
2760 mResolveInfo.activityInfo = mResolveActivity;
2761 mResolveInfo.priority = 0;
2762 mResolveInfo.preferredOrder = 0;
2763 mResolveInfo.match = 0;
2764 mResolveComponentName = new ComponentName(
2765 mAndroidApplication.packageName, mResolveActivity.name);
2766 }
2767 }
2768
2769 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002770 TAG, "Scanning package " + pkg.packageName);
2771 if (mPackages.containsKey(pkg.packageName)
2772 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002773 Slog.w(TAG, "*************************************************");
2774 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002776 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2778 return null;
2779 }
2780
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002781 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002782 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2783 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 SharedUserSetting suid = null;
2786 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002787
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002788 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2789 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002790 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002791 pkg.mRealPackage = null;
2792 pkg.mAdoptPermissions = null;
2793 }
2794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 synchronized (mPackages) {
2796 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002797 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2798 if (mTmpSharedLibraries == null ||
2799 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2800 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2801 }
2802 int num = 0;
2803 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2804 for (int i=0; i<N; i++) {
2805 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002807 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002809 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2811 return null;
2812 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002813 mTmpSharedLibraries[num] = file;
2814 num++;
2815 }
2816 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2817 for (int i=0; i<N; i++) {
2818 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2819 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002821 + " desires unavailable shared library "
2822 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2823 } else {
2824 mTmpSharedLibraries[num] = file;
2825 num++;
2826 }
2827 }
2828 if (num > 0) {
2829 pkg.usesLibraryFiles = new String[num];
2830 System.arraycopy(mTmpSharedLibraries, 0,
2831 pkg.usesLibraryFiles, 0, num);
2832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002833
Dianne Hackborn49237342009-08-27 20:08:01 -07002834 if (pkg.reqFeatures != null) {
2835 N = pkg.reqFeatures.size();
2836 for (int i=0; i<N; i++) {
2837 FeatureInfo fi = pkg.reqFeatures.get(i);
2838 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2839 // Don't care.
2840 continue;
2841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002842
Dianne Hackborn49237342009-08-27 20:08:01 -07002843 if (fi.name != null) {
2844 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002845 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002846 + " requires unavailable feature "
2847 + fi.name + "; failing!");
2848 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2849 return null;
2850 }
2851 }
2852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 }
2854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 if (pkg.mSharedUserId != null) {
2857 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2858 pkg.applicationInfo.flags, true);
2859 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002860 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 + " for shared user failed");
2862 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2863 return null;
2864 }
2865 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2866 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2867 + suid.userId + "): packages=" + suid.packages);
2868 }
2869 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002870
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002871 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002872 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002873 Log.w(TAG, "WAITING FOR DEBUGGER");
2874 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002875 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2876 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 }
2878 }
2879
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002880 // Check if we are renaming from an original package name.
2881 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002882 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002883 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002884 // This package may need to be renamed to a previously
2885 // installed name. Let's check on that...
2886 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002887 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 // This package had originally been installed as the
2889 // original name, and we have already taken care of
2890 // transitioning to the new one. Just update the new
2891 // one to continue using the old name.
2892 realName = pkg.mRealPackage;
2893 if (!pkg.packageName.equals(renamed)) {
2894 // Callers into this function may have already taken
2895 // care of renaming the package; only do it here if
2896 // it is not already done.
2897 pkg.setPackageName(renamed);
2898 }
2899
Dianne Hackbornc1552392010-03-03 16:19:01 -08002900 } else {
2901 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2902 if ((origPackage=mSettings.peekPackageLP(
2903 pkg.mOriginalPackages.get(i))) != null) {
2904 // We do have the package already installed under its
2905 // original name... should we use it?
2906 if (!verifyPackageUpdate(origPackage, pkg)) {
2907 // New package is not compatible with original.
2908 origPackage = null;
2909 continue;
2910 } else if (origPackage.sharedUser != null) {
2911 // Make sure uid is compatible between packages.
2912 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002913 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002914 + " to " + pkg.packageName + ": old uid "
2915 + origPackage.sharedUser.name
2916 + " differs from " + pkg.mSharedUserId);
2917 origPackage = null;
2918 continue;
2919 }
2920 } else {
2921 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2922 + pkg.packageName + " to old name " + origPackage.name);
2923 }
2924 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002925 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002926 }
2927 }
2928 }
2929
2930 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002931 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002932 + " was transferred to another, but its .apk remains");
2933 }
2934
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002935 // Just create the setting, don't add it yet. For already existing packages
2936 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002937 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 destResourceFile, pkg.applicationInfo.flags, true, false);
2939 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002940 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2942 return null;
2943 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002944
2945 if (pkgSetting.origPackage != null) {
2946 // If we are first transitioning from an original package,
2947 // fix up the new package's name now. We need to do this after
2948 // looking up the package under its new name, so getPackageLP
2949 // can take care of fiddling things correctly.
2950 pkg.setPackageName(origPackage.name);
2951
2952 // File a report about this.
2953 String msg = "New package " + pkgSetting.realName
2954 + " renamed to replace old package " + pkgSetting.name;
2955 reportSettingsProblem(Log.WARN, msg);
2956
2957 // Make a note of it.
2958 mTransferedPackages.add(origPackage.name);
2959
2960 // No longer need to retain this.
2961 pkgSetting.origPackage = null;
2962 }
2963
2964 if (realName != null) {
2965 // Make a note of it.
2966 mTransferedPackages.add(pkg.packageName);
2967 }
2968
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002969 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 pkg.applicationInfo.uid = pkgSetting.userId;
2974 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002975
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002976 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002977 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 return null;
2979 }
2980 // The signature has changed, but this package is in the system
2981 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002982 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 // However... if this package is part of a shared user, but it
2984 // doesn't match the signature of the shared user, let's fail.
2985 // What this means is that you can't change the signatures
2986 // associated with an overall shared user, which doesn't seem all
2987 // that unreasonable.
2988 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002989 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2990 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2991 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2993 return null;
2994 }
2995 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002996 // File a report about this.
2997 String msg = "System package " + pkg.packageName
2998 + " signature changed; retaining data.";
2999 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003001
The Android Open Source Project10592532009-03-18 17:39:46 -07003002 // Verify that this new package doesn't have any content providers
3003 // that conflict with existing packages. Only do this if the
3004 // package isn't already installed, since we don't want to break
3005 // things that are installed.
3006 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3007 int N = pkg.providers.size();
3008 int i;
3009 for (i=0; i<N; i++) {
3010 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003011 if (p.info.authority != null) {
3012 String names[] = p.info.authority.split(";");
3013 for (int j = 0; j < names.length; j++) {
3014 if (mProviders.containsKey(names[j])) {
3015 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003016 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003017 " (in package " + pkg.applicationInfo.packageName +
3018 ") is already used by "
3019 + ((other != null && other.getComponentName() != null)
3020 ? other.getComponentName().getPackageName() : "?"));
3021 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3022 return null;
3023 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003024 }
3025 }
3026 }
3027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 }
3029
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003030 final String pkgName = pkg.packageName;
3031
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003032 if (pkg.mAdoptPermissions != null) {
3033 // This package wants to adopt ownership of permissions from
3034 // another package.
3035 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3036 String origName = pkg.mAdoptPermissions.get(i);
3037 PackageSetting orig = mSettings.peekPackageLP(origName);
3038 if (orig != null) {
3039 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003040 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003041 + origName + " to " + pkg.packageName);
3042 mSettings.transferPermissions(origName, pkg.packageName);
3043 }
3044 }
3045 }
3046 }
3047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 long scanFileTime = scanFile.lastModified();
3049 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3050 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3051 pkg.applicationInfo.processName = fixProcessName(
3052 pkg.applicationInfo.packageName,
3053 pkg.applicationInfo.processName,
3054 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055
3056 File dataPath;
3057 if (mPlatformPackage == pkg) {
3058 // The system package is special.
3059 dataPath = new File (Environment.getDataDirectory(), "system");
3060 pkg.applicationInfo.dataDir = dataPath.getPath();
3061 } else {
3062 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003063 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003064
3065 boolean uidError = false;
3066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 if (dataPath.exists()) {
3068 mOutPermissions[1] = 0;
3069 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3070 if (mOutPermissions[1] == pkg.applicationInfo.uid
3071 || !Process.supportsProcesses()) {
3072 pkg.applicationInfo.dataDir = dataPath.getPath();
3073 } else {
3074 boolean recovered = false;
3075 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3076 // If this is a system app, we can at least delete its
3077 // current data so the application will still work.
3078 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003079 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003080 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 // Old data gone!
3082 String msg = "System package " + pkg.packageName
3083 + " has changed from uid: "
3084 + mOutPermissions[1] + " to "
3085 + pkg.applicationInfo.uid + "; old data erased";
3086 reportSettingsProblem(Log.WARN, msg);
3087 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003090 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 pkg.applicationInfo.uid);
3092 if (ret == -1) {
3093 // Ack should not happen!
3094 msg = "System package " + pkg.packageName
3095 + " could not have data directory re-created after delete.";
3096 reportSettingsProblem(Log.WARN, msg);
3097 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3098 return null;
3099 }
3100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 if (!recovered) {
3103 mHasSystemUidErrors = true;
3104 }
3105 }
3106 if (!recovered) {
3107 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3108 + pkg.applicationInfo.uid + "/fs_"
3109 + mOutPermissions[1];
3110 String msg = "Package " + pkg.packageName
3111 + " has mismatched uid: "
3112 + mOutPermissions[1] + " on disk, "
3113 + pkg.applicationInfo.uid + " in settings";
3114 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003115 mSettings.mReadMessages.append(msg);
3116 mSettings.mReadMessages.append('\n');
3117 uidError = true;
3118 if (!pkgSetting.uidError) {
3119 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 }
3122 }
3123 }
3124 pkg.applicationInfo.dataDir = dataPath.getPath();
3125 } else {
3126 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3127 Log.v(TAG, "Want this data dir: " + dataPath);
3128 //invoke installer to do the actual installation
3129 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003130 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 pkg.applicationInfo.uid);
3132 if(ret < 0) {
3133 // Error from installer
3134 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3135 return null;
3136 }
3137 } else {
3138 dataPath.mkdirs();
3139 if (dataPath.exists()) {
3140 FileUtils.setPermissions(
3141 dataPath.toString(),
3142 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3143 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3144 }
3145 }
3146 if (dataPath.exists()) {
3147 pkg.applicationInfo.dataDir = dataPath.getPath();
3148 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003149 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 pkg.applicationInfo.dataDir = null;
3151 }
3152 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003153
3154 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 }
3156
3157 // Perform shared library installation and dex validation and
3158 // optimization, if this is not a system app.
3159 if (mInstaller != null) {
3160 String path = scanFile.getPath();
3161 if (scanFileNewer) {
3162 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003163 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3164 if (err != PackageManager.INSTALL_SUCCEEDED) {
3165 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 return null;
3167 }
3168 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003169 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003170
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003171 if ((scanMode&SCAN_NO_DEX) == 0) {
3172 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3174 return null;
3175 }
3176 }
3177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 if (mFactoryTest && pkg.requestedPermissions.contains(
3180 android.Manifest.permission.FACTORY_TEST)) {
3181 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3182 }
3183
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003184 // Request the ActivityManager to kill the process(only for existing packages)
3185 // so that we do not end up in a confused state while the user is still using the older
3186 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003187 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003188 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003189 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003190 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003193 // We don't expect installation to fail beyond this point,
3194 if ((scanMode&SCAN_MONITOR) != 0) {
3195 mAppDirs.put(pkg.mPath, pkg);
3196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003198 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003200 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003201 // Make sure we don't accidentally delete its data.
3202 mSettings.mPackagesToBeCleaned.remove(pkgName);
3203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 int N = pkg.providers.size();
3205 StringBuilder r = null;
3206 int i;
3207 for (i=0; i<N; i++) {
3208 PackageParser.Provider p = pkg.providers.get(i);
3209 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3210 p.info.processName, pkg.applicationInfo.uid);
3211 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3212 p.info.name), p);
3213 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003214 if (p.info.authority != null) {
3215 String names[] = p.info.authority.split(";");
3216 p.info.authority = null;
3217 for (int j = 0; j < names.length; j++) {
3218 if (j == 1 && p.syncable) {
3219 // We only want the first authority for a provider to possibly be
3220 // syncable, so if we already added this provider using a different
3221 // authority clear the syncable flag. We copy the provider before
3222 // changing it because the mProviders object contains a reference
3223 // to a provider that we don't want to change.
3224 // Only do this for the second authority since the resulting provider
3225 // object can be the same for all future authorities for this provider.
3226 p = new PackageParser.Provider(p);
3227 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003229 if (!mProviders.containsKey(names[j])) {
3230 mProviders.put(names[j], p);
3231 if (p.info.authority == null) {
3232 p.info.authority = names[j];
3233 } else {
3234 p.info.authority = p.info.authority + ";" + names[j];
3235 }
3236 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3237 Log.d(TAG, "Registered content provider: " + names[j] +
3238 ", className = " + p.info.name +
3239 ", isSyncable = " + p.info.isSyncable);
3240 } else {
3241 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003242 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003243 " (in package " + pkg.applicationInfo.packageName +
3244 "): name already used by "
3245 + ((other != null && other.getComponentName() != null)
3246 ? other.getComponentName().getPackageName() : "?"));
3247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 }
3249 }
3250 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3251 if (r == null) {
3252 r = new StringBuilder(256);
3253 } else {
3254 r.append(' ');
3255 }
3256 r.append(p.info.name);
3257 }
3258 }
3259 if (r != null) {
3260 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 N = pkg.services.size();
3264 r = null;
3265 for (i=0; i<N; i++) {
3266 PackageParser.Service s = pkg.services.get(i);
3267 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3268 s.info.processName, pkg.applicationInfo.uid);
3269 mServices.addService(s);
3270 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3271 if (r == null) {
3272 r = new StringBuilder(256);
3273 } else {
3274 r.append(' ');
3275 }
3276 r.append(s.info.name);
3277 }
3278 }
3279 if (r != null) {
3280 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 N = pkg.receivers.size();
3284 r = null;
3285 for (i=0; i<N; i++) {
3286 PackageParser.Activity a = pkg.receivers.get(i);
3287 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3288 a.info.processName, pkg.applicationInfo.uid);
3289 mReceivers.addActivity(a, "receiver");
3290 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3291 if (r == null) {
3292 r = new StringBuilder(256);
3293 } else {
3294 r.append(' ');
3295 }
3296 r.append(a.info.name);
3297 }
3298 }
3299 if (r != null) {
3300 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 N = pkg.activities.size();
3304 r = null;
3305 for (i=0; i<N; i++) {
3306 PackageParser.Activity a = pkg.activities.get(i);
3307 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3308 a.info.processName, pkg.applicationInfo.uid);
3309 mActivities.addActivity(a, "activity");
3310 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3311 if (r == null) {
3312 r = new StringBuilder(256);
3313 } else {
3314 r.append(' ');
3315 }
3316 r.append(a.info.name);
3317 }
3318 }
3319 if (r != null) {
3320 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3321 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 N = pkg.permissionGroups.size();
3324 r = null;
3325 for (i=0; i<N; i++) {
3326 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3327 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3328 if (cur == null) {
3329 mPermissionGroups.put(pg.info.name, pg);
3330 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3331 if (r == null) {
3332 r = new StringBuilder(256);
3333 } else {
3334 r.append(' ');
3335 }
3336 r.append(pg.info.name);
3337 }
3338 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003339 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340 + pg.info.packageName + " ignored: original from "
3341 + cur.info.packageName);
3342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3343 if (r == null) {
3344 r = new StringBuilder(256);
3345 } else {
3346 r.append(' ');
3347 }
3348 r.append("DUP:");
3349 r.append(pg.info.name);
3350 }
3351 }
3352 }
3353 if (r != null) {
3354 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3355 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 N = pkg.permissions.size();
3358 r = null;
3359 for (i=0; i<N; i++) {
3360 PackageParser.Permission p = pkg.permissions.get(i);
3361 HashMap<String, BasePermission> permissionMap =
3362 p.tree ? mSettings.mPermissionTrees
3363 : mSettings.mPermissions;
3364 p.group = mPermissionGroups.get(p.info.group);
3365 if (p.info.group == null || p.group != null) {
3366 BasePermission bp = permissionMap.get(p.info.name);
3367 if (bp == null) {
3368 bp = new BasePermission(p.info.name, p.info.packageName,
3369 BasePermission.TYPE_NORMAL);
3370 permissionMap.put(p.info.name, bp);
3371 }
3372 if (bp.perm == null) {
3373 if (bp.sourcePackage == null
3374 || bp.sourcePackage.equals(p.info.packageName)) {
3375 BasePermission tree = findPermissionTreeLP(p.info.name);
3376 if (tree == null
3377 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003378 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 bp.perm = p;
3380 bp.uid = pkg.applicationInfo.uid;
3381 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3382 if (r == null) {
3383 r = new StringBuilder(256);
3384 } else {
3385 r.append(' ');
3386 }
3387 r.append(p.info.name);
3388 }
3389 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003390 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 + p.info.packageName + " ignored: base tree "
3392 + tree.name + " is from package "
3393 + tree.sourcePackage);
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: original from "
3398 + bp.sourcePackage);
3399 }
3400 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3401 if (r == null) {
3402 r = new StringBuilder(256);
3403 } else {
3404 r.append(' ');
3405 }
3406 r.append("DUP:");
3407 r.append(p.info.name);
3408 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003409 if (bp.perm == p) {
3410 bp.protectionLevel = p.info.protectionLevel;
3411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003413 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 + p.info.packageName + " ignored: no group "
3415 + p.group);
3416 }
3417 }
3418 if (r != null) {
3419 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3420 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 N = pkg.instrumentation.size();
3423 r = null;
3424 for (i=0; i<N; i++) {
3425 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3426 a.info.packageName = pkg.applicationInfo.packageName;
3427 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3428 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3429 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003430 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3432 if (r == null) {
3433 r = new StringBuilder(256);
3434 } else {
3435 r.append(' ');
3436 }
3437 r.append(a.info.name);
3438 }
3439 }
3440 if (r != null) {
3441 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003443
Dianne Hackborn854060af2009-07-09 18:14:31 -07003444 if (pkg.protectedBroadcasts != null) {
3445 N = pkg.protectedBroadcasts.size();
3446 for (i=0; i<N; i++) {
3447 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3448 }
3449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 pkgSetting.setTimeStamp(scanFileTime);
3452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 return pkg;
3455 }
3456
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003457 private void killApplication(String pkgName, int uid) {
3458 // Request the ActivityManager to kill the process(only for existing packages)
3459 // so that we do not end up in a confused state while the user is still using the older
3460 // version of the application while the new one gets installed.
3461 IActivityManager am = ActivityManagerNative.getDefault();
3462 if (am != null) {
3463 try {
3464 am.killApplicationWithUid(pkgName, uid);
3465 } catch (RemoteException e) {
3466 }
3467 }
3468 }
3469
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003470 // The following constants are returned by cachePackageSharedLibsForAbiLI
3471 // to indicate if native shared libraries were found in the package.
3472 // Values are:
3473 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3474 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3475 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3476 // in package (and not installed)
3477 //
3478 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3479 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3480 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003482 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3483 // and automatically copy them to /data/data/<appname>/lib if present.
3484 //
3485 // NOTE: this method may throw an IOException if the library cannot
3486 // be copied to its final destination, e.g. if there isn't enough
3487 // room left on the data partition, or a ZipException if the package
3488 // file is malformed.
3489 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003490 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3491 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003492 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3493 final String apkLib = "lib/";
3494 final int apkLibLen = apkLib.length();
3495 final int cpuAbiLen = cpuAbi.length();
3496 final String libPrefix = "lib";
3497 final int libPrefixLen = libPrefix.length();
3498 final String libSuffix = ".so";
3499 final int libSuffixLen = libSuffix.length();
3500 boolean hasNativeLibraries = false;
3501 boolean installedNativeLibraries = false;
3502
3503 // the minimum length of a valid native shared library of the form
3504 // lib/<something>/lib<name>.so.
3505 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3506
3507 ZipFile zipFile = new ZipFile(scanFile);
3508 Enumeration<ZipEntry> entries =
3509 (Enumeration<ZipEntry>) zipFile.entries();
3510
3511 while (entries.hasMoreElements()) {
3512 ZipEntry entry = entries.nextElement();
3513 // skip directories
3514 if (entry.isDirectory()) {
3515 continue;
3516 }
3517 String entryName = entry.getName();
3518
3519 // check that the entry looks like lib/<something>/lib<name>.so
3520 // here, but don't check the ABI just yet.
3521 //
3522 // - must be sufficiently long
3523 // - must end with libSuffix, i.e. ".so"
3524 // - must start with apkLib, i.e. "lib/"
3525 if (entryName.length() < minEntryLen ||
3526 !entryName.endsWith(libSuffix) ||
3527 !entryName.startsWith(apkLib) ) {
3528 continue;
3529 }
3530
3531 // file name must start with libPrefix, i.e. "lib"
3532 int lastSlash = entryName.lastIndexOf('/');
3533
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003534 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003535 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3536 continue;
3537 }
3538
3539 hasNativeLibraries = true;
3540
3541 // check the cpuAbi now, between lib/ and /lib<name>.so
3542 //
3543 if (lastSlash != apkLibLen + cpuAbiLen ||
3544 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3545 continue;
3546
3547 // extract the library file name, ensure it doesn't contain
3548 // weird characters. we're guaranteed here that it doesn't contain
3549 // a directory separator though.
3550 String libFileName = entryName.substring(lastSlash+1);
3551 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3552 continue;
3553 }
3554
3555 installedNativeLibraries = true;
3556
3557 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3558 File.separator + libFileName;
3559 File sharedLibraryFile = new File(sharedLibraryFilePath);
3560 if (! sharedLibraryFile.exists() ||
3561 sharedLibraryFile.length() != entry.getSize() ||
3562 sharedLibraryFile.lastModified() != entry.getTime()) {
3563 if (Config.LOGD) {
3564 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003566 if (mInstaller == null) {
3567 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003568 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003569 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003570 sharedLibraryFile);
3571 }
3572 }
3573 if (!hasNativeLibraries)
3574 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3575
3576 if (!installedNativeLibraries)
3577 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3578
3579 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3580 }
3581
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003582 // Find the gdbserver executable program in a package at
3583 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3584 //
3585 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3586 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3587 //
3588 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3589 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3590 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3591 final String GDBSERVER = "gdbserver";
3592 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3593
3594 ZipFile zipFile = new ZipFile(scanFile);
3595 Enumeration<ZipEntry> entries =
3596 (Enumeration<ZipEntry>) zipFile.entries();
3597
3598 while (entries.hasMoreElements()) {
3599 ZipEntry entry = entries.nextElement();
3600 // skip directories
3601 if (entry.isDirectory()) {
3602 continue;
3603 }
3604 String entryName = entry.getName();
3605
3606 if (!entryName.equals(apkGdbServerPath)) {
3607 continue;
3608 }
3609
3610 String installGdbServerPath = installGdbServerDir.getPath() +
3611 "/" + GDBSERVER;
3612 File installGdbServerFile = new File(installGdbServerPath);
3613 if (! installGdbServerFile.exists() ||
3614 installGdbServerFile.length() != entry.getSize() ||
3615 installGdbServerFile.lastModified() != entry.getTime()) {
3616 if (Config.LOGD) {
3617 Log.d(TAG, "Caching gdbserver " + entry.getName());
3618 }
3619 if (mInstaller == null) {
3620 installGdbServerDir.mkdir();
3621 }
3622 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3623 installGdbServerFile);
3624 }
3625 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3626 }
3627 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3628 }
3629
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003630 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3631 // and copy them to /data/data/<appname>/lib.
3632 //
3633 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3634 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3635 // one if ro.product.cpu.abi2 is defined.
3636 //
3637 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3638 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003639 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003640 try {
3641 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3642
3643 // some architectures are capable of supporting several CPU ABIs
3644 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3645 // this is indicated by the definition of the ro.product.cpu.abi2
3646 // system property.
3647 //
3648 // only scan the package twice in case of ABI mismatch
3649 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003650 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003651 if (cpuAbi2 != null) {
3652 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003654
3655 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003656 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003657 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003659
3660 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3661 cpuAbi = cpuAbi2;
3662 }
3663 }
3664
3665 // for debuggable packages, also extract gdbserver from lib/<abi>
3666 // into /data/data/<appname>/lib too.
3667 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3668 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3669 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3670 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3671 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003674 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003675 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003676 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003678 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003679 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003681 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 }
3683
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003684 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003686 File binaryDir,
3687 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 InputStream inputStream = zipFile.getInputStream(entry);
3689 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003690 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003692 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 // now need to be left as world readable and owned by the system.
3694 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3695 ! tempFile.setLastModified(entry.getTime()) ||
3696 FileUtils.setPermissions(tempFilePath,
3697 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003698 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003700 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 // Failed to properly write file.
3702 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003703 throw new IOException("Couldn't create cached binary "
3704 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 }
3706 } finally {
3707 inputStream.close();
3708 }
3709 }
3710
3711 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3712 if (chatty && Config.LOGD) Log.d(
3713 TAG, "Removing package " + pkg.applicationInfo.packageName );
3714
3715 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 mPackages.remove(pkg.applicationInfo.packageName);
3719 if (pkg.mPath != null) {
3720 mAppDirs.remove(pkg.mPath);
3721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 PackageSetting ps = (PackageSetting)pkg.mExtras;
3724 if (ps != null && ps.sharedUser != null) {
3725 // XXX don't do this until the data is removed.
3726 if (false) {
3727 ps.sharedUser.packages.remove(ps);
3728 if (ps.sharedUser.packages.size() == 0) {
3729 // Remove.
3730 }
3731 }
3732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 int N = pkg.providers.size();
3735 StringBuilder r = null;
3736 int i;
3737 for (i=0; i<N; i++) {
3738 PackageParser.Provider p = pkg.providers.get(i);
3739 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3740 p.info.name));
3741 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 /* The is another ContentProvider with this authority when
3744 * this app was installed so this authority is null,
3745 * Ignore it as we don't have to unregister the provider.
3746 */
3747 continue;
3748 }
3749 String names[] = p.info.authority.split(";");
3750 for (int j = 0; j < names.length; j++) {
3751 if (mProviders.get(names[j]) == p) {
3752 mProviders.remove(names[j]);
3753 if (chatty && Config.LOGD) Log.d(
3754 TAG, "Unregistered content provider: " + names[j] +
3755 ", className = " + p.info.name +
3756 ", isSyncable = " + p.info.isSyncable);
3757 }
3758 }
3759 if (chatty) {
3760 if (r == null) {
3761 r = new StringBuilder(256);
3762 } else {
3763 r.append(' ');
3764 }
3765 r.append(p.info.name);
3766 }
3767 }
3768 if (r != null) {
3769 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 N = pkg.services.size();
3773 r = null;
3774 for (i=0; i<N; i++) {
3775 PackageParser.Service s = pkg.services.get(i);
3776 mServices.removeService(s);
3777 if (chatty) {
3778 if (r == null) {
3779 r = new StringBuilder(256);
3780 } else {
3781 r.append(' ');
3782 }
3783 r.append(s.info.name);
3784 }
3785 }
3786 if (r != null) {
3787 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 N = pkg.receivers.size();
3791 r = null;
3792 for (i=0; i<N; i++) {
3793 PackageParser.Activity a = pkg.receivers.get(i);
3794 mReceivers.removeActivity(a, "receiver");
3795 if (chatty) {
3796 if (r == null) {
3797 r = new StringBuilder(256);
3798 } else {
3799 r.append(' ');
3800 }
3801 r.append(a.info.name);
3802 }
3803 }
3804 if (r != null) {
3805 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3806 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 N = pkg.activities.size();
3809 r = null;
3810 for (i=0; i<N; i++) {
3811 PackageParser.Activity a = pkg.activities.get(i);
3812 mActivities.removeActivity(a, "activity");
3813 if (chatty) {
3814 if (r == null) {
3815 r = new StringBuilder(256);
3816 } else {
3817 r.append(' ');
3818 }
3819 r.append(a.info.name);
3820 }
3821 }
3822 if (r != null) {
3823 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 N = pkg.permissions.size();
3827 r = null;
3828 for (i=0; i<N; i++) {
3829 PackageParser.Permission p = pkg.permissions.get(i);
3830 boolean tree = false;
3831 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3832 if (bp == null) {
3833 tree = true;
3834 bp = mSettings.mPermissionTrees.get(p.info.name);
3835 }
3836 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003837 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 if (chatty) {
3839 if (r == null) {
3840 r = new StringBuilder(256);
3841 } else {
3842 r.append(' ');
3843 }
3844 r.append(p.info.name);
3845 }
3846 }
3847 }
3848 if (r != null) {
3849 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 N = pkg.instrumentation.size();
3853 r = null;
3854 for (i=0; i<N; i++) {
3855 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003856 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 if (chatty) {
3858 if (r == null) {
3859 r = new StringBuilder(256);
3860 } else {
3861 r.append(' ');
3862 }
3863 r.append(a.info.name);
3864 }
3865 }
3866 if (r != null) {
3867 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3868 }
3869 }
3870 }
3871
3872 private static final boolean isPackageFilename(String name) {
3873 return name != null && name.endsWith(".apk");
3874 }
3875
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003876 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3877 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3878 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3879 return true;
3880 }
3881 }
3882 return false;
3883 }
3884
3885 private void updatePermissionsLP(String changingPkg,
3886 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 // Make sure there are no dangling permission trees.
3888 Iterator<BasePermission> it = mSettings.mPermissionTrees
3889 .values().iterator();
3890 while (it.hasNext()) {
3891 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003892 if (bp.packageSetting == null) {
3893 // We may not yet have parsed the package, so just see if
3894 // we still know about its settings.
3895 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3896 }
3897 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003898 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 + " from package " + bp.sourcePackage);
3900 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003901 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3902 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3903 Slog.i(TAG, "Removing old permission tree: " + bp.name
3904 + " from package " + bp.sourcePackage);
3905 grantPermissions = true;
3906 it.remove();
3907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
3910
3911 // Make sure all dynamic permissions have been assigned to a package,
3912 // and make sure there are no dangling permissions.
3913 it = mSettings.mPermissions.values().iterator();
3914 while (it.hasNext()) {
3915 BasePermission bp = it.next();
3916 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3917 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3918 + bp.name + " pkg=" + bp.sourcePackage
3919 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003920 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 BasePermission tree = findPermissionTreeLP(bp.name);
3922 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003923 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 bp.perm = new PackageParser.Permission(tree.perm.owner,
3925 new PermissionInfo(bp.pendingInfo));
3926 bp.perm.info.packageName = tree.perm.info.packageName;
3927 bp.perm.info.name = bp.name;
3928 bp.uid = tree.uid;
3929 }
3930 }
3931 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003932 if (bp.packageSetting == null) {
3933 // We may not yet have parsed the package, so just see if
3934 // we still know about its settings.
3935 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3936 }
3937 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003938 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 + " from package " + bp.sourcePackage);
3940 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003941 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3942 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3943 Slog.i(TAG, "Removing old permission: " + bp.name
3944 + " from package " + bp.sourcePackage);
3945 grantPermissions = true;
3946 it.remove();
3947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 }
3949 }
3950
3951 // Now update the permissions for all packages, in particular
3952 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003953 if (grantPermissions) {
3954 for (PackageParser.Package pkg : mPackages.values()) {
3955 if (pkg != pkgInfo) {
3956 grantPermissionsLP(pkg, false);
3957 }
3958 }
3959 }
3960
3961 if (pkgInfo != null) {
3962 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
3964 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3967 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3968 if (ps == null) {
3969 return;
3970 }
3971 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003972 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 if (replace) {
3975 ps.permissionsFixed = false;
3976 if (gp == ps) {
3977 gp.grantedPermissions.clear();
3978 gp.gids = mGlobalGids;
3979 }
3980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 if (gp.gids == null) {
3983 gp.gids = mGlobalGids;
3984 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 final int N = pkg.requestedPermissions.size();
3987 for (int i=0; i<N; i++) {
3988 String name = pkg.requestedPermissions.get(i);
3989 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 if (false) {
3991 if (gp != ps) {
3992 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003993 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 }
3995 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003996 if (bp != null && bp.packageSetting != null) {
3997 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003999 boolean allowedSig = false;
4000 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4001 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004003 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4004 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4005 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004007 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004009 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4011 // For updated system applications, the signatureOrSystem permission
4012 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004013 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4015 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4016 if(sysPs.grantedPermissions.contains(perm)) {
4017 allowed = true;
4018 } else {
4019 allowed = false;
4020 }
4021 } else {
4022 allowed = true;
4023 }
4024 }
4025 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 if (allowed) {
4027 allowedSig = true;
4028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 } else {
4030 allowed = false;
4031 }
4032 if (false) {
4033 if (gp != ps) {
4034 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4035 }
4036 }
4037 if (allowed) {
4038 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4039 && ps.permissionsFixed) {
4040 // If this is an existing, non-system package, then
4041 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004042 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004044 // Except... if this is a permission that was added
4045 // to the platform (note: need to only do this when
4046 // updating the platform).
4047 final int NP = PackageParser.NEW_PERMISSIONS.length;
4048 for (int ip=0; ip<NP; ip++) {
4049 final PackageParser.NewPermissionInfo npi
4050 = PackageParser.NEW_PERMISSIONS[ip];
4051 if (npi.name.equals(perm)
4052 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4053 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004054 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004055 + pkg.packageName);
4056 break;
4057 }
4058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 }
4060 }
4061 if (allowed) {
4062 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004063 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 gp.grantedPermissions.add(perm);
4065 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004066 } else if (!ps.haveGids) {
4067 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 }
4069 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004070 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 + " to package " + pkg.packageName
4072 + " because it was previously installed without");
4073 }
4074 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004075 if (gp.grantedPermissions.remove(perm)) {
4076 changedPermission = true;
4077 gp.gids = removeInts(gp.gids, bp.gids);
4078 Slog.i(TAG, "Un-granting permission " + perm
4079 + " from package " + pkg.packageName
4080 + " (protectionLevel=" + bp.protectionLevel
4081 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4082 + ")");
4083 } else {
4084 Slog.w(TAG, "Not granting permission " + perm
4085 + " to package " + pkg.packageName
4086 + " (protectionLevel=" + bp.protectionLevel
4087 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4088 + ")");
4089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 }
4091 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004092 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 + " in package " + pkg.packageName);
4094 }
4095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004096
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004097 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004098 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4099 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 // This is the first that we have heard about this package, so the
4101 // permissions we have now selected are fixed until explicitly
4102 // changed.
4103 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004105 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 private final class ActivityIntentResolver
4109 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004110 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004111 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004112 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114
Mihai Preda074edef2009-05-18 17:13:31 +02004115 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004117 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4119 }
4120
Mihai Predaeae850c2009-05-13 10:13:48 +02004121 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4122 ArrayList<PackageParser.Activity> packageActivities) {
4123 if (packageActivities == null) {
4124 return null;
4125 }
4126 mFlags = flags;
4127 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4128 int N = packageActivities.size();
4129 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4130 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004131
4132 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004133 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004134 intentFilters = packageActivities.get(i).intents;
4135 if (intentFilters != null && intentFilters.size() > 0) {
4136 listCut.add(intentFilters);
4137 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004138 }
4139 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4140 }
4141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004143 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 if (SHOW_INFO || Config.LOGV) Log.v(
4145 TAG, " " + type + " " +
4146 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4147 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4148 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004149 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4151 if (SHOW_INFO || Config.LOGV) {
4152 Log.v(TAG, " IntentFilter:");
4153 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4154 }
4155 if (!intent.debugCheck()) {
4156 Log.w(TAG, "==> For Activity " + a.info.name);
4157 }
4158 addFilter(intent);
4159 }
4160 }
4161
4162 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004163 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 if (SHOW_INFO || Config.LOGV) Log.v(
4165 TAG, " " + type + " " +
4166 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4167 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4168 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004169 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4171 if (SHOW_INFO || Config.LOGV) {
4172 Log.v(TAG, " IntentFilter:");
4173 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4174 }
4175 removeFilter(intent);
4176 }
4177 }
4178
4179 @Override
4180 protected boolean allowFilterResult(
4181 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4182 ActivityInfo filterAi = filter.activity.info;
4183 for (int i=dest.size()-1; i>=0; i--) {
4184 ActivityInfo destAi = dest.get(i).activityInfo;
4185 if (destAi.name == filterAi.name
4186 && destAi.packageName == filterAi.packageName) {
4187 return false;
4188 }
4189 }
4190 return true;
4191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004194 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4195 return info.activity.owner.packageName;
4196 }
4197
4198 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4200 int match) {
4201 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4202 return null;
4203 }
4204 final PackageParser.Activity activity = info.activity;
4205 if (mSafeMode && (activity.info.applicationInfo.flags
4206 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4207 return null;
4208 }
4209 final ResolveInfo res = new ResolveInfo();
4210 res.activityInfo = PackageParser.generateActivityInfo(activity,
4211 mFlags);
4212 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4213 res.filter = info;
4214 }
4215 res.priority = info.getPriority();
4216 res.preferredOrder = activity.owner.mPreferredOrder;
4217 //System.out.println("Result: " + res.activityInfo.className +
4218 // " = " + res.priority);
4219 res.match = match;
4220 res.isDefault = info.hasDefault;
4221 res.labelRes = info.labelRes;
4222 res.nonLocalizedLabel = info.nonLocalizedLabel;
4223 res.icon = info.icon;
4224 return res;
4225 }
4226
4227 @Override
4228 protected void sortResults(List<ResolveInfo> results) {
4229 Collections.sort(results, mResolvePrioritySorter);
4230 }
4231
4232 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004233 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004235 out.print(prefix); out.print(
4236 Integer.toHexString(System.identityHashCode(filter.activity)));
4237 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004238 out.print(filter.activity.getComponentShortName());
4239 out.print(" filter ");
4240 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
4242
4243// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4244// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4245// final List<ResolveInfo> retList = Lists.newArrayList();
4246// while (i.hasNext()) {
4247// final ResolveInfo resolveInfo = i.next();
4248// if (isEnabledLP(resolveInfo.activityInfo)) {
4249// retList.add(resolveInfo);
4250// }
4251// }
4252// return retList;
4253// }
4254
4255 // Keys are String (activity class name), values are Activity.
4256 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4257 = new HashMap<ComponentName, PackageParser.Activity>();
4258 private int mFlags;
4259 }
4260
4261 private final class ServiceIntentResolver
4262 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004263 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004265 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 }
4267
Mihai Preda074edef2009-05-18 17:13:31 +02004268 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004270 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4272 }
4273
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004274 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4275 ArrayList<PackageParser.Service> packageServices) {
4276 if (packageServices == null) {
4277 return null;
4278 }
4279 mFlags = flags;
4280 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4281 int N = packageServices.size();
4282 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4283 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4284
4285 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4286 for (int i = 0; i < N; ++i) {
4287 intentFilters = packageServices.get(i).intents;
4288 if (intentFilters != null && intentFilters.size() > 0) {
4289 listCut.add(intentFilters);
4290 }
4291 }
4292 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4293 }
4294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004295 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004296 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 if (SHOW_INFO || Config.LOGV) Log.v(
4298 TAG, " " + (s.info.nonLocalizedLabel != null
4299 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4300 if (SHOW_INFO || Config.LOGV) Log.v(
4301 TAG, " Class=" + s.info.name);
4302 int NI = s.intents.size();
4303 int j;
4304 for (j=0; j<NI; j++) {
4305 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4306 if (SHOW_INFO || Config.LOGV) {
4307 Log.v(TAG, " IntentFilter:");
4308 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4309 }
4310 if (!intent.debugCheck()) {
4311 Log.w(TAG, "==> For Service " + s.info.name);
4312 }
4313 addFilter(intent);
4314 }
4315 }
4316
4317 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004318 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 if (SHOW_INFO || Config.LOGV) Log.v(
4320 TAG, " " + (s.info.nonLocalizedLabel != null
4321 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4322 if (SHOW_INFO || Config.LOGV) Log.v(
4323 TAG, " Class=" + s.info.name);
4324 int NI = s.intents.size();
4325 int j;
4326 for (j=0; j<NI; j++) {
4327 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4328 if (SHOW_INFO || Config.LOGV) {
4329 Log.v(TAG, " IntentFilter:");
4330 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4331 }
4332 removeFilter(intent);
4333 }
4334 }
4335
4336 @Override
4337 protected boolean allowFilterResult(
4338 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4339 ServiceInfo filterSi = filter.service.info;
4340 for (int i=dest.size()-1; i>=0; i--) {
4341 ServiceInfo destAi = dest.get(i).serviceInfo;
4342 if (destAi.name == filterSi.name
4343 && destAi.packageName == filterSi.packageName) {
4344 return false;
4345 }
4346 }
4347 return true;
4348 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004351 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4352 return info.service.owner.packageName;
4353 }
4354
4355 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4357 int match) {
4358 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4359 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4360 return null;
4361 }
4362 final PackageParser.Service service = info.service;
4363 if (mSafeMode && (service.info.applicationInfo.flags
4364 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4365 return null;
4366 }
4367 final ResolveInfo res = new ResolveInfo();
4368 res.serviceInfo = PackageParser.generateServiceInfo(service,
4369 mFlags);
4370 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4371 res.filter = filter;
4372 }
4373 res.priority = info.getPriority();
4374 res.preferredOrder = service.owner.mPreferredOrder;
4375 //System.out.println("Result: " + res.activityInfo.className +
4376 // " = " + res.priority);
4377 res.match = match;
4378 res.isDefault = info.hasDefault;
4379 res.labelRes = info.labelRes;
4380 res.nonLocalizedLabel = info.nonLocalizedLabel;
4381 res.icon = info.icon;
4382 return res;
4383 }
4384
4385 @Override
4386 protected void sortResults(List<ResolveInfo> results) {
4387 Collections.sort(results, mResolvePrioritySorter);
4388 }
4389
4390 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004391 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004393 out.print(prefix); out.print(
4394 Integer.toHexString(System.identityHashCode(filter.service)));
4395 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004396 out.print(filter.service.getComponentShortName());
4397 out.print(" filter ");
4398 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 }
4400
4401// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4402// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4403// final List<ResolveInfo> retList = Lists.newArrayList();
4404// while (i.hasNext()) {
4405// final ResolveInfo resolveInfo = (ResolveInfo) i;
4406// if (isEnabledLP(resolveInfo.serviceInfo)) {
4407// retList.add(resolveInfo);
4408// }
4409// }
4410// return retList;
4411// }
4412
4413 // Keys are String (activity class name), values are Activity.
4414 private final HashMap<ComponentName, PackageParser.Service> mServices
4415 = new HashMap<ComponentName, PackageParser.Service>();
4416 private int mFlags;
4417 };
4418
4419 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4420 new Comparator<ResolveInfo>() {
4421 public int compare(ResolveInfo r1, ResolveInfo r2) {
4422 int v1 = r1.priority;
4423 int v2 = r2.priority;
4424 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4425 if (v1 != v2) {
4426 return (v1 > v2) ? -1 : 1;
4427 }
4428 v1 = r1.preferredOrder;
4429 v2 = r2.preferredOrder;
4430 if (v1 != v2) {
4431 return (v1 > v2) ? -1 : 1;
4432 }
4433 if (r1.isDefault != r2.isDefault) {
4434 return r1.isDefault ? -1 : 1;
4435 }
4436 v1 = r1.match;
4437 v2 = r2.match;
4438 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4439 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4440 }
4441 };
4442
4443 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4444 new Comparator<ProviderInfo>() {
4445 public int compare(ProviderInfo p1, ProviderInfo p2) {
4446 final int v1 = p1.initOrder;
4447 final int v2 = p2.initOrder;
4448 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4449 }
4450 };
4451
4452 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4453 IActivityManager am = ActivityManagerNative.getDefault();
4454 if (am != null) {
4455 try {
4456 final Intent intent = new Intent(action,
4457 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4458 if (extras != null) {
4459 intent.putExtras(extras);
4460 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004461 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 am.broadcastIntent(
4463 null, intent,
4464 null, null, 0, null, null, null, false, false);
4465 } catch (RemoteException ex) {
4466 }
4467 }
4468 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004469
4470 public String nextPackageToClean(String lastPackage) {
4471 synchronized (mPackages) {
4472 if (!mMediaMounted) {
4473 // If the external storage is no longer mounted at this point,
4474 // the caller may not have been able to delete all of this
4475 // packages files and can not delete any more. Bail.
4476 return null;
4477 }
4478 if (lastPackage != null) {
4479 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4480 }
4481 return mSettings.mPackagesToBeCleaned.size() > 0
4482 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4483 }
4484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004486 void schedulePackageCleaning(String packageName) {
4487 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4488 }
4489
4490 void startCleaningPackages() {
4491 synchronized (mPackages) {
4492 if (!mMediaMounted) {
4493 return;
4494 }
4495 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4496 return;
4497 }
4498 }
4499 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4500 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4501 IActivityManager am = ActivityManagerNative.getDefault();
4502 if (am != null) {
4503 try {
4504 am.startService(null, intent, null);
4505 } catch (RemoteException e) {
4506 }
4507 }
4508 }
4509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 private final class AppDirObserver extends FileObserver {
4511 public AppDirObserver(String path, int mask, boolean isrom) {
4512 super(path, mask);
4513 mRootDir = path;
4514 mIsRom = isrom;
4515 }
4516
4517 public void onEvent(int event, String path) {
4518 String removedPackage = null;
4519 int removedUid = -1;
4520 String addedPackage = null;
4521 int addedUid = -1;
4522
4523 synchronized (mInstallLock) {
4524 String fullPathStr = null;
4525 File fullPath = null;
4526 if (path != null) {
4527 fullPath = new File(mRootDir, path);
4528 fullPathStr = fullPath.getPath();
4529 }
4530
4531 if (Config.LOGV) Log.v(
4532 TAG, "File " + fullPathStr + " changed: "
4533 + Integer.toHexString(event));
4534
4535 if (!isPackageFilename(path)) {
4536 if (Config.LOGV) Log.v(
4537 TAG, "Ignoring change of non-package file: " + fullPathStr);
4538 return;
4539 }
4540
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004541 // Ignore packages that are being installed or
4542 // have just been installed.
4543 if (ignoreCodePath(fullPathStr)) {
4544 return;
4545 }
4546 PackageParser.Package p = null;
4547 synchronized (mPackages) {
4548 p = mAppDirs.get(fullPathStr);
4549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004551 if (p != null) {
4552 removePackageLI(p, true);
4553 removedPackage = p.applicationInfo.packageName;
4554 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 }
4556 }
4557
4558 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004560 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004561 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4562 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 PackageParser.PARSE_CHATTY |
4564 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004565 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 if (p != null) {
4567 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004568 updatePermissionsLP(p.packageName, p,
4569 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 }
4571 addedPackage = p.applicationInfo.packageName;
4572 addedUid = p.applicationInfo.uid;
4573 }
4574 }
4575 }
4576
4577 synchronized (mPackages) {
4578 mSettings.writeLP();
4579 }
4580 }
4581
4582 if (removedPackage != null) {
4583 Bundle extras = new Bundle(1);
4584 extras.putInt(Intent.EXTRA_UID, removedUid);
4585 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4586 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4587 }
4588 if (addedPackage != null) {
4589 Bundle extras = new Bundle(1);
4590 extras.putInt(Intent.EXTRA_UID, addedUid);
4591 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4592 }
4593 }
4594
4595 private final String mRootDir;
4596 private final boolean mIsRom;
4597 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 /* Called when a downloaded package installation has been confirmed by the user */
4600 public void installPackage(
4601 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004602 installPackage(packageURI, observer, flags, null);
4603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004604
Jacek Surazski65e13172009-04-28 15:26:38 +02004605 /* 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,
4608 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 mContext.enforceCallingOrSelfPermission(
4610 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004611
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004612 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004613 msg.obj = new InstallParams(packageURI, observer, flags,
4614 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004615 mHandler.sendMessage(msg);
4616 }
4617
Christopher Tate1bb69062010-02-19 17:02:12 -08004618 public void finishPackageInstall(int token) {
4619 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4620 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4621 mHandler.sendMessage(msg);
4622 }
4623
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004624 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 // Queue up an async operation since the package installation may take a little while.
4626 mHandler.post(new Runnable() {
4627 public void run() {
4628 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004629 // Result object to be returned
4630 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004631 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004632 res.uid = -1;
4633 res.pkg = null;
4634 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004635 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004636 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004637 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004638 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004639 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004640 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004642
4643 // A restore should be performed at this point if (a) the install
4644 // succeeded, (b) the operation is not an update, and (c) the new
4645 // package has a backupAgent defined.
4646 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004647 boolean doRestore = (!update
4648 && res.pkg != null
4649 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004650
4651 // Set up the post-install work request bookkeeping. This will be used
4652 // and cleaned up by the post-install event handling regardless of whether
4653 // there's a restore pass performed. Token values are >= 1.
4654 int token;
4655 if (mNextInstallToken < 0) mNextInstallToken = 1;
4656 token = mNextInstallToken++;
4657
4658 PostInstallData data = new PostInstallData(args, res);
4659 mRunningInstalls.put(token, data);
4660 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4661
4662 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4663 // Pass responsibility to the Backup Manager. It will perform a
4664 // restore if appropriate, then pass responsibility back to the
4665 // Package Manager to run the post-install observer callbacks
4666 // and broadcasts.
4667 IBackupManager bm = IBackupManager.Stub.asInterface(
4668 ServiceManager.getService(Context.BACKUP_SERVICE));
4669 if (bm != null) {
4670 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4671 + " to BM for possible restore");
4672 try {
4673 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4674 } catch (RemoteException e) {
4675 // can't happen; the backup manager is local
4676 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004677 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004678 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004679 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004680 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004681 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004682 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004685
4686 if (!doRestore) {
4687 // No restore possible, or the Backup Manager was mysteriously not
4688 // available -- just fire the post-install work request directly.
4689 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4690 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4691 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 }
4694 });
4695 }
4696
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004697 abstract class HandlerParams {
4698 final static int MAX_RETRIES = 4;
4699 int retry = 0;
4700 final void startCopy() {
4701 try {
4702 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4703 retry++;
4704 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004705 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004706 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4707 handleServiceError();
4708 return;
4709 } else {
4710 handleStartCopy();
4711 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4712 mHandler.sendEmptyMessage(MCS_UNBIND);
4713 }
4714 } catch (RemoteException e) {
4715 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4716 mHandler.sendEmptyMessage(MCS_RECONNECT);
4717 }
4718 handleReturnCode();
4719 }
4720
4721 final void serviceError() {
4722 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4723 handleServiceError();
4724 handleReturnCode();
4725 }
4726 abstract void handleStartCopy() throws RemoteException;
4727 abstract void handleServiceError();
4728 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004729 }
4730
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004731 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004732 final IPackageInstallObserver observer;
4733 int flags;
4734 final Uri packageURI;
4735 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004736 private InstallArgs mArgs;
4737 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004738 InstallParams(Uri packageURI,
4739 IPackageInstallObserver observer, int flags,
4740 String installerPackageName) {
4741 this.packageURI = packageURI;
4742 this.flags = flags;
4743 this.observer = observer;
4744 this.installerPackageName = installerPackageName;
4745 }
4746
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004747 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4748 String packageName = pkgLite.packageName;
4749 int installLocation = pkgLite.installLocation;
4750 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4751 synchronized (mPackages) {
4752 PackageParser.Package pkg = mPackages.get(packageName);
4753 if (pkg != null) {
4754 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4755 // Check for updated system application.
4756 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4757 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004758 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004759 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4760 }
4761 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4762 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004763 if (onSd) {
4764 // Install flag overrides everything.
4765 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4766 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004767 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004768 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4769 // Application explicitly specified internal.
4770 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4771 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4772 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004773 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004774 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004775 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4776 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4777 }
4778 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004779 }
4780 }
4781 } else {
4782 // Invalid install. Return error code
4783 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4784 }
4785 }
4786 }
4787 // All the special cases have been taken care of.
4788 // Return result based on recommended install location.
4789 if (onSd) {
4790 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4791 }
4792 return pkgLite.recommendedInstallLocation;
4793 }
4794
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004795 /*
4796 * Invoke remote method to get package information and install
4797 * location values. Override install location based on default
4798 * policy if needed and then create install arguments based
4799 * on the install location.
4800 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004801 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004802 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004803 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4804 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004805 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4806 if (onInt && onSd) {
4807 // Check if both bits are set.
4808 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4809 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4810 } else if (fwdLocked && onSd) {
4811 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004812 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004813 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004814 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004816 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004817 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004818 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4819 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4820 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4821 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4822 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004823 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4824 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4825 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004826 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4827 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004829 // Override with defaults if needed.
4830 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004831 if (!onSd && !onInt) {
4832 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4834 // Set the flag to install on external media.
4835 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004836 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004837 } else {
4838 // Make sure the flag for installing on external
4839 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004840 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 flags &= ~PackageManager.INSTALL_EXTERNAL;
4842 }
4843 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 }
4845 }
4846 // Create the file args now.
4847 mArgs = createInstallArgs(this);
4848 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4849 // Create copy only if we are not in an erroneous state.
4850 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004851 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 }
4853 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 }
4855
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 void handleReturnCode() {
4858 processPendingInstall(mArgs, mRet);
4859 }
4860
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004861 @Override
4862 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 mArgs = createInstallArgs(this);
4864 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004865 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004866 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867
4868 /*
4869 * Utility class used in movePackage api.
4870 * srcArgs and targetArgs are not set for invalid flags and make
4871 * sure to do null checks when invoking methods on them.
4872 * We probably want to return ErrorPrams for both failed installs
4873 * and moves.
4874 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004875 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 final IPackageMoveObserver observer;
4877 final int flags;
4878 final String packageName;
4879 final InstallArgs srcArgs;
4880 final InstallArgs targetArgs;
4881 int mRet;
4882 MoveParams(InstallArgs srcArgs,
4883 IPackageMoveObserver observer,
4884 int flags, String packageName) {
4885 this.srcArgs = srcArgs;
4886 this.observer = observer;
4887 this.flags = flags;
4888 this.packageName = packageName;
4889 if (srcArgs != null) {
4890 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4891 targetArgs = createInstallArgs(packageUri, flags, packageName);
4892 } else {
4893 targetArgs = null;
4894 }
4895 }
4896
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004897 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004898 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4899 // Check for storage space on target medium
4900 if (!targetArgs.checkFreeStorage(mContainerService)) {
4901 Log.w(TAG, "Insufficient storage to install");
4902 return;
4903 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004905 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004907 if (DEBUG_SD_INSTALL) {
4908 StringBuilder builder = new StringBuilder();
4909 if (srcArgs != null) {
4910 builder.append("src: ");
4911 builder.append(srcArgs.getCodePath());
4912 }
4913 if (targetArgs != null) {
4914 builder.append(" target : ");
4915 builder.append(targetArgs.getCodePath());
4916 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004917 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004918 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919 }
4920
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004921 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004922 void handleReturnCode() {
4923 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004924 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4925 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4926 currentStatus = PackageManager.MOVE_SUCCEEDED;
4927 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4928 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4929 }
4930 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004931 }
4932
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004933 @Override
4934 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004935 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004936 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004937 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004938
4939 private InstallArgs createInstallArgs(InstallParams params) {
4940 if (installOnSd(params.flags)) {
4941 return new SdInstallArgs(params);
4942 } else {
4943 return new FileInstallArgs(params);
4944 }
4945 }
4946
4947 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4948 if (installOnSd(flags)) {
4949 return new SdInstallArgs(fullCodePath, fullResourcePath);
4950 } else {
4951 return new FileInstallArgs(fullCodePath, fullResourcePath);
4952 }
4953 }
4954
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004955 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4956 if (installOnSd(flags)) {
4957 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4958 return new SdInstallArgs(packageURI, cid);
4959 } else {
4960 return new FileInstallArgs(packageURI, pkgName);
4961 }
4962 }
4963
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004964 static abstract class InstallArgs {
4965 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 final int flags;
4968 final Uri packageURI;
4969 final String installerPackageName;
4970
4971 InstallArgs(Uri packageURI,
4972 IPackageInstallObserver observer, int flags,
4973 String installerPackageName) {
4974 this.packageURI = packageURI;
4975 this.flags = flags;
4976 this.observer = observer;
4977 this.installerPackageName = installerPackageName;
4978 }
4979
4980 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004981 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004982 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004983 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004984 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004985 abstract String getCodePath();
4986 abstract String getResourcePath();
4987 // Need installer lock especially for dex file removal.
4988 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004989 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004990 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 }
4992
4993 class FileInstallArgs extends InstallArgs {
4994 File installDir;
4995 String codeFileName;
4996 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004997 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004998
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004999 FileInstallArgs(InstallParams params) {
5000 super(params.packageURI, params.observer,
5001 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 }
5003
5004 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5005 super(null, null, 0, null);
5006 File codeFile = new File(fullCodePath);
5007 installDir = codeFile.getParentFile();
5008 codeFileName = fullCodePath;
5009 resourceFileName = fullResourcePath;
5010 }
5011
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005012 FileInstallArgs(Uri packageURI, String pkgName) {
5013 super(packageURI, null, 0, null);
5014 boolean fwdLocked = isFwdLocked(flags);
5015 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5016 String apkName = getNextCodePath(null, pkgName, ".apk");
5017 codeFileName = new File(installDir, apkName + ".apk").getPath();
5018 resourceFileName = getResourcePathFromCodePath();
5019 }
5020
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005021 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5022 return imcs.checkFreeStorage(false, packageURI);
5023 }
5024
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005025 String getCodePath() {
5026 return codeFileName;
5027 }
5028
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005029 void createCopyFile() {
5030 boolean fwdLocked = isFwdLocked(flags);
5031 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5032 codeFileName = createTempPackageFile(installDir).getPath();
5033 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005034 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005035 }
5036
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005037 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005038 if (temp) {
5039 // Generate temp file name
5040 createCopyFile();
5041 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005042 // Get a ParcelFileDescriptor to write to the output file
5043 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005044 if (!created) {
5045 try {
5046 codeFile.createNewFile();
5047 // Set permissions
5048 if (!setPermissions()) {
5049 // Failed setting permissions.
5050 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5051 }
5052 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005053 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005054 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5055 }
5056 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005057 ParcelFileDescriptor out = null;
5058 try {
5059 out = ParcelFileDescriptor.open(codeFile,
5060 ParcelFileDescriptor.MODE_READ_WRITE);
5061 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005062 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5064 }
5065 // Copy the resource now
5066 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5067 try {
5068 if (imcs.copyResource(packageURI, out)) {
5069 ret = PackageManager.INSTALL_SUCCEEDED;
5070 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071 } finally {
5072 try { if (out != null) out.close(); } catch (IOException e) {}
5073 }
5074 return ret;
5075 }
5076
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005077 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005078 if (status != PackageManager.INSTALL_SUCCEEDED) {
5079 cleanUp();
5080 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005081 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005082 }
5083
5084 boolean doRename(int status, final String pkgName, String oldCodePath) {
5085 if (status != PackageManager.INSTALL_SUCCEEDED) {
5086 cleanUp();
5087 return false;
5088 } else {
5089 // Rename based on packageName
5090 File codeFile = new File(getCodePath());
5091 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5092 File desFile = new File(installDir, apkName + ".apk");
5093 if (!codeFile.renameTo(desFile)) {
5094 return false;
5095 }
5096 // Reset paths since the file has been renamed.
5097 codeFileName = desFile.getPath();
5098 resourceFileName = getResourcePathFromCodePath();
5099 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005100 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005101 // Failed setting permissions.
5102 return false;
5103 }
5104 return true;
5105 }
5106 }
5107
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005108 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 if (status != PackageManager.INSTALL_SUCCEEDED) {
5110 cleanUp();
5111 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005112 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005113 }
5114
5115 String getResourcePath() {
5116 return resourceFileName;
5117 }
5118
5119 String getResourcePathFromCodePath() {
5120 String codePath = getCodePath();
5121 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5122 String apkNameOnly = getApkName(codePath);
5123 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5124 } else {
5125 return codePath;
5126 }
5127 }
5128
5129 private boolean cleanUp() {
5130 boolean ret = true;
5131 String sourceDir = getCodePath();
5132 String publicSourceDir = getResourcePath();
5133 if (sourceDir != null) {
5134 File sourceFile = new File(sourceDir);
5135 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005136 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005137 ret = false;
5138 }
5139 // Delete application's code and resources
5140 sourceFile.delete();
5141 }
5142 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5143 final File publicSourceFile = new File(publicSourceDir);
5144 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005145 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 }
5147 if (publicSourceFile.exists()) {
5148 publicSourceFile.delete();
5149 }
5150 }
5151 return ret;
5152 }
5153
5154 void cleanUpResourcesLI() {
5155 String sourceDir = getCodePath();
5156 if (cleanUp() && mInstaller != null) {
5157 int retCode = mInstaller.rmdex(sourceDir);
5158 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005159 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005160 + " at location "
5161 + sourceDir + ", retcode=" + retCode);
5162 // we don't consider this to be a failure of the core package deletion
5163 }
5164 }
5165 }
5166
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005167 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 // TODO Do this in a more elegant way later on. for now just a hack
5169 if (!isFwdLocked(flags)) {
5170 final int filePermissions =
5171 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5172 |FileUtils.S_IROTH;
5173 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5174 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005175 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 getCodePath()
5177 + ". The return code was: " + retCode);
5178 // TODO Define new internal error
5179 return false;
5180 }
5181 return true;
5182 }
5183 return true;
5184 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005185
5186 boolean doPostDeleteLI(boolean delete) {
5187 cleanUpResourcesLI();
5188 return true;
5189 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 }
5191
5192 class SdInstallArgs extends InstallArgs {
5193 String cid;
5194 String cachePath;
5195 static final String RES_FILE_NAME = "pkg.apk";
5196
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005197 SdInstallArgs(InstallParams params) {
5198 super(params.packageURI, params.observer,
5199 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005200 }
5201
5202 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005203 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005204 // Extract cid from fullCodePath
5205 int eidx = fullCodePath.lastIndexOf("/");
5206 String subStr1 = fullCodePath.substring(0, eidx);
5207 int sidx = subStr1.lastIndexOf("/");
5208 cid = subStr1.substring(sidx+1, eidx);
5209 cachePath = subStr1;
5210 }
5211
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005212 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005213 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5214 this.cid = cid;
5215 }
5216
5217 SdInstallArgs(Uri packageURI, String cid) {
5218 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005219 this.cid = cid;
5220 }
5221
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 void createCopyFile() {
5223 cid = getTempContainerId();
5224 }
5225
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005226 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5227 return imcs.checkFreeStorage(true, packageURI);
5228 }
5229
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005230 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005231 if (temp) {
5232 createCopyFile();
5233 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005234 cachePath = imcs.copyResourceToContainer(
5235 packageURI, cid,
5236 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5238 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 }
5240
5241 @Override
5242 String getCodePath() {
5243 return cachePath + "/" + RES_FILE_NAME;
5244 }
5245
5246 @Override
5247 String getResourcePath() {
5248 return cachePath + "/" + RES_FILE_NAME;
5249 }
5250
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005251 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005252 if (status != PackageManager.INSTALL_SUCCEEDED) {
5253 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005254 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005255 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005256 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005257 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005258 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005259 if (cachePath == null) {
5260 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5261 }
5262 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005263 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005264 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 }
5266
5267 boolean doRename(int status, final String pkgName,
5268 String oldCodePath) {
5269 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005270 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005271 if (PackageHelper.isContainerMounted(cid)) {
5272 // Unmount the container
5273 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005274 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005275 return false;
5276 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005277 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005278 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005279 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5280 " which might be stale. Will try to clean up.");
5281 // Clean up the stale container and proceed to recreate.
5282 if (!PackageHelper.destroySdDir(newCacheId)) {
5283 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5284 return false;
5285 }
5286 // Successfully cleaned up stale container. Try to rename again.
5287 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5288 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5289 + " inspite of cleaning it up.");
5290 return false;
5291 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005292 }
5293 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005294 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005295 newCachePath = PackageHelper.mountSdDir(newCacheId,
5296 getEncryptKey(), Process.SYSTEM_UID);
5297 } else {
5298 newCachePath = PackageHelper.getSdDir(newCacheId);
5299 }
5300 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005301 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005302 return false;
5303 }
5304 Log.i(TAG, "Succesfully renamed " + cid +
5305 " at path: " + cachePath + " to " + newCacheId +
5306 " at new path: " + newCachePath);
5307 cid = newCacheId;
5308 cachePath = newCachePath;
5309 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005310 }
5311
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005312 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 if (status != PackageManager.INSTALL_SUCCEEDED) {
5314 cleanUp();
5315 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005316 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005317 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005318 PackageHelper.mountSdDir(cid,
5319 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005320 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005322 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005323 }
5324
5325 private void cleanUp() {
5326 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005327 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005328 }
5329
5330 void cleanUpResourcesLI() {
5331 String sourceFile = getCodePath();
5332 // Remove dex file
5333 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005334 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005336 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005337 + " at location "
5338 + sourceFile.toString() + ", retcode=" + retCode);
5339 // we don't consider this to be a failure of the core package deletion
5340 }
5341 }
5342 cleanUp();
5343 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005344
5345 boolean matchContainer(String app) {
5346 if (cid.startsWith(app)) {
5347 return true;
5348 }
5349 return false;
5350 }
5351
5352 String getPackageName() {
5353 int idx = cid.lastIndexOf("-");
5354 if (idx == -1) {
5355 return cid;
5356 }
5357 return cid.substring(0, idx);
5358 }
5359
5360 boolean doPostDeleteLI(boolean delete) {
5361 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005362 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005363 if (mounted) {
5364 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005365 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005366 }
5367 if (ret && delete) {
5368 cleanUpResourcesLI();
5369 }
5370 return ret;
5371 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 };
5373
5374 // Utility method used to create code paths based on package name and available index.
5375 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5376 String idxStr = "";
5377 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005378 // Fall back to default value of idx=1 if prefix is not
5379 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005380 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005381 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005382 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005383 if (subStr.endsWith(suffix)) {
5384 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005385 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005386 // If oldCodePath already contains prefix find out the
5387 // ending index to either increment or decrement.
5388 int sidx = subStr.lastIndexOf(prefix);
5389 if (sidx != -1) {
5390 subStr = subStr.substring(sidx + prefix.length());
5391 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005392 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5393 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005395 try {
5396 idx = Integer.parseInt(subStr);
5397 if (idx <= 1) {
5398 idx++;
5399 } else {
5400 idx--;
5401 }
5402 } catch(NumberFormatException e) {
5403 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005404 }
5405 }
5406 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005407 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005408 return prefix + idxStr;
5409 }
5410
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005411 // Utility method used to ignore ADD/REMOVE events
5412 // by directory observer.
5413 private static boolean ignoreCodePath(String fullPathStr) {
5414 String apkName = getApkName(fullPathStr);
5415 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5416 if (idx != -1 && ((idx+1) < apkName.length())) {
5417 // Make sure the package ends with a numeral
5418 String version = apkName.substring(idx+1);
5419 try {
5420 Integer.parseInt(version);
5421 return true;
5422 } catch (NumberFormatException e) {}
5423 }
5424 return false;
5425 }
5426
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005427 // Utility method that returns the relative package path with respect
5428 // to the installation directory. Like say for /data/data/com.test-1.apk
5429 // string com.test-1 is returned.
5430 static String getApkName(String codePath) {
5431 if (codePath == null) {
5432 return null;
5433 }
5434 int sidx = codePath.lastIndexOf("/");
5435 int eidx = codePath.lastIndexOf(".");
5436 if (eidx == -1) {
5437 eidx = codePath.length();
5438 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005439 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005440 return null;
5441 }
5442 return codePath.substring(sidx+1, eidx);
5443 }
5444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 class PackageInstalledInfo {
5446 String name;
5447 int uid;
5448 PackageParser.Package pkg;
5449 int returnCode;
5450 PackageRemovedInfo removedInfo;
5451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 /*
5454 * Install a non-existing package.
5455 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005456 private void installNewPackageLI(PackageParser.Package pkg,
5457 int parseFlags,
5458 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005459 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005461 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005462
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005463 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 res.name = pkgName;
5465 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005466 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5467 // A package with the same name is already installed, though
5468 // it has been renamed to an older name. The package we
5469 // are trying to install should be installed as an update to
5470 // the existing one, but that has not been requested, so bail.
5471 Slog.w(TAG, "Attempt to re-install " + pkgName
5472 + " without first uninstalling package running as "
5473 + mSettings.mRenamedPackages.get(pkgName));
5474 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5475 return;
5476 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005477 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005479 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 + " without first uninstalling.");
5481 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5482 return;
5483 }
5484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005486 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005488 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5490 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5491 }
5492 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005493 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005494 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 res);
5496 // delete the partially installed application. the data directory will have to be
5497 // restored if it was already existing
5498 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5499 // remove package from internal structures. Note that we want deletePackageX to
5500 // delete the package data and cache directories that it created in
5501 // scanPackageLocked, unless those directories existed before we even tried to
5502 // install.
5503 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005504 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5506 res.removedInfo);
5507 }
5508 }
5509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005510
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005511 private void replacePackageLI(PackageParser.Package pkg,
5512 int parseFlags,
5513 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005514 String installerPackageName, PackageInstalledInfo res) {
5515
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005516 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005517 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 // First find the old package info and check signatures
5519 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005520 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005521 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005522 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5524 return;
5525 }
5526 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005527 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005528 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 }
5533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 PackageParser.Package pkg,
5537 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005538 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 PackageParser.Package newPackage = null;
5540 String pkgName = deletedPackage.packageName;
5541 boolean deletedPkg = true;
5542 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005543
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 String oldInstallerPackageName = null;
5545 synchronized (mPackages) {
5546 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005550 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 res.removedInfo)) {
5552 // If the existing package was'nt successfully deleted
5553 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5554 deletedPkg = false;
5555 } else {
5556 // Successfully deleted the old package. Now proceed with re-installation
5557 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005558 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005560 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5562 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005563 }
5564 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005565 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005566 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 res);
5568 updatedSettings = true;
5569 }
5570 }
5571
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005572 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 // remove package from internal structures. Note that we want deletePackageX to
5574 // delete the package data and cache directories that it created in
5575 // scanPackageLocked, unless those directories existed before we even tried to
5576 // install.
5577 if(updatedSettings) {
5578 deletePackageLI(
5579 pkgName, true,
5580 PackageManager.DONT_DELETE_DATA,
5581 res.removedInfo);
5582 }
5583 // Since we failed to install the new package we need to restore the old
5584 // package that we deleted.
5585 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005586 File restoreFile = new File(deletedPackage.mPath);
5587 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005588 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005589 return;
5590 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005591 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005592 boolean oldOnSd = isExternal(deletedPackage);
5593 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5594 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5595 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5596 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5597 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5598 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5599 return;
5600 }
5601 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005602 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005603 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5604 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005605 mSettings.writeLP();
5606 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005607 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 }
5609 }
5610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005613 PackageParser.Package pkg,
5614 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005615 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 PackageParser.Package newPackage = null;
5617 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 PackageParser.PARSE_IS_SYSTEM;
5620 String packageName = deletedPackage.packageName;
5621 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5622 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005623 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 return;
5625 }
5626 PackageParser.Package oldPkg;
5627 PackageSetting oldPkgSetting;
5628 synchronized (mPackages) {
5629 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005630 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5632 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005633 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 return;
5635 }
5636 }
5637 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5638 res.removedInfo.removedPackage = packageName;
5639 // Remove existing system package
5640 removePackageLI(oldPkg, true);
5641 synchronized (mPackages) {
5642 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5643 }
5644
5645 // Successfully disabled the old package. Now proceed with re-installation
5646 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5647 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005648 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005650 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5652 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5653 }
5654 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005655 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 updatedSettings = true;
5657 }
5658
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005659 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 // Re installation failed. Restore old information
5661 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005662 if (newPackage != null) {
5663 removePackageLI(newPackage, true);
5664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005666 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005668 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 // Restore the old system information in Settings
5670 synchronized(mPackages) {
5671 if(updatedSettings) {
5672 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005673 mSettings.setInstallerPackageName(packageName,
5674 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 }
5676 mSettings.writeLP();
5677 }
5678 }
5679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005680
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005681 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005682 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005683 int retCode;
5684 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5685 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5686 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005687 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005688 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5689 }
5690 }
5691 return PackageManager.INSTALL_SUCCEEDED;
5692 }
5693
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005694 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005695 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005696 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 synchronized (mPackages) {
5698 //write settings. the installStatus will be incomplete at this stage.
5699 //note that the new package setting would have already been
5700 //added to mPackages. It hasn't been persisted yet.
5701 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5702 mSettings.writeLP();
5703 }
5704
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005705 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005706 != PackageManager.INSTALL_SUCCEEDED) {
5707 // Discontinue if moving dex files failed.
5708 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005710 if((res.returnCode = setPermissionsLI(newPackage))
5711 != PackageManager.INSTALL_SUCCEEDED) {
5712 if (mInstaller != null) {
5713 mInstaller.rmdex(newPackage.mScanPath);
5714 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005715 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005717 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005720 updatePermissionsLP(newPackage.packageName, newPackage,
5721 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 res.name = pkgName;
5723 res.uid = newPackage.applicationInfo.uid;
5724 res.pkg = newPackage;
5725 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005726 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5728 //to update install status
5729 mSettings.writeLP();
5730 }
5731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005732
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005733 private void installPackageLI(InstallArgs args,
5734 boolean newInstall, PackageInstalledInfo res) {
5735 int pFlags = args.flags;
5736 String installerPackageName = args.installerPackageName;
5737 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005738 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005739 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005740 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005741 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005742 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005743 // Result object to be returned
5744 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5745
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005746 // Retrieve PackageSettings and parse package
5747 int parseFlags = PackageParser.PARSE_CHATTY |
5748 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5749 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5750 parseFlags |= mDefParseFlags;
5751 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5752 pp.setSeparateProcesses(mSeparateProcesses);
5753 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5754 null, mMetrics, parseFlags);
5755 if (pkg == null) {
5756 res.returnCode = pp.getParseError();
5757 return;
5758 }
5759 String pkgName = res.name = pkg.packageName;
5760 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5761 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5762 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5763 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005765 }
5766 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5767 res.returnCode = pp.getParseError();
5768 return;
5769 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005770 // Get rid of all references to package scan path via parser.
5771 pp = null;
5772 String oldCodePath = null;
5773 boolean systemApp = false;
5774 synchronized (mPackages) {
5775 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005776 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5777 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005778 if (pkg.mOriginalPackages != null
5779 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005780 && mPackages.containsKey(oldName)) {
5781 // This package is derived from an original package,
5782 // and this device has been updating from that original
5783 // name. We must continue using the original name, so
5784 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005785 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005786 pkgName = pkg.packageName;
5787 replace = true;
5788 } else if (mPackages.containsKey(pkgName)) {
5789 // This package, under its official name, already exists
5790 // on the device; we should replace it.
5791 replace = true;
5792 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005793 }
5794 PackageSetting ps = mSettings.mPackages.get(pkgName);
5795 if (ps != null) {
5796 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5797 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5798 systemApp = (ps.pkg.applicationInfo.flags &
5799 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005800 }
5801 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005802 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005803
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005804 if (systemApp && onSd) {
5805 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005806 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005807 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5808 return;
5809 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005810
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005811 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5812 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5813 return;
5814 }
5815 // Set application objects path explicitly after the rename
5816 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005817 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005818 replacePackageLI(pkg, parseFlags, scanMode,
5819 installerPackageName, res);
5820 } else {
5821 installNewPackageLI(pkg, parseFlags, scanMode,
5822 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 }
5824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005825
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005826 private int setPermissionsLI(PackageParser.Package newPackage) {
5827 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005828 int retCode = 0;
5829 // TODO Gross hack but fix later. Ideally move this to be a post installation
5830 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005831 if ((newPackage.applicationInfo.flags
5832 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5833 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 try {
5835 extractPublicFiles(newPackage, destResourceFile);
5836 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005837 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 -08005838 " forward-locked app.");
5839 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5840 } finally {
5841 //TODO clean up the extracted public files
5842 }
5843 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005844 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 newPackage.applicationInfo.uid);
5846 } else {
5847 final int filePermissions =
5848 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005849 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 newPackage.applicationInfo.uid);
5851 }
5852 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005853 // The permissions on the resource file was set when it was copied for
5854 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005858 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005859 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861 // TODO Define new internal error
5862 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 }
5864 return PackageManager.INSTALL_SUCCEEDED;
5865 }
5866
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005867 private boolean isForwardLocked(PackageParser.Package pkg) {
5868 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 }
5870
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005871 private boolean isExternal(PackageParser.Package pkg) {
5872 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
5873 }
5874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 private void extractPublicFiles(PackageParser.Package newPackage,
5876 File publicZipFile) throws IOException {
5877 final ZipOutputStream publicZipOutStream =
5878 new ZipOutputStream(new FileOutputStream(publicZipFile));
5879 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5880
5881 // Copy manifest, resources.arsc and res directory to public zip
5882
5883 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5884 while (privateZipEntries.hasMoreElements()) {
5885 final ZipEntry zipEntry = privateZipEntries.nextElement();
5886 final String zipEntryName = zipEntry.getName();
5887 if ("AndroidManifest.xml".equals(zipEntryName)
5888 || "resources.arsc".equals(zipEntryName)
5889 || zipEntryName.startsWith("res/")) {
5890 try {
5891 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5892 } catch (IOException e) {
5893 try {
5894 publicZipOutStream.close();
5895 throw e;
5896 } finally {
5897 publicZipFile.delete();
5898 }
5899 }
5900 }
5901 }
5902
5903 publicZipOutStream.close();
5904 FileUtils.setPermissions(
5905 publicZipFile.getAbsolutePath(),
5906 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5907 -1, -1);
5908 }
5909
5910 private static void copyZipEntry(ZipEntry zipEntry,
5911 ZipFile inZipFile,
5912 ZipOutputStream outZipStream) throws IOException {
5913 byte[] buffer = new byte[4096];
5914 int num;
5915
5916 ZipEntry newEntry;
5917 if (zipEntry.getMethod() == ZipEntry.STORED) {
5918 // Preserve the STORED method of the input entry.
5919 newEntry = new ZipEntry(zipEntry);
5920 } else {
5921 // Create a new entry so that the compressed len is recomputed.
5922 newEntry = new ZipEntry(zipEntry.getName());
5923 }
5924 outZipStream.putNextEntry(newEntry);
5925
5926 InputStream data = inZipFile.getInputStream(zipEntry);
5927 while ((num = data.read(buffer)) > 0) {
5928 outZipStream.write(buffer, 0, num);
5929 }
5930 outZipStream.flush();
5931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 private void deleteTempPackageFiles() {
5934 FilenameFilter filter = new FilenameFilter() {
5935 public boolean accept(File dir, String name) {
5936 return name.startsWith("vmdl") && name.endsWith(".tmp");
5937 }
5938 };
5939 String tmpFilesList[] = mAppInstallDir.list(filter);
5940 if(tmpFilesList == null) {
5941 return;
5942 }
5943 for(int i = 0; i < tmpFilesList.length; i++) {
5944 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5945 tmpFile.delete();
5946 }
5947 }
5948
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005949 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 File tmpPackageFile;
5951 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005952 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005954 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 return null;
5956 }
5957 try {
5958 FileUtils.setPermissions(
5959 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5960 -1, -1);
5961 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005962 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 return null;
5964 }
5965 return tmpPackageFile;
5966 }
5967
5968 public void deletePackage(final String packageName,
5969 final IPackageDeleteObserver observer,
5970 final int flags) {
5971 mContext.enforceCallingOrSelfPermission(
5972 android.Manifest.permission.DELETE_PACKAGES, null);
5973 // Queue up an async operation since the package deletion may take a little while.
5974 mHandler.post(new Runnable() {
5975 public void run() {
5976 mHandler.removeCallbacks(this);
5977 final boolean succeded = deletePackageX(packageName, true, true, flags);
5978 if (observer != null) {
5979 try {
5980 observer.packageDeleted(succeded);
5981 } catch (RemoteException e) {
5982 Log.i(TAG, "Observer no longer exists.");
5983 } //end catch
5984 } //end if
5985 } //end run
5986 });
5987 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 /**
5990 * This method is an internal method that could be get invoked either
5991 * to delete an installed package or to clean up a failed installation.
5992 * After deleting an installed package, a broadcast is sent to notify any
5993 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005994 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 * installation wouldn't have sent the initial broadcast either
5996 * The key steps in deleting a package are
5997 * deleting the package information in internal structures like mPackages,
5998 * deleting the packages base directories through installd
5999 * updating mSettings to reflect current status
6000 * persisting settings for later use
6001 * sending a broadcast if necessary
6002 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6004 boolean deleteCodeAndResources, int flags) {
6005 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006006 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006008 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6009 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6010 try {
6011 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006012 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006013 return false;
6014 }
6015 } catch (RemoteException e) {
6016 }
6017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 synchronized (mInstallLock) {
6019 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6020 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006023 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6024 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6025
6026 // If the removed package was a system update, the old system packaged
6027 // was re-enabled; we need to broadcast this information
6028 if (systemUpdate) {
6029 Bundle extras = new Bundle(1);
6030 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6031 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6032
6033 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
6034 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
6035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006037 // Force a gc here.
6038 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006039 // Delete the resources here after sending the broadcast to let
6040 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006041 if (info.args != null) {
6042 synchronized (mInstallLock) {
6043 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006044 }
6045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 return res;
6047 }
6048
6049 static class PackageRemovedInfo {
6050 String removedPackage;
6051 int uid = -1;
6052 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006053 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006054 // Clean up resources deleted packages.
6055 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 void sendBroadcast(boolean fullRemove, boolean replacing) {
6058 Bundle extras = new Bundle(1);
6059 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6060 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6061 if (replacing) {
6062 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6063 }
6064 if (removedPackage != null) {
6065 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6066 }
6067 if (removedUid >= 0) {
6068 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6069 }
6070 }
6071 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 /*
6074 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6075 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006076 * 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 -08006077 * delete a partially installed application.
6078 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006079 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 int flags) {
6081 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006082 if (outInfo != null) {
6083 outInfo.removedPackage = packageName;
6084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 removePackageLI(p, true);
6086 // Retrieve object to delete permissions for shared user later on
6087 PackageSetting deletedPs;
6088 synchronized (mPackages) {
6089 deletedPs = mSettings.mPackages.get(packageName);
6090 }
6091 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6092 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006093 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006095 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 + packageName + ", retcode=" + retCode);
6097 // we don't consider this to be a failure of the core package deletion
6098 }
6099 } else {
6100 //for emulator
6101 PackageParser.Package pkg = mPackages.get(packageName);
6102 File dataDir = new File(pkg.applicationInfo.dataDir);
6103 dataDir.delete();
6104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
6106 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006107 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006108 schedulePackageCleaning(packageName);
6109
6110 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6111 if (outInfo != null) {
6112 outInfo.removedUid = mSettings.removePackageLP(packageName);
6113 }
6114 if (deletedPs != null) {
6115 updatePermissionsLP(deletedPs.name, null, false, false);
6116 if (deletedPs.sharedUser != null) {
6117 // remove permissions associated with package
6118 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6119 }
6120 }
6121 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006122 // remove from preferred activities.
6123 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6124 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6125 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6126 removed.add(pa);
6127 }
6128 }
6129 for (PreferredActivity pa : removed) {
6130 mSettings.mPreferredActivities.removeFilter(pa);
6131 }
6132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006134 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 }
6136 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 /*
6139 * Tries to delete system package.
6140 */
6141 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006142 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 ApplicationInfo applicationInfo = p.applicationInfo;
6144 //applicable for non-partially installed applications only
6145 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006146 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 return false;
6148 }
6149 PackageSetting ps = null;
6150 // Confirm if the system package has been updated
6151 // An updated system app can be deleted. This will also have to restore
6152 // the system pkg from system partition
6153 synchronized (mPackages) {
6154 ps = mSettings.getDisabledSystemPkg(p.packageName);
6155 }
6156 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006157 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 return false;
6159 } else {
6160 Log.i(TAG, "Deleting system pkg from data partition");
6161 }
6162 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006163 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006164 boolean deleteCodeAndResources = false;
6165 if (ps.versionCode < p.mVersionCode) {
6166 // Delete code and resources for downgrades
6167 deleteCodeAndResources = true;
6168 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6169 flags &= ~PackageManager.DONT_DELETE_DATA;
6170 }
6171 } else {
6172 // Preserve data by setting flag
6173 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6174 flags |= PackageManager.DONT_DELETE_DATA;
6175 }
6176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6178 if (!ret) {
6179 return false;
6180 }
6181 synchronized (mPackages) {
6182 // Reinstate the old system package
6183 mSettings.enableSystemPackageLP(p.packageName);
6184 }
6185 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006186 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006188 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006190 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006191 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 return false;
6193 }
6194 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006195 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 mSettings.writeLP();
6197 }
6198 return true;
6199 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6202 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6203 ApplicationInfo applicationInfo = p.applicationInfo;
6204 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006205 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 return false;
6207 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006208 if (outInfo != null) {
6209 outInfo.uid = applicationInfo.uid;
6210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211
6212 // Delete package data from internal structures and also remove data if flag is set
6213 removePackageDataLI(p, outInfo, flags);
6214
6215 // Delete application code and resources
6216 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006217 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006218 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006219 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006220 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6221 PackageManager.INSTALL_FORWARD_LOCK : 0;
6222 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006223 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 }
6225 return true;
6226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 /*
6229 * This method handles package deletion in general
6230 */
6231 private boolean deletePackageLI(String packageName,
6232 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6233 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006234 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 return false;
6236 }
6237 PackageParser.Package p;
6238 boolean dataOnly = false;
6239 synchronized (mPackages) {
6240 p = mPackages.get(packageName);
6241 if (p == null) {
6242 //this retrieves partially installed apps
6243 dataOnly = true;
6244 PackageSetting ps = mSettings.mPackages.get(packageName);
6245 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006246 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 return false;
6248 }
6249 p = ps.pkg;
6250 }
6251 }
6252 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006253 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 return false;
6255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 if (dataOnly) {
6258 // Delete application data first
6259 removePackageDataLI(p, outInfo, flags);
6260 return true;
6261 }
6262 // At this point the package should have ApplicationInfo associated with it
6263 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006264 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 return false;
6266 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006267 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6269 Log.i(TAG, "Removing system package:"+p.packageName);
6270 // When an updated system application is deleted we delete the existing resources as well and
6271 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006272 ret = deleteSystemPackageLI(p, flags, outInfo);
6273 } else {
6274 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006275 // Kill application pre-emptively especially for apps on sd.
6276 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006277 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006279 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 public void clearApplicationUserData(final String packageName,
6283 final IPackageDataObserver observer) {
6284 mContext.enforceCallingOrSelfPermission(
6285 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6286 // Queue up an async operation since the package deletion may take a little while.
6287 mHandler.post(new Runnable() {
6288 public void run() {
6289 mHandler.removeCallbacks(this);
6290 final boolean succeeded;
6291 synchronized (mInstallLock) {
6292 succeeded = clearApplicationUserDataLI(packageName);
6293 }
6294 if (succeeded) {
6295 // invoke DeviceStorageMonitor's update method to clear any notifications
6296 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6297 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6298 if (dsm != null) {
6299 dsm.updateMemory();
6300 }
6301 }
6302 if(observer != null) {
6303 try {
6304 observer.onRemoveCompleted(packageName, succeeded);
6305 } catch (RemoteException e) {
6306 Log.i(TAG, "Observer no longer exists.");
6307 }
6308 } //end if observer
6309 } //end run
6310 });
6311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 private boolean clearApplicationUserDataLI(String packageName) {
6314 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006315 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 return false;
6317 }
6318 PackageParser.Package p;
6319 boolean dataOnly = false;
6320 synchronized (mPackages) {
6321 p = mPackages.get(packageName);
6322 if(p == null) {
6323 dataOnly = true;
6324 PackageSetting ps = mSettings.mPackages.get(packageName);
6325 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006326 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 return false;
6328 }
6329 p = ps.pkg;
6330 }
6331 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 if(!dataOnly) {
6334 //need to check this only for fully installed applications
6335 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006336 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 return false;
6338 }
6339 final ApplicationInfo applicationInfo = p.applicationInfo;
6340 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006341 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 return false;
6343 }
6344 }
6345 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006346 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006348 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 + packageName);
6350 return false;
6351 }
6352 }
6353 return true;
6354 }
6355
6356 public void deleteApplicationCacheFiles(final String packageName,
6357 final IPackageDataObserver observer) {
6358 mContext.enforceCallingOrSelfPermission(
6359 android.Manifest.permission.DELETE_CACHE_FILES, null);
6360 // Queue up an async operation since the package deletion may take a little while.
6361 mHandler.post(new Runnable() {
6362 public void run() {
6363 mHandler.removeCallbacks(this);
6364 final boolean succeded;
6365 synchronized (mInstallLock) {
6366 succeded = deleteApplicationCacheFilesLI(packageName);
6367 }
6368 if(observer != null) {
6369 try {
6370 observer.onRemoveCompleted(packageName, succeded);
6371 } catch (RemoteException e) {
6372 Log.i(TAG, "Observer no longer exists.");
6373 }
6374 } //end if observer
6375 } //end run
6376 });
6377 }
6378
6379 private boolean deleteApplicationCacheFilesLI(String packageName) {
6380 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006381 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 return false;
6383 }
6384 PackageParser.Package p;
6385 synchronized (mPackages) {
6386 p = mPackages.get(packageName);
6387 }
6388 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006389 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 return false;
6391 }
6392 final ApplicationInfo applicationInfo = p.applicationInfo;
6393 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return false;
6396 }
6397 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006398 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006400 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 + packageName);
6402 return false;
6403 }
6404 }
6405 return true;
6406 }
6407
6408 public void getPackageSizeInfo(final String packageName,
6409 final IPackageStatsObserver observer) {
6410 mContext.enforceCallingOrSelfPermission(
6411 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6412 // Queue up an async operation since the package deletion may take a little while.
6413 mHandler.post(new Runnable() {
6414 public void run() {
6415 mHandler.removeCallbacks(this);
6416 PackageStats lStats = new PackageStats(packageName);
6417 final boolean succeded;
6418 synchronized (mInstallLock) {
6419 succeded = getPackageSizeInfoLI(packageName, lStats);
6420 }
6421 if(observer != null) {
6422 try {
6423 observer.onGetStatsCompleted(lStats, succeded);
6424 } catch (RemoteException e) {
6425 Log.i(TAG, "Observer no longer exists.");
6426 }
6427 } //end if observer
6428 } //end run
6429 });
6430 }
6431
6432 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6433 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006434 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006435 return false;
6436 }
6437 PackageParser.Package p;
6438 boolean dataOnly = false;
6439 synchronized (mPackages) {
6440 p = mPackages.get(packageName);
6441 if(p == null) {
6442 dataOnly = true;
6443 PackageSetting ps = mSettings.mPackages.get(packageName);
6444 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006445 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 return false;
6447 }
6448 p = ps.pkg;
6449 }
6450 }
6451 String publicSrcDir = null;
6452 if(!dataOnly) {
6453 final ApplicationInfo applicationInfo = p.applicationInfo;
6454 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006455 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 return false;
6457 }
6458 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6459 }
6460 if (mInstaller != null) {
6461 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006462 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 if (res < 0) {
6464 return false;
6465 } else {
6466 return true;
6467 }
6468 }
6469 return true;
6470 }
6471
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 public void addPackageToPreferred(String packageName) {
6474 mContext.enforceCallingOrSelfPermission(
6475 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006476 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 }
6478
6479 public void removePackageFromPreferred(String packageName) {
6480 mContext.enforceCallingOrSelfPermission(
6481 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006482 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 }
6484
6485 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006486 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 int getUidTargetSdkVersionLockedLP(int uid) {
6490 Object obj = mSettings.getUserIdLP(uid);
6491 if (obj instanceof SharedUserSetting) {
6492 SharedUserSetting sus = (SharedUserSetting)obj;
6493 final int N = sus.packages.size();
6494 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6495 Iterator<PackageSetting> it = sus.packages.iterator();
6496 int i=0;
6497 while (it.hasNext()) {
6498 PackageSetting ps = it.next();
6499 if (ps.pkg != null) {
6500 int v = ps.pkg.applicationInfo.targetSdkVersion;
6501 if (v < vers) vers = v;
6502 }
6503 }
6504 return vers;
6505 } else if (obj instanceof PackageSetting) {
6506 PackageSetting ps = (PackageSetting)obj;
6507 if (ps.pkg != null) {
6508 return ps.pkg.applicationInfo.targetSdkVersion;
6509 }
6510 }
6511 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6512 }
6513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 public void addPreferredActivity(IntentFilter filter, int match,
6515 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 if (mContext.checkCallingOrSelfPermission(
6518 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6519 != PackageManager.PERMISSION_GRANTED) {
6520 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6521 < Build.VERSION_CODES.FROYO) {
6522 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6523 + Binder.getCallingUid());
6524 return;
6525 }
6526 mContext.enforceCallingOrSelfPermission(
6527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6528 }
6529
6530 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6532 mSettings.mPreferredActivities.addFilter(
6533 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006534 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 }
6536 }
6537
Satish Sampath8dbe6122009-06-02 23:35:54 +01006538 public void replacePreferredActivity(IntentFilter filter, int match,
6539 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006540 if (filter.countActions() != 1) {
6541 throw new IllegalArgumentException(
6542 "replacePreferredActivity expects filter to have only 1 action.");
6543 }
6544 if (filter.countCategories() != 1) {
6545 throw new IllegalArgumentException(
6546 "replacePreferredActivity expects filter to have only 1 category.");
6547 }
6548 if (filter.countDataAuthorities() != 0
6549 || filter.countDataPaths() != 0
6550 || filter.countDataSchemes() != 0
6551 || filter.countDataTypes() != 0) {
6552 throw new IllegalArgumentException(
6553 "replacePreferredActivity expects filter to have no data authorities, " +
6554 "paths, schemes or types.");
6555 }
6556 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006557 if (mContext.checkCallingOrSelfPermission(
6558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6559 != PackageManager.PERMISSION_GRANTED) {
6560 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6561 < Build.VERSION_CODES.FROYO) {
6562 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6563 + Binder.getCallingUid());
6564 return;
6565 }
6566 mContext.enforceCallingOrSelfPermission(
6567 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6568 }
6569
Satish Sampath8dbe6122009-06-02 23:35:54 +01006570 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6571 String action = filter.getAction(0);
6572 String category = filter.getCategory(0);
6573 while (it.hasNext()) {
6574 PreferredActivity pa = it.next();
6575 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6576 it.remove();
6577 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6578 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6579 }
6580 }
6581 addPreferredActivity(filter, match, set, activity);
6582 }
6583 }
6584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006587 int uid = Binder.getCallingUid();
6588 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006589 if (pkg == null || pkg.applicationInfo.uid != uid) {
6590 if (mContext.checkCallingOrSelfPermission(
6591 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6592 != PackageManager.PERMISSION_GRANTED) {
6593 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6594 < Build.VERSION_CODES.FROYO) {
6595 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6596 + Binder.getCallingUid());
6597 return;
6598 }
6599 mContext.enforceCallingOrSelfPermission(
6600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6601 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006602 }
6603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006605 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
6607 }
6608 }
6609
6610 boolean clearPackagePreferredActivitiesLP(String packageName) {
6611 boolean changed = false;
6612 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6613 while (it.hasNext()) {
6614 PreferredActivity pa = it.next();
6615 if (pa.mActivity.getPackageName().equals(packageName)) {
6616 it.remove();
6617 changed = true;
6618 }
6619 }
6620 return changed;
6621 }
6622
6623 public int getPreferredActivities(List<IntentFilter> outFilters,
6624 List<ComponentName> outActivities, String packageName) {
6625
6626 int num = 0;
6627 synchronized (mPackages) {
6628 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6629 while (it.hasNext()) {
6630 PreferredActivity pa = it.next();
6631 if (packageName == null
6632 || pa.mActivity.getPackageName().equals(packageName)) {
6633 if (outFilters != null) {
6634 outFilters.add(new IntentFilter(pa));
6635 }
6636 if (outActivities != null) {
6637 outActivities.add(pa.mActivity);
6638 }
6639 }
6640 }
6641 }
6642
6643 return num;
6644 }
6645
6646 public void setApplicationEnabledSetting(String appPackageName,
6647 int newState, int flags) {
6648 setEnabledSetting(appPackageName, null, newState, flags);
6649 }
6650
6651 public void setComponentEnabledSetting(ComponentName componentName,
6652 int newState, int flags) {
6653 setEnabledSetting(componentName.getPackageName(),
6654 componentName.getClassName(), newState, flags);
6655 }
6656
6657 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006658 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6660 || newState == COMPONENT_ENABLED_STATE_ENABLED
6661 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6662 throw new IllegalArgumentException("Invalid new component state: "
6663 + newState);
6664 }
6665 PackageSetting pkgSetting;
6666 final int uid = Binder.getCallingUid();
6667 final int permission = mContext.checkCallingPermission(
6668 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6669 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006670 boolean sendNow = false;
6671 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006672 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006674 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006676 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006680 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 }
6682 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006683 "Unknown component: " + packageName
6684 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 }
6686 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6687 throw new SecurityException(
6688 "Permission Denial: attempt to change component state from pid="
6689 + Binder.getCallingPid()
6690 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6691 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006692 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006694 if (pkgSetting.enabled == newState) {
6695 // Nothing to do
6696 return;
6697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 pkgSetting.enabled = newState;
6699 } else {
6700 // We're dealing with a component level state change
6701 switch (newState) {
6702 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006703 if (!pkgSetting.enableComponentLP(className)) {
6704 return;
6705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 break;
6707 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006708 if (!pkgSetting.disableComponentLP(className)) {
6709 return;
6710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 break;
6712 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006713 if (!pkgSetting.restoreComponentLP(className)) {
6714 return;
6715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 break;
6717 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006718 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006719 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 }
6721 }
6722 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006723 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006724 components = mPendingBroadcasts.get(packageName);
6725 boolean newPackage = components == null;
6726 if (newPackage) {
6727 components = new ArrayList<String>();
6728 }
6729 if (!components.contains(componentName)) {
6730 components.add(componentName);
6731 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6733 sendNow = true;
6734 // Purge entry from pending broadcast list if another one exists already
6735 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006736 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006737 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006738 if (newPackage) {
6739 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006740 }
6741 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6742 // Schedule a message
6743 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6744 }
6745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 long callingId = Binder.clearCallingIdentity();
6749 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006750 if (sendNow) {
6751 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006752 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 } finally {
6755 Binder.restoreCallingIdentity(callingId);
6756 }
6757 }
6758
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006760 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6761 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6762 + " components=" + componentNames);
6763 Bundle extras = new Bundle(4);
6764 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6765 String nameList[] = new String[componentNames.size()];
6766 componentNames.toArray(nameList);
6767 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6769 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006770 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006771 }
6772
Jacek Surazski65e13172009-04-28 15:26:38 +02006773 public String getInstallerPackageName(String packageName) {
6774 synchronized (mPackages) {
6775 PackageSetting pkg = mSettings.mPackages.get(packageName);
6776 if (pkg == null) {
6777 throw new IllegalArgumentException("Unknown package: " + packageName);
6778 }
6779 return pkg.installerPackageName;
6780 }
6781 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 public int getApplicationEnabledSetting(String appPackageName) {
6784 synchronized (mPackages) {
6785 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6786 if (pkg == null) {
6787 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6788 }
6789 return pkg.enabled;
6790 }
6791 }
6792
6793 public int getComponentEnabledSetting(ComponentName componentName) {
6794 synchronized (mPackages) {
6795 final String packageNameStr = componentName.getPackageName();
6796 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6797 if (pkg == null) {
6798 throw new IllegalArgumentException("Unknown component: " + componentName);
6799 }
6800 final String classNameStr = componentName.getClassName();
6801 return pkg.currentEnabledStateLP(classNameStr);
6802 }
6803 }
6804
6805 public void enterSafeMode() {
6806 if (!mSystemReady) {
6807 mSafeMode = true;
6808 }
6809 }
6810
6811 public void systemReady() {
6812 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006813
6814 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006815 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006816 mContext.getContentResolver(),
6817 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006818 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006819 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006820 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006822 }
6823
6824 public boolean isSafeMode() {
6825 return mSafeMode;
6826 }
6827
6828 public boolean hasSystemUidErrors() {
6829 return mHasSystemUidErrors;
6830 }
6831
6832 static String arrayToString(int[] array) {
6833 StringBuffer buf = new StringBuffer(128);
6834 buf.append('[');
6835 if (array != null) {
6836 for (int i=0; i<array.length; i++) {
6837 if (i > 0) buf.append(", ");
6838 buf.append(array[i]);
6839 }
6840 }
6841 buf.append(']');
6842 return buf.toString();
6843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 @Override
6846 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6847 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6848 != PackageManager.PERMISSION_GRANTED) {
6849 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6850 + Binder.getCallingPid()
6851 + ", uid=" + Binder.getCallingUid()
6852 + " without permission "
6853 + android.Manifest.permission.DUMP);
6854 return;
6855 }
6856
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006857 String packageName = null;
6858
6859 int opti = 0;
6860 while (opti < args.length) {
6861 String opt = args[opti];
6862 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6863 break;
6864 }
6865 opti++;
6866 if ("-a".equals(opt)) {
6867 // Right now we only know how to print all.
6868 } else if ("-h".equals(opt)) {
6869 pw.println("Package manager dump options:");
6870 pw.println(" [-h] [cmd] ...");
6871 pw.println(" cmd may be one of:");
6872 pw.println(" [package.name]: info about given package");
6873 return;
6874 } else {
6875 pw.println("Unknown argument: " + opt + "; use -h for help");
6876 }
6877 }
6878
6879 // Is the caller requesting to dump a particular piece of data?
6880 if (opti < args.length) {
6881 String cmd = args[opti];
6882 opti++;
6883 // Is this a package name?
6884 if ("android".equals(cmd) || cmd.contains(".")) {
6885 packageName = cmd;
6886 }
6887 }
6888
6889 boolean printedTitle = false;
6890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006892 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6893 printedTitle = true;
6894 }
6895 if (mReceivers.dump(pw, printedTitle
6896 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6897 " ", packageName)) {
6898 printedTitle = true;
6899 }
6900 if (mServices.dump(pw, printedTitle
6901 ? "\nService Resolver Table:" : "Service Resolver Table:",
6902 " ", packageName)) {
6903 printedTitle = true;
6904 }
6905 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6906 ? "\nPreferred Activities:" : "Preferred Activities:",
6907 " ", packageName)) {
6908 printedTitle = true;
6909 }
6910 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006911 {
6912 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006913 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6914 continue;
6915 }
6916 if (!printedSomething) {
6917 if (printedTitle) pw.println(" ");
6918 pw.println("Permissions:");
6919 printedSomething = true;
6920 printedTitle = true;
6921 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006922 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6923 pw.print(Integer.toHexString(System.identityHashCode(p)));
6924 pw.println("):");
6925 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6926 pw.print(" uid="); pw.print(p.uid);
6927 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006928 pw.print(" type="); pw.print(p.type);
6929 pw.print(" prot="); pw.println(p.protectionLevel);
6930 if (p.packageSetting != null) {
6931 pw.print(" packageSetting="); pw.println(p.packageSetting);
6932 }
6933 if (p.perm != null) {
6934 pw.print(" perm="); pw.println(p.perm);
6935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 }
6937 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006938 printedSomething = false;
6939 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 {
6941 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 if (packageName != null && !packageName.equals(ps.realName)
6943 && !packageName.equals(ps.name)) {
6944 continue;
6945 }
6946 if (!printedSomething) {
6947 if (printedTitle) pw.println(" ");
6948 pw.println("Packages:");
6949 printedSomething = true;
6950 printedTitle = true;
6951 }
6952 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006953 pw.print(" Package [");
6954 pw.print(ps.realName != null ? ps.realName : ps.name);
6955 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006956 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6957 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006958 if (ps.realName != null) {
6959 pw.print(" compat name="); pw.println(ps.name);
6960 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006961 pw.print(" userId="); pw.print(ps.userId);
6962 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6963 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6964 pw.print(" pkg="); pw.println(ps.pkg);
6965 pw.print(" codePath="); pw.println(ps.codePathString);
6966 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006968 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006969 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006970 pw.print(" supportsScreens=[");
6971 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006972 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006973 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006974 if (!first) pw.print(", ");
6975 first = false;
6976 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006977 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006978 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006979 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006980 if (!first) pw.print(", ");
6981 first = false;
6982 pw.print("large");
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_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006986 if (!first) pw.print(", ");
6987 first = false;
6988 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006990 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006991 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006992 if (!first) pw.print(", ");
6993 first = false;
6994 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006996 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006997 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6998 if (!first) pw.print(", ");
6999 first = false;
7000 pw.print("anyDensity");
7001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007003 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007004 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7005 pw.print(" signatures="); pw.println(ps.signatures);
7006 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007007 pw.print(" haveGids="); pw.println(ps.haveGids);
7008 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007009 pw.print(" installStatus="); pw.print(ps.installStatus);
7010 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 if (ps.disabledComponents.size() > 0) {
7012 pw.println(" disabledComponents:");
7013 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007014 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
7016 }
7017 if (ps.enabledComponents.size() > 0) {
7018 pw.println(" enabledComponents:");
7019 for (String s : ps.enabledComponents) {
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 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007023 if (ps.grantedPermissions.size() > 0) {
7024 pw.println(" grantedPermissions:");
7025 for (String s : ps.grantedPermissions) {
7026 pw.print(" "); pw.println(s);
7027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007029 }
7030 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007031 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007032 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007033 for (HashMap.Entry<String, String> e
7034 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007035 if (packageName != null && !packageName.equals(e.getKey())
7036 && !packageName.equals(e.getValue())) {
7037 continue;
7038 }
7039 if (!printedSomething) {
7040 if (printedTitle) pw.println(" ");
7041 pw.println("Renamed packages:");
7042 printedSomething = true;
7043 printedTitle = true;
7044 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007045 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7046 pw.println(e.getValue());
7047 }
7048 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007049 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007050 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007051 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007052 if (packageName != null && !packageName.equals(ps.realName)
7053 && !packageName.equals(ps.name)) {
7054 continue;
7055 }
7056 if (!printedSomething) {
7057 if (printedTitle) pw.println(" ");
7058 pw.println("Hidden system packages:");
7059 printedSomething = true;
7060 printedTitle = true;
7061 }
7062 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007063 pw.print(ps.realName != null ? ps.realName : ps.name);
7064 pw.print("] (");
7065 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7066 pw.println("):");
7067 if (ps.realName != null) {
7068 pw.print(" compat name="); pw.println(ps.name);
7069 }
7070 pw.print(" userId="); pw.println(ps.userId);
7071 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7072 pw.print(" codePath="); pw.println(ps.codePathString);
7073 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7074 }
7075 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007076 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007077 {
7078 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007079 if (packageName != null && su != packageSharedUser) {
7080 continue;
7081 }
7082 if (!printedSomething) {
7083 if (printedTitle) pw.println(" ");
7084 pw.println("Shared users:");
7085 printedSomething = true;
7086 printedTitle = true;
7087 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007088 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7089 pw.print(Integer.toHexString(System.identityHashCode(su)));
7090 pw.println("):");
7091 pw.print(" userId="); pw.print(su.userId);
7092 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 pw.println(" grantedPermissions:");
7094 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007095 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 }
7098 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007099
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007100 if (packageName == null) {
7101 if (printedTitle) pw.println(" ");
7102 printedTitle = true;
7103 pw.println("Settings parse messages:");
7104 pw.println(mSettings.mReadMessages.toString());
7105
7106 pw.println(" ");
7107 pw.println("Package warning messages:");
7108 File fname = getSettingsProblemFile();
7109 FileInputStream in;
7110 try {
7111 in = new FileInputStream(fname);
7112 int avail = in.available();
7113 byte[] data = new byte[avail];
7114 in.read(data);
7115 pw.println(new String(data));
7116 } catch (FileNotFoundException e) {
7117 } catch (IOException e) {
7118 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007121
7122 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007123 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007124 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007125 if (packageName != null && !packageName.equals(p.info.packageName)) {
7126 continue;
7127 }
7128 if (!printedSomething) {
7129 if (printedTitle) pw.println(" ");
7130 pw.println("Registered ContentProviders:");
7131 printedSomething = true;
7132 printedTitle = true;
7133 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007134 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007135 pw.println(p.toString());
7136 }
7137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007138 }
7139
7140 static final class BasePermission {
7141 final static int TYPE_NORMAL = 0;
7142 final static int TYPE_BUILTIN = 1;
7143 final static int TYPE_DYNAMIC = 2;
7144
7145 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007146 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007147 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007149 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 PackageParser.Permission perm;
7151 PermissionInfo pendingInfo;
7152 int uid;
7153 int[] gids;
7154
7155 BasePermission(String _name, String _sourcePackage, int _type) {
7156 name = _name;
7157 sourcePackage = _sourcePackage;
7158 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007159 // Default to most conservative protection level.
7160 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7161 }
7162
7163 public String toString() {
7164 return "BasePermission{"
7165 + Integer.toHexString(System.identityHashCode(this))
7166 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 }
7168 }
7169
7170 static class PackageSignatures {
7171 private Signature[] mSignatures;
7172
7173 PackageSignatures(Signature[] sigs) {
7174 assignSignatures(sigs);
7175 }
7176
7177 PackageSignatures() {
7178 }
7179
7180 void writeXml(XmlSerializer serializer, String tagName,
7181 ArrayList<Signature> pastSignatures) throws IOException {
7182 if (mSignatures == null) {
7183 return;
7184 }
7185 serializer.startTag(null, tagName);
7186 serializer.attribute(null, "count",
7187 Integer.toString(mSignatures.length));
7188 for (int i=0; i<mSignatures.length; i++) {
7189 serializer.startTag(null, "cert");
7190 final Signature sig = mSignatures[i];
7191 final int sigHash = sig.hashCode();
7192 final int numPast = pastSignatures.size();
7193 int j;
7194 for (j=0; j<numPast; j++) {
7195 Signature pastSig = pastSignatures.get(j);
7196 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7197 serializer.attribute(null, "index", Integer.toString(j));
7198 break;
7199 }
7200 }
7201 if (j >= numPast) {
7202 pastSignatures.add(sig);
7203 serializer.attribute(null, "index", Integer.toString(numPast));
7204 serializer.attribute(null, "key", sig.toCharsString());
7205 }
7206 serializer.endTag(null, "cert");
7207 }
7208 serializer.endTag(null, tagName);
7209 }
7210
7211 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7212 throws IOException, XmlPullParserException {
7213 String countStr = parser.getAttributeValue(null, "count");
7214 if (countStr == null) {
7215 reportSettingsProblem(Log.WARN,
7216 "Error in package manager settings: <signatures> has"
7217 + " no count at " + parser.getPositionDescription());
7218 XmlUtils.skipCurrentTag(parser);
7219 }
7220 final int count = Integer.parseInt(countStr);
7221 mSignatures = new Signature[count];
7222 int pos = 0;
7223
7224 int outerDepth = parser.getDepth();
7225 int type;
7226 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7227 && (type != XmlPullParser.END_TAG
7228 || parser.getDepth() > outerDepth)) {
7229 if (type == XmlPullParser.END_TAG
7230 || type == XmlPullParser.TEXT) {
7231 continue;
7232 }
7233
7234 String tagName = parser.getName();
7235 if (tagName.equals("cert")) {
7236 if (pos < count) {
7237 String index = parser.getAttributeValue(null, "index");
7238 if (index != null) {
7239 try {
7240 int idx = Integer.parseInt(index);
7241 String key = parser.getAttributeValue(null, "key");
7242 if (key == null) {
7243 if (idx >= 0 && idx < pastSignatures.size()) {
7244 Signature sig = pastSignatures.get(idx);
7245 if (sig != null) {
7246 mSignatures[pos] = pastSignatures.get(idx);
7247 pos++;
7248 } else {
7249 reportSettingsProblem(Log.WARN,
7250 "Error in package manager settings: <cert> "
7251 + "index " + index + " is not defined at "
7252 + parser.getPositionDescription());
7253 }
7254 } else {
7255 reportSettingsProblem(Log.WARN,
7256 "Error in package manager settings: <cert> "
7257 + "index " + index + " is out of bounds at "
7258 + parser.getPositionDescription());
7259 }
7260 } else {
7261 while (pastSignatures.size() <= idx) {
7262 pastSignatures.add(null);
7263 }
7264 Signature sig = new Signature(key);
7265 pastSignatures.set(idx, sig);
7266 mSignatures[pos] = sig;
7267 pos++;
7268 }
7269 } catch (NumberFormatException e) {
7270 reportSettingsProblem(Log.WARN,
7271 "Error in package manager settings: <cert> "
7272 + "index " + index + " is not a number at "
7273 + parser.getPositionDescription());
7274 }
7275 } else {
7276 reportSettingsProblem(Log.WARN,
7277 "Error in package manager settings: <cert> has"
7278 + " no index at " + parser.getPositionDescription());
7279 }
7280 } else {
7281 reportSettingsProblem(Log.WARN,
7282 "Error in package manager settings: too "
7283 + "many <cert> tags, expected " + count
7284 + " at " + parser.getPositionDescription());
7285 }
7286 } else {
7287 reportSettingsProblem(Log.WARN,
7288 "Unknown element under <cert>: "
7289 + parser.getName());
7290 }
7291 XmlUtils.skipCurrentTag(parser);
7292 }
7293
7294 if (pos < count) {
7295 // Should never happen -- there is an error in the written
7296 // settings -- but if it does we don't want to generate
7297 // a bad array.
7298 Signature[] newSigs = new Signature[pos];
7299 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7300 mSignatures = newSigs;
7301 }
7302 }
7303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 private void assignSignatures(Signature[] sigs) {
7305 if (sigs == null) {
7306 mSignatures = null;
7307 return;
7308 }
7309 mSignatures = new Signature[sigs.length];
7310 for (int i=0; i<sigs.length; i++) {
7311 mSignatures[i] = sigs[i];
7312 }
7313 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 @Override
7316 public String toString() {
7317 StringBuffer buf = new StringBuffer(128);
7318 buf.append("PackageSignatures{");
7319 buf.append(Integer.toHexString(System.identityHashCode(this)));
7320 buf.append(" [");
7321 if (mSignatures != null) {
7322 for (int i=0; i<mSignatures.length; i++) {
7323 if (i > 0) buf.append(", ");
7324 buf.append(Integer.toHexString(
7325 System.identityHashCode(mSignatures[i])));
7326 }
7327 }
7328 buf.append("]}");
7329 return buf.toString();
7330 }
7331 }
7332
7333 static class PreferredActivity extends IntentFilter {
7334 final int mMatch;
7335 final String[] mSetPackages;
7336 final String[] mSetClasses;
7337 final String[] mSetComponents;
7338 final ComponentName mActivity;
7339 final String mShortActivity;
7340 String mParseError;
7341
7342 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7343 ComponentName activity) {
7344 super(filter);
7345 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7346 mActivity = activity;
7347 mShortActivity = activity.flattenToShortString();
7348 mParseError = null;
7349 if (set != null) {
7350 final int N = set.length;
7351 String[] myPackages = new String[N];
7352 String[] myClasses = new String[N];
7353 String[] myComponents = new String[N];
7354 for (int i=0; i<N; i++) {
7355 ComponentName cn = set[i];
7356 if (cn == null) {
7357 mSetPackages = null;
7358 mSetClasses = null;
7359 mSetComponents = null;
7360 return;
7361 }
7362 myPackages[i] = cn.getPackageName().intern();
7363 myClasses[i] = cn.getClassName().intern();
7364 myComponents[i] = cn.flattenToShortString().intern();
7365 }
7366 mSetPackages = myPackages;
7367 mSetClasses = myClasses;
7368 mSetComponents = myComponents;
7369 } else {
7370 mSetPackages = null;
7371 mSetClasses = null;
7372 mSetComponents = null;
7373 }
7374 }
7375
7376 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7377 IOException {
7378 mShortActivity = parser.getAttributeValue(null, "name");
7379 mActivity = ComponentName.unflattenFromString(mShortActivity);
7380 if (mActivity == null) {
7381 mParseError = "Bad activity name " + mShortActivity;
7382 }
7383 String matchStr = parser.getAttributeValue(null, "match");
7384 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7385 String setCountStr = parser.getAttributeValue(null, "set");
7386 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7387
7388 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7389 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7390 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7391
7392 int setPos = 0;
7393
7394 int outerDepth = parser.getDepth();
7395 int type;
7396 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7397 && (type != XmlPullParser.END_TAG
7398 || parser.getDepth() > outerDepth)) {
7399 if (type == XmlPullParser.END_TAG
7400 || type == XmlPullParser.TEXT) {
7401 continue;
7402 }
7403
7404 String tagName = parser.getName();
7405 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7406 // + parser.getDepth() + " tag=" + tagName);
7407 if (tagName.equals("set")) {
7408 String name = parser.getAttributeValue(null, "name");
7409 if (name == null) {
7410 if (mParseError == null) {
7411 mParseError = "No name in set tag in preferred activity "
7412 + mShortActivity;
7413 }
7414 } else if (setPos >= setCount) {
7415 if (mParseError == null) {
7416 mParseError = "Too many set tags in preferred activity "
7417 + mShortActivity;
7418 }
7419 } else {
7420 ComponentName cn = ComponentName.unflattenFromString(name);
7421 if (cn == null) {
7422 if (mParseError == null) {
7423 mParseError = "Bad set name " + name + " in preferred activity "
7424 + mShortActivity;
7425 }
7426 } else {
7427 myPackages[setPos] = cn.getPackageName();
7428 myClasses[setPos] = cn.getClassName();
7429 myComponents[setPos] = name;
7430 setPos++;
7431 }
7432 }
7433 XmlUtils.skipCurrentTag(parser);
7434 } else if (tagName.equals("filter")) {
7435 //Log.i(TAG, "Starting to parse filter...");
7436 readFromXml(parser);
7437 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7438 // + parser.getDepth() + " tag=" + parser.getName());
7439 } else {
7440 reportSettingsProblem(Log.WARN,
7441 "Unknown element under <preferred-activities>: "
7442 + parser.getName());
7443 XmlUtils.skipCurrentTag(parser);
7444 }
7445 }
7446
7447 if (setPos != setCount) {
7448 if (mParseError == null) {
7449 mParseError = "Not enough set tags (expected " + setCount
7450 + " but found " + setPos + ") in " + mShortActivity;
7451 }
7452 }
7453
7454 mSetPackages = myPackages;
7455 mSetClasses = myClasses;
7456 mSetComponents = myComponents;
7457 }
7458
7459 public void writeToXml(XmlSerializer serializer) throws IOException {
7460 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7461 serializer.attribute(null, "name", mShortActivity);
7462 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7463 serializer.attribute(null, "set", Integer.toString(NS));
7464 for (int s=0; s<NS; s++) {
7465 serializer.startTag(null, "set");
7466 serializer.attribute(null, "name", mSetComponents[s]);
7467 serializer.endTag(null, "set");
7468 }
7469 serializer.startTag(null, "filter");
7470 super.writeToXml(serializer);
7471 serializer.endTag(null, "filter");
7472 }
7473
7474 boolean sameSet(List<ResolveInfo> query, int priority) {
7475 if (mSetPackages == null) return false;
7476 final int NQ = query.size();
7477 final int NS = mSetPackages.length;
7478 int numMatch = 0;
7479 for (int i=0; i<NQ; i++) {
7480 ResolveInfo ri = query.get(i);
7481 if (ri.priority != priority) continue;
7482 ActivityInfo ai = ri.activityInfo;
7483 boolean good = false;
7484 for (int j=0; j<NS; j++) {
7485 if (mSetPackages[j].equals(ai.packageName)
7486 && mSetClasses[j].equals(ai.name)) {
7487 numMatch++;
7488 good = true;
7489 break;
7490 }
7491 }
7492 if (!good) return false;
7493 }
7494 return numMatch == NS;
7495 }
7496 }
7497
7498 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007499 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007501 HashSet<String> grantedPermissions = new HashSet<String>();
7502 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007505 setFlags(pkgFlags);
7506 }
7507
7508 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007509 this.pkgFlags = pkgFlags & (
7510 ApplicationInfo.FLAG_SYSTEM |
7511 ApplicationInfo.FLAG_FORWARD_LOCK |
7512 ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 }
7514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007516 /**
7517 * Settings base class for pending and resolved classes.
7518 */
7519 static class PackageSettingBase extends GrantedPermissions {
7520 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007521 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007522 File codePath;
7523 String codePathString;
7524 File resourcePath;
7525 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 private long timeStamp;
7527 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007528 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007529
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007530 boolean uidError;
7531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007532 PackageSignatures signatures = new PackageSignatures();
7533
7534 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007535 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 /* Explicitly disabled components */
7538 HashSet<String> disabledComponents = new HashSet<String>(0);
7539 /* Explicitly enabled components */
7540 HashSet<String> enabledComponents = new HashSet<String>(0);
7541 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7542 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007543
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007544 PackageSettingBase origPackage;
7545
Jacek Surazski65e13172009-04-28 15:26:38 +02007546 /* package name of the app that installed this package */
7547 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007549 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007550 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 super(pkgFlags);
7552 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007553 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007554 init(codePath, resourcePath, pVersionCode);
7555 }
7556
7557 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 this.codePath = codePath;
7559 this.codePathString = codePath.toString();
7560 this.resourcePath = resourcePath;
7561 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007562 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007563 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007564
Jacek Surazski65e13172009-04-28 15:26:38 +02007565 public void setInstallerPackageName(String packageName) {
7566 installerPackageName = packageName;
7567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007568
Jacek Surazski65e13172009-04-28 15:26:38 +02007569 String getInstallerPackageName() {
7570 return installerPackageName;
7571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 public void setInstallStatus(int newStatus) {
7574 installStatus = newStatus;
7575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 public int getInstallStatus() {
7578 return installStatus;
7579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 public void setTimeStamp(long newStamp) {
7582 if (newStamp != timeStamp) {
7583 timeStamp = newStamp;
7584 timeStampString = Long.toString(newStamp);
7585 }
7586 }
7587
7588 public void setTimeStamp(long newStamp, String newStampStr) {
7589 timeStamp = newStamp;
7590 timeStampString = newStampStr;
7591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 public long getTimeStamp() {
7594 return timeStamp;
7595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 public String getTimeStampStr() {
7598 return timeStampString;
7599 }
7600
7601 public void copyFrom(PackageSettingBase base) {
7602 grantedPermissions = base.grantedPermissions;
7603 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 timeStamp = base.timeStamp;
7606 timeStampString = base.timeStampString;
7607 signatures = base.signatures;
7608 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007609 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 disabledComponents = base.disabledComponents;
7611 enabledComponents = base.enabledComponents;
7612 enabled = base.enabled;
7613 installStatus = base.installStatus;
7614 }
7615
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007616 boolean enableComponentLP(String componentClassName) {
7617 boolean changed = disabledComponents.remove(componentClassName);
7618 changed |= enabledComponents.add(componentClassName);
7619 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 }
7621
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007622 boolean disableComponentLP(String componentClassName) {
7623 boolean changed = enabledComponents.remove(componentClassName);
7624 changed |= disabledComponents.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 restoreComponentLP(String componentClassName) {
7629 boolean changed = enabledComponents.remove(componentClassName);
7630 changed |= disabledComponents.remove(componentClassName);
7631 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 }
7633
7634 int currentEnabledStateLP(String componentName) {
7635 if (enabledComponents.contains(componentName)) {
7636 return COMPONENT_ENABLED_STATE_ENABLED;
7637 } else if (disabledComponents.contains(componentName)) {
7638 return COMPONENT_ENABLED_STATE_DISABLED;
7639 } else {
7640 return COMPONENT_ENABLED_STATE_DEFAULT;
7641 }
7642 }
7643 }
7644
7645 /**
7646 * Settings data for a particular package we know about.
7647 */
7648 static final class PackageSetting extends PackageSettingBase {
7649 int userId;
7650 PackageParser.Package pkg;
7651 SharedUserSetting sharedUser;
7652
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007653 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007654 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007655 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 @Override
7659 public String toString() {
7660 return "PackageSetting{"
7661 + Integer.toHexString(System.identityHashCode(this))
7662 + " " + name + "/" + userId + "}";
7663 }
7664 }
7665
7666 /**
7667 * Settings data for a particular shared user ID we know about.
7668 */
7669 static final class SharedUserSetting extends GrantedPermissions {
7670 final String name;
7671 int userId;
7672 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7673 final PackageSignatures signatures = new PackageSignatures();
7674
7675 SharedUserSetting(String _name, int _pkgFlags) {
7676 super(_pkgFlags);
7677 name = _name;
7678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 @Override
7681 public String toString() {
7682 return "SharedUserSetting{"
7683 + Integer.toHexString(System.identityHashCode(this))
7684 + " " + name + "/" + userId + "}";
7685 }
7686 }
7687
7688 /**
7689 * Holds information about dynamic settings.
7690 */
7691 private static final class Settings {
7692 private final File mSettingsFilename;
7693 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007694 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 private final HashMap<String, PackageSetting> mPackages =
7696 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007697 // List of replaced system applications
7698 final HashMap<String, PackageSetting> mDisabledSysPackages =
7699 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 // The user's preferred activities associated with particular intent
7702 // filters.
7703 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7704 new IntentResolver<PreferredActivity, PreferredActivity>() {
7705 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007706 protected String packageForFilter(PreferredActivity filter) {
7707 return filter.mActivity.getPackageName();
7708 }
7709 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007710 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007712 out.print(prefix); out.print(
7713 Integer.toHexString(System.identityHashCode(filter)));
7714 out.print(' ');
7715 out.print(filter.mActivity.flattenToShortString());
7716 out.print(" match=0x");
7717 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007719 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007721 out.print(prefix); out.print(" ");
7722 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 }
7724 }
7725 }
7726 };
7727 private final HashMap<String, SharedUserSetting> mSharedUsers =
7728 new HashMap<String, SharedUserSetting>();
7729 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7730 private final SparseArray<Object> mOtherUserIds =
7731 new SparseArray<Object>();
7732
7733 // For reading/writing settings file.
7734 private final ArrayList<Signature> mPastSignatures =
7735 new ArrayList<Signature>();
7736
7737 // Mapping from permission names to info about them.
7738 final HashMap<String, BasePermission> mPermissions =
7739 new HashMap<String, BasePermission>();
7740
7741 // Mapping from permission tree names to info about them.
7742 final HashMap<String, BasePermission> mPermissionTrees =
7743 new HashMap<String, BasePermission>();
7744
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007745 // Packages that have been uninstalled and still need their external
7746 // storage data deleted.
7747 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7748
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007749 // Packages that have been renamed since they were first installed.
7750 // Keys are the new names of the packages, values are the original
7751 // names. The packages appear everwhere else under their original
7752 // names.
7753 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 private final StringBuilder mReadMessages = new StringBuilder();
7756
7757 private static final class PendingPackage extends PackageSettingBase {
7758 final int sharedId;
7759
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007760 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007761 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007762 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 this.sharedId = sharedId;
7764 }
7765 }
7766 private final ArrayList<PendingPackage> mPendingPackages
7767 = new ArrayList<PendingPackage>();
7768
7769 Settings() {
7770 File dataDir = Environment.getDataDirectory();
7771 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007772 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 systemDir.mkdirs();
7774 FileUtils.setPermissions(systemDir.toString(),
7775 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7776 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7777 -1, -1);
7778 mSettingsFilename = new File(systemDir, "packages.xml");
7779 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007780 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 }
7782
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007783 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007784 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 int pkgFlags, boolean create, boolean add) {
7786 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007787 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007788 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 return p;
7790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007791
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007792 PackageSetting peekPackageLP(String name) {
7793 return mPackages.get(name);
7794 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 PackageSetting p = mPackages.get(name);
7796 if (p != null && p.codePath.getPath().equals(codePath)) {
7797 return p;
7798 }
7799 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007800 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 void setInstallStatus(String pkgName, int status) {
7804 PackageSetting p = mPackages.get(pkgName);
7805 if(p != null) {
7806 if(p.getInstallStatus() != status) {
7807 p.setInstallStatus(status);
7808 }
7809 }
7810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007811
Jacek Surazski65e13172009-04-28 15:26:38 +02007812 void setInstallerPackageName(String pkgName,
7813 String installerPkgName) {
7814 PackageSetting p = mPackages.get(pkgName);
7815 if(p != null) {
7816 p.setInstallerPackageName(installerPkgName);
7817 }
7818 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007819
Jacek Surazski65e13172009-04-28 15:26:38 +02007820 String getInstallerPackageName(String pkgName) {
7821 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007822 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007823 }
7824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 int getInstallStatus(String pkgName) {
7826 PackageSetting p = mPackages.get(pkgName);
7827 if(p != null) {
7828 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 return -1;
7831 }
7832
7833 SharedUserSetting getSharedUserLP(String name,
7834 int pkgFlags, boolean create) {
7835 SharedUserSetting s = mSharedUsers.get(name);
7836 if (s == null) {
7837 if (!create) {
7838 return null;
7839 }
7840 s = new SharedUserSetting(name, pkgFlags);
7841 if (MULTIPLE_APPLICATION_UIDS) {
7842 s.userId = newUserIdLP(s);
7843 } else {
7844 s.userId = FIRST_APPLICATION_UID;
7845 }
7846 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7847 // < 0 means we couldn't assign a userid; fall out and return
7848 // s, which is currently null
7849 if (s.userId >= 0) {
7850 mSharedUsers.put(name, s);
7851 }
7852 }
7853
7854 return s;
7855 }
7856
7857 int disableSystemPackageLP(String name) {
7858 PackageSetting p = mPackages.get(name);
7859 if(p == null) {
7860 Log.w(TAG, "Package:"+name+" is not an installed package");
7861 return -1;
7862 }
7863 PackageSetting dp = mDisabledSysPackages.get(name);
7864 // always make sure the system package code and resource paths dont change
7865 if(dp == null) {
7866 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7867 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7868 }
7869 mDisabledSysPackages.put(name, p);
7870 }
7871 return removePackageLP(name);
7872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 PackageSetting enableSystemPackageLP(String name) {
7875 PackageSetting p = mDisabledSysPackages.get(name);
7876 if(p == null) {
7877 Log.w(TAG, "Package:"+name+" is not disabled");
7878 return null;
7879 }
7880 // Reset flag in ApplicationInfo object
7881 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7882 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7883 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007884 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007885 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 mDisabledSysPackages.remove(name);
7887 return ret;
7888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007889
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007890 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007891 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 PackageSetting p = mPackages.get(name);
7893 if (p != null) {
7894 if (p.userId == uid) {
7895 return p;
7896 }
7897 reportSettingsProblem(Log.ERROR,
7898 "Adding duplicate package, keeping first: " + name);
7899 return null;
7900 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007901 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 p.userId = uid;
7903 if (addUserIdLP(uid, p, name)) {
7904 mPackages.put(name, p);
7905 return p;
7906 }
7907 return null;
7908 }
7909
7910 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7911 SharedUserSetting s = mSharedUsers.get(name);
7912 if (s != null) {
7913 if (s.userId == uid) {
7914 return s;
7915 }
7916 reportSettingsProblem(Log.ERROR,
7917 "Adding duplicate shared user, keeping first: " + name);
7918 return null;
7919 }
7920 s = new SharedUserSetting(name, pkgFlags);
7921 s.userId = uid;
7922 if (addUserIdLP(uid, s, name)) {
7923 mSharedUsers.put(name, s);
7924 return s;
7925 }
7926 return null;
7927 }
7928
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007929 // Transfer ownership of permissions from one package to another.
7930 private void transferPermissions(String origPkg, String newPkg) {
7931 // Transfer ownership of permissions to the new package.
7932 for (int i=0; i<2; i++) {
7933 HashMap<String, BasePermission> permissions =
7934 i == 0 ? mPermissionTrees : mPermissions;
7935 for (BasePermission bp : permissions.values()) {
7936 if (origPkg.equals(bp.sourcePackage)) {
7937 if (DEBUG_UPGRADE) Log.v(TAG,
7938 "Moving permission " + bp.name
7939 + " from pkg " + bp.sourcePackage
7940 + " to " + newPkg);
7941 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007942 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007943 bp.perm = null;
7944 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007945 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007946 }
7947 bp.uid = 0;
7948 bp.gids = null;
7949 }
7950 }
7951 }
7952 }
7953
7954 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007955 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007956 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 PackageSetting p = mPackages.get(name);
7958 if (p != null) {
7959 if (!p.codePath.equals(codePath)) {
7960 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007961 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007962 // This is an updated system app with versions in both system
7963 // and data partition. Just let the most recent version
7964 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007965 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007966 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007967 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007968 // Just a change in the code path is not an issue, but
7969 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007970 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007971 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007973 }
7974 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 reportSettingsProblem(Log.WARN,
7976 "Package " + name + " shared user changed from "
7977 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7978 + " to "
7979 + (sharedUser != null ? sharedUser.name : "<nothing>")
7980 + "; replacing with new");
7981 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007982 } else {
7983 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7984 // If what we are scanning is a system package, then
7985 // make it so, regardless of whether it was previously
7986 // installed only in the data partition.
7987 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 }
7990 }
7991 if (p == null) {
7992 // Create a new PackageSettings entry. this can end up here because
7993 // of code path mismatch or user id mismatch of an updated system partition
7994 if (!create) {
7995 return null;
7996 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007997 if (origPackage != null) {
7998 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007999 p = new PackageSetting(origPackage.name, name, codePath,
8000 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008001 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8002 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008003 // Note that we will retain the new package's signature so
8004 // that we can keep its data.
8005 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008006 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008007 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008008 p.sharedUser = origPackage.sharedUser;
8009 p.userId = origPackage.userId;
8010 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008011 mRenamedPackages.put(name, origPackage.name);
8012 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008013 // Update new package state.
8014 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008016 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008017 p.setTimeStamp(codePath.lastModified());
8018 p.sharedUser = sharedUser;
8019 if (sharedUser != null) {
8020 p.userId = sharedUser.userId;
8021 } else if (MULTIPLE_APPLICATION_UIDS) {
8022 // Clone the setting here for disabled system packages
8023 PackageSetting dis = mDisabledSysPackages.get(name);
8024 if (dis != null) {
8025 // For disabled packages a new setting is created
8026 // from the existing user id. This still has to be
8027 // added to list of user id's
8028 // Copy signatures from previous setting
8029 if (dis.signatures.mSignatures != null) {
8030 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8031 }
8032 p.userId = dis.userId;
8033 // Clone permissions
8034 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008035 // Clone component info
8036 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8037 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8038 // Add new setting to list of user ids
8039 addUserIdLP(p.userId, p, name);
8040 } else {
8041 // Assign new user id
8042 p.userId = newUserIdLP(p);
8043 }
8044 } else {
8045 p.userId = FIRST_APPLICATION_UID;
8046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008047 }
8048 if (p.userId < 0) {
8049 reportSettingsProblem(Log.WARN,
8050 "Package " + name + " could not be assigned a valid uid");
8051 return null;
8052 }
8053 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008054 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008056 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 }
8058 }
8059 return p;
8060 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008061
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008062 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008063 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008064 String codePath = pkg.applicationInfo.sourceDir;
8065 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008066 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008067 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008068 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008069 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008070 p.codePath = new File(codePath);
8071 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008072 }
8073 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008074 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008075 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008076 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008077 p.resourcePath = new File(resourcePath);
8078 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008079 }
8080 // Update version code if needed
8081 if (pkg.mVersionCode != p.versionCode) {
8082 p.versionCode = pkg.mVersionCode;
8083 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008084 // Update signatures if needed.
8085 if (p.signatures.mSignatures == null) {
8086 p.signatures.assignSignatures(pkg.mSignatures);
8087 }
8088 // If this app defines a shared user id initialize
8089 // the shared user signatures as well.
8090 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8091 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8092 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008093 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8094 }
8095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 // Utility method that adds a PackageSetting to mPackages and
8097 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008098 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 SharedUserSetting sharedUser) {
8100 mPackages.put(name, p);
8101 if (sharedUser != null) {
8102 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8103 reportSettingsProblem(Log.ERROR,
8104 "Package " + p.name + " was user "
8105 + p.sharedUser + " but is now " + sharedUser
8106 + "; I am not changing its files so it will probably fail!");
8107 p.sharedUser.packages.remove(p);
8108 } else if (p.userId != sharedUser.userId) {
8109 reportSettingsProblem(Log.ERROR,
8110 "Package " + p.name + " was user id " + p.userId
8111 + " but is now user " + sharedUser
8112 + " with id " + sharedUser.userId
8113 + "; I am not changing its files so it will probably fail!");
8114 }
8115
8116 sharedUser.packages.add(p);
8117 p.sharedUser = sharedUser;
8118 p.userId = sharedUser.userId;
8119 }
8120 }
8121
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008122 /*
8123 * Update the shared user setting when a package using
8124 * specifying the shared user id is removed. The gids
8125 * associated with each permission of the deleted package
8126 * are removed from the shared user's gid list only if its
8127 * not in use by other permissions of packages in the
8128 * shared user setting.
8129 */
8130 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008132 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 return;
8134 }
8135 // No sharedUserId
8136 if (deletedPs.sharedUser == null) {
8137 return;
8138 }
8139 SharedUserSetting sus = deletedPs.sharedUser;
8140 // Update permissions
8141 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8142 boolean used = false;
8143 if (!sus.grantedPermissions.contains (eachPerm)) {
8144 continue;
8145 }
8146 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008147 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008148 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008149 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 used = true;
8151 break;
8152 }
8153 }
8154 if (!used) {
8155 // can safely delete this permission from list
8156 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 }
8158 }
8159 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008160 int newGids[] = globalGids;
8161 for (String eachPerm : sus.grantedPermissions) {
8162 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008163 if (bp != null) {
8164 newGids = appendInts(newGids, bp.gids);
8165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 }
8167 sus.gids = newGids;
8168 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 private int removePackageLP(String name) {
8171 PackageSetting p = mPackages.get(name);
8172 if (p != null) {
8173 mPackages.remove(name);
8174 if (p.sharedUser != null) {
8175 p.sharedUser.packages.remove(p);
8176 if (p.sharedUser.packages.size() == 0) {
8177 mSharedUsers.remove(p.sharedUser.name);
8178 removeUserIdLP(p.sharedUser.userId);
8179 return p.sharedUser.userId;
8180 }
8181 } else {
8182 removeUserIdLP(p.userId);
8183 return p.userId;
8184 }
8185 }
8186 return -1;
8187 }
8188
8189 private boolean addUserIdLP(int uid, Object obj, Object name) {
8190 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8191 return false;
8192 }
8193
8194 if (uid >= FIRST_APPLICATION_UID) {
8195 int N = mUserIds.size();
8196 final int index = uid - FIRST_APPLICATION_UID;
8197 while (index >= N) {
8198 mUserIds.add(null);
8199 N++;
8200 }
8201 if (mUserIds.get(index) != null) {
8202 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008203 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 + " name=" + name);
8205 return false;
8206 }
8207 mUserIds.set(index, obj);
8208 } else {
8209 if (mOtherUserIds.get(uid) != null) {
8210 reportSettingsProblem(Log.ERROR,
8211 "Adding duplicate shared id: " + uid
8212 + " name=" + name);
8213 return false;
8214 }
8215 mOtherUserIds.put(uid, obj);
8216 }
8217 return true;
8218 }
8219
8220 public Object getUserIdLP(int uid) {
8221 if (uid >= FIRST_APPLICATION_UID) {
8222 int N = mUserIds.size();
8223 final int index = uid - FIRST_APPLICATION_UID;
8224 return index < N ? mUserIds.get(index) : null;
8225 } else {
8226 return mOtherUserIds.get(uid);
8227 }
8228 }
8229
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008230 private Set<String> findPackagesWithFlag(int flag) {
8231 Set<String> ret = new HashSet<String>();
8232 for (PackageSetting ps : mPackages.values()) {
8233 // Has to match atleast all the flag bits set on flag
8234 if ((ps.pkgFlags & flag) == flag) {
8235 ret.add(ps.name);
8236 }
8237 }
8238 return ret;
8239 }
8240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008241 private void removeUserIdLP(int uid) {
8242 if (uid >= FIRST_APPLICATION_UID) {
8243 int N = mUserIds.size();
8244 final int index = uid - FIRST_APPLICATION_UID;
8245 if (index < N) mUserIds.set(index, null);
8246 } else {
8247 mOtherUserIds.remove(uid);
8248 }
8249 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 void writeLP() {
8252 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8253
8254 // Keep the old settings around until we know the new ones have
8255 // been successfully written.
8256 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008257 // Presence of backup settings file indicates that we failed
8258 // to persist settings earlier. So preserve the older
8259 // backup for future reference since the current settings
8260 // might have been corrupted.
8261 if (!mBackupSettingsFilename.exists()) {
8262 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008263 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008264 return;
8265 }
8266 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008267 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008268 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 }
8271
8272 mPastSignatures.clear();
8273
8274 try {
8275 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8276
8277 //XmlSerializer serializer = XmlUtils.serializerInstance();
8278 XmlSerializer serializer = new FastXmlSerializer();
8279 serializer.setOutput(str, "utf-8");
8280 serializer.startDocument(null, true);
8281 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8282
8283 serializer.startTag(null, "packages");
8284
8285 serializer.startTag(null, "permission-trees");
8286 for (BasePermission bp : mPermissionTrees.values()) {
8287 writePermission(serializer, bp);
8288 }
8289 serializer.endTag(null, "permission-trees");
8290
8291 serializer.startTag(null, "permissions");
8292 for (BasePermission bp : mPermissions.values()) {
8293 writePermission(serializer, bp);
8294 }
8295 serializer.endTag(null, "permissions");
8296
8297 for (PackageSetting pkg : mPackages.values()) {
8298 writePackage(serializer, pkg);
8299 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8302 writeDisabledSysPackage(serializer, pkg);
8303 }
8304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 serializer.startTag(null, "preferred-activities");
8306 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8307 serializer.startTag(null, "item");
8308 pa.writeToXml(serializer);
8309 serializer.endTag(null, "item");
8310 }
8311 serializer.endTag(null, "preferred-activities");
8312
8313 for (SharedUserSetting usr : mSharedUsers.values()) {
8314 serializer.startTag(null, "shared-user");
8315 serializer.attribute(null, "name", usr.name);
8316 serializer.attribute(null, "userId",
8317 Integer.toString(usr.userId));
8318 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8319 serializer.startTag(null, "perms");
8320 for (String name : usr.grantedPermissions) {
8321 serializer.startTag(null, "item");
8322 serializer.attribute(null, "name", name);
8323 serializer.endTag(null, "item");
8324 }
8325 serializer.endTag(null, "perms");
8326 serializer.endTag(null, "shared-user");
8327 }
8328
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008329 if (mPackagesToBeCleaned.size() > 0) {
8330 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8331 serializer.startTag(null, "cleaning-package");
8332 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8333 serializer.endTag(null, "cleaning-package");
8334 }
8335 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008336
8337 if (mRenamedPackages.size() > 0) {
8338 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8339 serializer.startTag(null, "renamed-package");
8340 serializer.attribute(null, "new", e.getKey());
8341 serializer.attribute(null, "old", e.getValue());
8342 serializer.endTag(null, "renamed-package");
8343 }
8344 }
8345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 serializer.endTag(null, "packages");
8347
8348 serializer.endDocument();
8349
8350 str.flush();
8351 str.close();
8352
8353 // New settings successfully written, old ones are no longer
8354 // needed.
8355 mBackupSettingsFilename.delete();
8356 FileUtils.setPermissions(mSettingsFilename.toString(),
8357 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8358 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8359 |FileUtils.S_IROTH,
8360 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008361
8362 // Write package list file now, use a JournaledFile.
8363 //
8364 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8365 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8366
8367 str = new FileOutputStream(journal.chooseForWrite());
8368 try {
8369 StringBuilder sb = new StringBuilder();
8370 for (PackageSetting pkg : mPackages.values()) {
8371 ApplicationInfo ai = pkg.pkg.applicationInfo;
8372 String dataPath = ai.dataDir;
8373 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8374
8375 // Avoid any application that has a space in its path
8376 // or that is handled by the system.
8377 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8378 continue;
8379
8380 // we store on each line the following information for now:
8381 //
8382 // pkgName - package name
8383 // userId - application-specific user id
8384 // debugFlag - 0 or 1 if the package is debuggable.
8385 // dataPath - path to package's data path
8386 //
8387 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8388 //
8389 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8390 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8391 // system/core/run-as/run-as.c
8392 //
8393 sb.setLength(0);
8394 sb.append(ai.packageName);
8395 sb.append(" ");
8396 sb.append((int)ai.uid);
8397 sb.append(isDebug ? " 1 " : " 0 ");
8398 sb.append(dataPath);
8399 sb.append("\n");
8400 str.write(sb.toString().getBytes());
8401 }
8402 str.flush();
8403 str.close();
8404 journal.commit();
8405 }
8406 catch (Exception e) {
8407 journal.rollback();
8408 }
8409
8410 FileUtils.setPermissions(mPackageListFilename.toString(),
8411 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8412 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8413 |FileUtils.S_IROTH,
8414 -1, -1);
8415
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008416 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417
8418 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008419 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 -08008420 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008421 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 -08008422 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008423 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008424 if (mSettingsFilename.exists()) {
8425 if (!mSettingsFilename.delete()) {
8426 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8427 }
8428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 //Debug.stopMethodTracing();
8430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008431
8432 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008433 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008434 serializer.startTag(null, "updated-package");
8435 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008436 if (pkg.realName != null) {
8437 serializer.attribute(null, "realName", pkg.realName);
8438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008439 serializer.attribute(null, "codePath", pkg.codePathString);
8440 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008441 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8443 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8444 }
8445 if (pkg.sharedUser == null) {
8446 serializer.attribute(null, "userId",
8447 Integer.toString(pkg.userId));
8448 } else {
8449 serializer.attribute(null, "sharedUserId",
8450 Integer.toString(pkg.userId));
8451 }
8452 serializer.startTag(null, "perms");
8453 if (pkg.sharedUser == null) {
8454 // If this is a shared user, the permissions will
8455 // be written there. We still need to write an
8456 // empty permissions list so permissionsFixed will
8457 // be set.
8458 for (final String name : pkg.grantedPermissions) {
8459 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008460 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008461 // We only need to write signature or system permissions but this wont
8462 // match the semantics of grantedPermissions. So write all permissions.
8463 serializer.startTag(null, "item");
8464 serializer.attribute(null, "name", name);
8465 serializer.endTag(null, "item");
8466 }
8467 }
8468 }
8469 serializer.endTag(null, "perms");
8470 serializer.endTag(null, "updated-package");
8471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008472
8473 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008474 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 serializer.startTag(null, "package");
8476 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008477 if (pkg.realName != null) {
8478 serializer.attribute(null, "realName", pkg.realName);
8479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 serializer.attribute(null, "codePath", pkg.codePathString);
8481 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8482 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8483 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008484 serializer.attribute(null, "flags",
8485 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008487 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 if (pkg.sharedUser == null) {
8489 serializer.attribute(null, "userId",
8490 Integer.toString(pkg.userId));
8491 } else {
8492 serializer.attribute(null, "sharedUserId",
8493 Integer.toString(pkg.userId));
8494 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008495 if (pkg.uidError) {
8496 serializer.attribute(null, "uidError", "true");
8497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8499 serializer.attribute(null, "enabled",
8500 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8501 ? "true" : "false");
8502 }
8503 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8504 serializer.attribute(null, "installStatus", "false");
8505 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008506 if (pkg.installerPackageName != null) {
8507 serializer.attribute(null, "installer", pkg.installerPackageName);
8508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8510 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8511 serializer.startTag(null, "perms");
8512 if (pkg.sharedUser == null) {
8513 // If this is a shared user, the permissions will
8514 // be written there. We still need to write an
8515 // empty permissions list so permissionsFixed will
8516 // be set.
8517 for (final String name : pkg.grantedPermissions) {
8518 serializer.startTag(null, "item");
8519 serializer.attribute(null, "name", name);
8520 serializer.endTag(null, "item");
8521 }
8522 }
8523 serializer.endTag(null, "perms");
8524 }
8525 if (pkg.disabledComponents.size() > 0) {
8526 serializer.startTag(null, "disabled-components");
8527 for (final String name : pkg.disabledComponents) {
8528 serializer.startTag(null, "item");
8529 serializer.attribute(null, "name", name);
8530 serializer.endTag(null, "item");
8531 }
8532 serializer.endTag(null, "disabled-components");
8533 }
8534 if (pkg.enabledComponents.size() > 0) {
8535 serializer.startTag(null, "enabled-components");
8536 for (final String name : pkg.enabledComponents) {
8537 serializer.startTag(null, "item");
8538 serializer.attribute(null, "name", name);
8539 serializer.endTag(null, "item");
8540 }
8541 serializer.endTag(null, "enabled-components");
8542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008544 serializer.endTag(null, "package");
8545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 void writePermission(XmlSerializer serializer, BasePermission bp)
8548 throws XmlPullParserException, java.io.IOException {
8549 if (bp.type != BasePermission.TYPE_BUILTIN
8550 && bp.sourcePackage != null) {
8551 serializer.startTag(null, "item");
8552 serializer.attribute(null, "name", bp.name);
8553 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008554 if (bp.protectionLevel !=
8555 PermissionInfo.PROTECTION_NORMAL) {
8556 serializer.attribute(null, "protection",
8557 Integer.toString(bp.protectionLevel));
8558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 if (DEBUG_SETTINGS) Log.v(TAG,
8560 "Writing perm: name=" + bp.name + " type=" + bp.type);
8561 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8562 PermissionInfo pi = bp.perm != null ? bp.perm.info
8563 : bp.pendingInfo;
8564 if (pi != null) {
8565 serializer.attribute(null, "type", "dynamic");
8566 if (pi.icon != 0) {
8567 serializer.attribute(null, "icon",
8568 Integer.toString(pi.icon));
8569 }
8570 if (pi.nonLocalizedLabel != null) {
8571 serializer.attribute(null, "label",
8572 pi.nonLocalizedLabel.toString());
8573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 }
8575 }
8576 serializer.endTag(null, "item");
8577 }
8578 }
8579
8580 String getReadMessagesLP() {
8581 return mReadMessages.toString();
8582 }
8583
Oscar Montemayora8529f62009-11-18 10:14:20 -08008584 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8586 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008587 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 while(its.hasNext()) {
8589 String key = its.next();
8590 PackageSetting ps = mPackages.get(key);
8591 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008592 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 }
8594 }
8595 return ret;
8596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 boolean readLP() {
8599 FileInputStream str = null;
8600 if (mBackupSettingsFilename.exists()) {
8601 try {
8602 str = new FileInputStream(mBackupSettingsFilename);
8603 mReadMessages.append("Reading from backup settings file\n");
8604 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008605 if (mSettingsFilename.exists()) {
8606 // If both the backup and settings file exist, we
8607 // ignore the settings since it might have been
8608 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008609 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008610 mSettingsFilename.delete();
8611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 } catch (java.io.IOException e) {
8613 // We'll try for the normal settings file.
8614 }
8615 }
8616
8617 mPastSignatures.clear();
8618
8619 try {
8620 if (str == null) {
8621 if (!mSettingsFilename.exists()) {
8622 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008623 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 return false;
8625 }
8626 str = new FileInputStream(mSettingsFilename);
8627 }
8628 XmlPullParser parser = Xml.newPullParser();
8629 parser.setInput(str, null);
8630
8631 int type;
8632 while ((type=parser.next()) != XmlPullParser.START_TAG
8633 && type != XmlPullParser.END_DOCUMENT) {
8634 ;
8635 }
8636
8637 if (type != XmlPullParser.START_TAG) {
8638 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008639 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 return false;
8641 }
8642
8643 int outerDepth = parser.getDepth();
8644 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8645 && (type != XmlPullParser.END_TAG
8646 || parser.getDepth() > outerDepth)) {
8647 if (type == XmlPullParser.END_TAG
8648 || type == XmlPullParser.TEXT) {
8649 continue;
8650 }
8651
8652 String tagName = parser.getName();
8653 if (tagName.equals("package")) {
8654 readPackageLP(parser);
8655 } else if (tagName.equals("permissions")) {
8656 readPermissionsLP(mPermissions, parser);
8657 } else if (tagName.equals("permission-trees")) {
8658 readPermissionsLP(mPermissionTrees, parser);
8659 } else if (tagName.equals("shared-user")) {
8660 readSharedUserLP(parser);
8661 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008662 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 } else if (tagName.equals("preferred-activities")) {
8664 readPreferredActivitiesLP(parser);
8665 } else if(tagName.equals("updated-package")) {
8666 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008667 } else if (tagName.equals("cleaning-package")) {
8668 String name = parser.getAttributeValue(null, "name");
8669 if (name != null) {
8670 mPackagesToBeCleaned.add(name);
8671 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008672 } else if (tagName.equals("renamed-package")) {
8673 String nname = parser.getAttributeValue(null, "new");
8674 String oname = parser.getAttributeValue(null, "old");
8675 if (nname != null && oname != null) {
8676 mRenamedPackages.put(nname, oname);
8677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008679 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 + parser.getName());
8681 XmlUtils.skipCurrentTag(parser);
8682 }
8683 }
8684
8685 str.close();
8686
8687 } catch(XmlPullParserException e) {
8688 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008689 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690
8691 } catch(java.io.IOException e) {
8692 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008693 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694
8695 }
8696
8697 int N = mPendingPackages.size();
8698 for (int i=0; i<N; i++) {
8699 final PendingPackage pp = mPendingPackages.get(i);
8700 Object idObj = getUserIdLP(pp.sharedId);
8701 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008702 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008703 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008704 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008706 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 + pp.name);
8708 continue;
8709 }
8710 p.copyFrom(pp);
8711 } else if (idObj != null) {
8712 String msg = "Bad package setting: package " + pp.name
8713 + " has shared uid " + pp.sharedId
8714 + " that is not a shared uid\n";
8715 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008716 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717 } else {
8718 String msg = "Bad package setting: package " + pp.name
8719 + " has shared uid " + pp.sharedId
8720 + " that is not defined\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 }
8724 }
8725 mPendingPackages.clear();
8726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008727 mReadMessages.append("Read completed successfully: "
8728 + mPackages.size() + " packages, "
8729 + mSharedUsers.size() + " shared uids\n");
8730
8731 return true;
8732 }
8733
8734 private int readInt(XmlPullParser parser, String ns, String name,
8735 int defValue) {
8736 String v = parser.getAttributeValue(ns, name);
8737 try {
8738 if (v == null) {
8739 return defValue;
8740 }
8741 return Integer.parseInt(v);
8742 } catch (NumberFormatException e) {
8743 reportSettingsProblem(Log.WARN,
8744 "Error in package manager settings: attribute " +
8745 name + " has bad integer value " + v + " at "
8746 + parser.getPositionDescription());
8747 }
8748 return defValue;
8749 }
8750
8751 private void readPermissionsLP(HashMap<String, BasePermission> out,
8752 XmlPullParser parser)
8753 throws IOException, XmlPullParserException {
8754 int outerDepth = parser.getDepth();
8755 int type;
8756 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8757 && (type != XmlPullParser.END_TAG
8758 || parser.getDepth() > outerDepth)) {
8759 if (type == XmlPullParser.END_TAG
8760 || type == XmlPullParser.TEXT) {
8761 continue;
8762 }
8763
8764 String tagName = parser.getName();
8765 if (tagName.equals("item")) {
8766 String name = parser.getAttributeValue(null, "name");
8767 String sourcePackage = parser.getAttributeValue(null, "package");
8768 String ptype = parser.getAttributeValue(null, "type");
8769 if (name != null && sourcePackage != null) {
8770 boolean dynamic = "dynamic".equals(ptype);
8771 BasePermission bp = new BasePermission(name, sourcePackage,
8772 dynamic
8773 ? BasePermission.TYPE_DYNAMIC
8774 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008775 bp.protectionLevel = readInt(parser, null, "protection",
8776 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 if (dynamic) {
8778 PermissionInfo pi = new PermissionInfo();
8779 pi.packageName = sourcePackage.intern();
8780 pi.name = name.intern();
8781 pi.icon = readInt(parser, null, "icon", 0);
8782 pi.nonLocalizedLabel = parser.getAttributeValue(
8783 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008784 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 bp.pendingInfo = pi;
8786 }
8787 out.put(bp.name, bp);
8788 } else {
8789 reportSettingsProblem(Log.WARN,
8790 "Error in package manager settings: permissions has"
8791 + " no name at " + parser.getPositionDescription());
8792 }
8793 } else {
8794 reportSettingsProblem(Log.WARN,
8795 "Unknown element reading permissions: "
8796 + parser.getName() + " at "
8797 + parser.getPositionDescription());
8798 }
8799 XmlUtils.skipCurrentTag(parser);
8800 }
8801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008804 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008806 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 String codePathStr = parser.getAttributeValue(null, "codePath");
8808 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008809 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008810 resourcePathStr = codePathStr;
8811 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008812 String version = parser.getAttributeValue(null, "version");
8813 int versionCode = 0;
8814 if (version != null) {
8815 try {
8816 versionCode = Integer.parseInt(version);
8817 } catch (NumberFormatException e) {
8818 }
8819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008821 int pkgFlags = 0;
8822 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008823 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008824 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008825 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826 String timeStampStr = parser.getAttributeValue(null, "ts");
8827 if (timeStampStr != null) {
8828 try {
8829 long timeStamp = Long.parseLong(timeStampStr);
8830 ps.setTimeStamp(timeStamp, timeStampStr);
8831 } catch (NumberFormatException e) {
8832 }
8833 }
8834 String idStr = parser.getAttributeValue(null, "userId");
8835 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8836 if(ps.userId <= 0) {
8837 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8838 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8839 }
8840 int outerDepth = parser.getDepth();
8841 int type;
8842 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8843 && (type != XmlPullParser.END_TAG
8844 || parser.getDepth() > outerDepth)) {
8845 if (type == XmlPullParser.END_TAG
8846 || type == XmlPullParser.TEXT) {
8847 continue;
8848 }
8849
8850 String tagName = parser.getName();
8851 if (tagName.equals("perms")) {
8852 readGrantedPermissionsLP(parser,
8853 ps.grantedPermissions);
8854 } else {
8855 reportSettingsProblem(Log.WARN,
8856 "Unknown element under <updated-package>: "
8857 + parser.getName());
8858 XmlUtils.skipCurrentTag(parser);
8859 }
8860 }
8861 mDisabledSysPackages.put(name, ps);
8862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 private void readPackageLP(XmlPullParser parser)
8865 throws XmlPullParserException, IOException {
8866 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008867 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 String idStr = null;
8869 String sharedIdStr = null;
8870 String codePathStr = null;
8871 String resourcePathStr = null;
8872 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008873 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008874 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 int pkgFlags = 0;
8876 String timeStampStr;
8877 long timeStamp = 0;
8878 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008879 String version = null;
8880 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 try {
8882 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008883 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008885 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8887 codePathStr = parser.getAttributeValue(null, "codePath");
8888 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008889 version = parser.getAttributeValue(null, "version");
8890 if (version != null) {
8891 try {
8892 versionCode = Integer.parseInt(version);
8893 } catch (NumberFormatException e) {
8894 }
8895 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008896 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008897
8898 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008900 try {
8901 pkgFlags = Integer.parseInt(systemStr);
8902 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 }
8904 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008905 // For backward compatibility
8906 systemStr = parser.getAttributeValue(null, "system");
8907 if (systemStr != null) {
8908 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8909 } else {
8910 // Old settings that don't specify system... just treat
8911 // them as system, good enough.
8912 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 }
8915 timeStampStr = parser.getAttributeValue(null, "ts");
8916 if (timeStampStr != null) {
8917 try {
8918 timeStamp = Long.parseLong(timeStampStr);
8919 } catch (NumberFormatException e) {
8920 }
8921 }
8922 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8923 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8924 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8925 if (resourcePathStr == null) {
8926 resourcePathStr = codePathStr;
8927 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008928 if (realName != null) {
8929 realName = realName.intern();
8930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 if (name == null) {
8932 reportSettingsProblem(Log.WARN,
8933 "Error in package manager settings: <package> has no name at "
8934 + parser.getPositionDescription());
8935 } else if (codePathStr == null) {
8936 reportSettingsProblem(Log.WARN,
8937 "Error in package manager settings: <package> has no codePath at "
8938 + parser.getPositionDescription());
8939 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008940 packageSetting = addPackageLP(name.intern(), realName,
8941 new File(codePathStr), new File(resourcePathStr),
8942 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8944 + ": userId=" + userId + " pkg=" + packageSetting);
8945 if (packageSetting == null) {
8946 reportSettingsProblem(Log.ERROR,
8947 "Failure adding uid " + userId
8948 + " while parsing settings at "
8949 + parser.getPositionDescription());
8950 } else {
8951 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8952 }
8953 } else if (sharedIdStr != null) {
8954 userId = sharedIdStr != null
8955 ? Integer.parseInt(sharedIdStr) : 0;
8956 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008957 packageSetting = new PendingPackage(name.intern(), realName,
8958 new File(codePathStr), new File(resourcePathStr),
8959 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8961 mPendingPackages.add((PendingPackage) packageSetting);
8962 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8963 + ": sharedUserId=" + userId + " pkg="
8964 + packageSetting);
8965 } else {
8966 reportSettingsProblem(Log.WARN,
8967 "Error in package manager settings: package "
8968 + name + " has bad sharedId " + sharedIdStr
8969 + " at " + parser.getPositionDescription());
8970 }
8971 } else {
8972 reportSettingsProblem(Log.WARN,
8973 "Error in package manager settings: package "
8974 + name + " has bad userId " + idStr + " at "
8975 + parser.getPositionDescription());
8976 }
8977 } catch (NumberFormatException e) {
8978 reportSettingsProblem(Log.WARN,
8979 "Error in package manager settings: package "
8980 + name + " has bad userId " + idStr + " at "
8981 + parser.getPositionDescription());
8982 }
8983 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008984 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008985 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008986 final String enabledStr = parser.getAttributeValue(null, "enabled");
8987 if (enabledStr != null) {
8988 if (enabledStr.equalsIgnoreCase("true")) {
8989 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8990 } else if (enabledStr.equalsIgnoreCase("false")) {
8991 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8992 } else if (enabledStr.equalsIgnoreCase("default")) {
8993 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8994 } else {
8995 reportSettingsProblem(Log.WARN,
8996 "Error in package manager settings: package "
8997 + name + " has bad enabled value: " + idStr
8998 + " at " + parser.getPositionDescription());
8999 }
9000 } else {
9001 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9002 }
9003 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9004 if (installStatusStr != null) {
9005 if (installStatusStr.equalsIgnoreCase("false")) {
9006 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9007 } else {
9008 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9009 }
9010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 int outerDepth = parser.getDepth();
9013 int type;
9014 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9015 && (type != XmlPullParser.END_TAG
9016 || parser.getDepth() > outerDepth)) {
9017 if (type == XmlPullParser.END_TAG
9018 || type == XmlPullParser.TEXT) {
9019 continue;
9020 }
9021
9022 String tagName = parser.getName();
9023 if (tagName.equals("disabled-components")) {
9024 readDisabledComponentsLP(packageSetting, parser);
9025 } else if (tagName.equals("enabled-components")) {
9026 readEnabledComponentsLP(packageSetting, parser);
9027 } else if (tagName.equals("sigs")) {
9028 packageSetting.signatures.readXml(parser, mPastSignatures);
9029 } else if (tagName.equals("perms")) {
9030 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009031 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 packageSetting.permissionsFixed = true;
9033 } else {
9034 reportSettingsProblem(Log.WARN,
9035 "Unknown element under <package>: "
9036 + parser.getName());
9037 XmlUtils.skipCurrentTag(parser);
9038 }
9039 }
9040 } else {
9041 XmlUtils.skipCurrentTag(parser);
9042 }
9043 }
9044
9045 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9046 XmlPullParser parser)
9047 throws IOException, XmlPullParserException {
9048 int outerDepth = parser.getDepth();
9049 int type;
9050 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9051 && (type != XmlPullParser.END_TAG
9052 || parser.getDepth() > outerDepth)) {
9053 if (type == XmlPullParser.END_TAG
9054 || type == XmlPullParser.TEXT) {
9055 continue;
9056 }
9057
9058 String tagName = parser.getName();
9059 if (tagName.equals("item")) {
9060 String name = parser.getAttributeValue(null, "name");
9061 if (name != null) {
9062 packageSetting.disabledComponents.add(name.intern());
9063 } else {
9064 reportSettingsProblem(Log.WARN,
9065 "Error in package manager settings: <disabled-components> has"
9066 + " no name at " + parser.getPositionDescription());
9067 }
9068 } else {
9069 reportSettingsProblem(Log.WARN,
9070 "Unknown element under <disabled-components>: "
9071 + parser.getName());
9072 }
9073 XmlUtils.skipCurrentTag(parser);
9074 }
9075 }
9076
9077 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9078 XmlPullParser parser)
9079 throws IOException, XmlPullParserException {
9080 int outerDepth = parser.getDepth();
9081 int type;
9082 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9083 && (type != XmlPullParser.END_TAG
9084 || parser.getDepth() > outerDepth)) {
9085 if (type == XmlPullParser.END_TAG
9086 || type == XmlPullParser.TEXT) {
9087 continue;
9088 }
9089
9090 String tagName = parser.getName();
9091 if (tagName.equals("item")) {
9092 String name = parser.getAttributeValue(null, "name");
9093 if (name != null) {
9094 packageSetting.enabledComponents.add(name.intern());
9095 } else {
9096 reportSettingsProblem(Log.WARN,
9097 "Error in package manager settings: <enabled-components> has"
9098 + " no name at " + parser.getPositionDescription());
9099 }
9100 } else {
9101 reportSettingsProblem(Log.WARN,
9102 "Unknown element under <enabled-components>: "
9103 + parser.getName());
9104 }
9105 XmlUtils.skipCurrentTag(parser);
9106 }
9107 }
9108
9109 private void readSharedUserLP(XmlPullParser parser)
9110 throws XmlPullParserException, IOException {
9111 String name = null;
9112 String idStr = null;
9113 int pkgFlags = 0;
9114 SharedUserSetting su = null;
9115 try {
9116 name = parser.getAttributeValue(null, "name");
9117 idStr = parser.getAttributeValue(null, "userId");
9118 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9119 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9120 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9121 }
9122 if (name == null) {
9123 reportSettingsProblem(Log.WARN,
9124 "Error in package manager settings: <shared-user> has no name at "
9125 + parser.getPositionDescription());
9126 } else if (userId == 0) {
9127 reportSettingsProblem(Log.WARN,
9128 "Error in package manager settings: shared-user "
9129 + name + " has bad userId " + idStr + " at "
9130 + parser.getPositionDescription());
9131 } else {
9132 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9133 reportSettingsProblem(Log.ERROR,
9134 "Occurred while parsing settings at "
9135 + parser.getPositionDescription());
9136 }
9137 }
9138 } catch (NumberFormatException e) {
9139 reportSettingsProblem(Log.WARN,
9140 "Error in package manager settings: package "
9141 + name + " has bad userId " + idStr + " at "
9142 + parser.getPositionDescription());
9143 };
9144
9145 if (su != null) {
9146 int outerDepth = parser.getDepth();
9147 int type;
9148 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9149 && (type != XmlPullParser.END_TAG
9150 || parser.getDepth() > outerDepth)) {
9151 if (type == XmlPullParser.END_TAG
9152 || type == XmlPullParser.TEXT) {
9153 continue;
9154 }
9155
9156 String tagName = parser.getName();
9157 if (tagName.equals("sigs")) {
9158 su.signatures.readXml(parser, mPastSignatures);
9159 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009160 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 } else {
9162 reportSettingsProblem(Log.WARN,
9163 "Unknown element under <shared-user>: "
9164 + parser.getName());
9165 XmlUtils.skipCurrentTag(parser);
9166 }
9167 }
9168
9169 } else {
9170 XmlUtils.skipCurrentTag(parser);
9171 }
9172 }
9173
9174 private void readGrantedPermissionsLP(XmlPullParser parser,
9175 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9176 int outerDepth = parser.getDepth();
9177 int type;
9178 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9179 && (type != XmlPullParser.END_TAG
9180 || parser.getDepth() > outerDepth)) {
9181 if (type == XmlPullParser.END_TAG
9182 || type == XmlPullParser.TEXT) {
9183 continue;
9184 }
9185
9186 String tagName = parser.getName();
9187 if (tagName.equals("item")) {
9188 String name = parser.getAttributeValue(null, "name");
9189 if (name != null) {
9190 outPerms.add(name.intern());
9191 } else {
9192 reportSettingsProblem(Log.WARN,
9193 "Error in package manager settings: <perms> has"
9194 + " no name at " + parser.getPositionDescription());
9195 }
9196 } else {
9197 reportSettingsProblem(Log.WARN,
9198 "Unknown element under <perms>: "
9199 + parser.getName());
9200 }
9201 XmlUtils.skipCurrentTag(parser);
9202 }
9203 }
9204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009205 private void readPreferredActivitiesLP(XmlPullParser parser)
9206 throws XmlPullParserException, IOException {
9207 int outerDepth = parser.getDepth();
9208 int type;
9209 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9210 && (type != XmlPullParser.END_TAG
9211 || parser.getDepth() > outerDepth)) {
9212 if (type == XmlPullParser.END_TAG
9213 || type == XmlPullParser.TEXT) {
9214 continue;
9215 }
9216
9217 String tagName = parser.getName();
9218 if (tagName.equals("item")) {
9219 PreferredActivity pa = new PreferredActivity(parser);
9220 if (pa.mParseError == null) {
9221 mPreferredActivities.addFilter(pa);
9222 } else {
9223 reportSettingsProblem(Log.WARN,
9224 "Error in package manager settings: <preferred-activity> "
9225 + pa.mParseError + " at "
9226 + parser.getPositionDescription());
9227 }
9228 } else {
9229 reportSettingsProblem(Log.WARN,
9230 "Unknown element under <preferred-activities>: "
9231 + parser.getName());
9232 XmlUtils.skipCurrentTag(parser);
9233 }
9234 }
9235 }
9236
9237 // Returns -1 if we could not find an available UserId to assign
9238 private int newUserIdLP(Object obj) {
9239 // Let's be stupidly inefficient for now...
9240 final int N = mUserIds.size();
9241 for (int i=0; i<N; i++) {
9242 if (mUserIds.get(i) == null) {
9243 mUserIds.set(i, obj);
9244 return FIRST_APPLICATION_UID + i;
9245 }
9246 }
9247
9248 // None left?
9249 if (N >= MAX_APPLICATION_UIDS) {
9250 return -1;
9251 }
9252
9253 mUserIds.add(obj);
9254 return FIRST_APPLICATION_UID + N;
9255 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009257 public PackageSetting getDisabledSystemPkg(String name) {
9258 synchronized(mPackages) {
9259 PackageSetting ps = mDisabledSysPackages.get(name);
9260 return ps;
9261 }
9262 }
9263
9264 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9265 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9266 if (Config.LOGV) {
9267 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9268 + " componentName = " + componentInfo.name);
9269 Log.v(TAG, "enabledComponents: "
9270 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9271 Log.v(TAG, "disabledComponents: "
9272 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9273 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009274 if (packageSettings == null) {
9275 if (false) {
9276 Log.w(TAG, "WAITING FOR DEBUGGER");
9277 Debug.waitForDebugger();
9278 Log.i(TAG, "We will crash!");
9279 }
9280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9282 || ((componentInfo.enabled
9283 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9284 || (componentInfo.applicationInfo.enabled
9285 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9286 && !packageSettings.disabledComponents.contains(componentInfo.name))
9287 || packageSettings.enabledComponents.contains(componentInfo.name));
9288 }
9289 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009290
9291 // ------- apps on sdcard specific code -------
9292 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009293 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009294 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009295 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009296 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009297
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009298 private String getEncryptKey() {
9299 try {
9300 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9301 if (sdEncKey == null) {
9302 sdEncKey = SystemKeyStore.getInstance().
9303 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9304 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009305 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009306 return null;
9307 }
9308 }
9309 return sdEncKey;
9310 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009311 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009312 return null;
9313 }
9314 }
9315
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009316 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009317 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009318 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009319 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009320 if (list != null) {
9321 int idx = 0;
9322 int idList[] = new int[MAX_CONTAINERS];
9323 boolean neverFound = true;
9324 for (String name : list) {
9325 // Ignore null entries
9326 if (name == null) {
9327 continue;
9328 }
9329 int sidx = name.indexOf(prefix);
9330 if (sidx == -1) {
9331 // Not a temp file. just ignore
9332 continue;
9333 }
9334 String subStr = name.substring(sidx + prefix.length());
9335 idList[idx] = -1;
9336 if (subStr != null) {
9337 try {
9338 int cid = Integer.parseInt(subStr);
9339 idList[idx++] = cid;
9340 neverFound = false;
9341 } catch (NumberFormatException e) {
9342 }
9343 }
9344 }
9345 if (!neverFound) {
9346 // Sort idList
9347 Arrays.sort(idList);
9348 for (int j = 1; j <= idList.length; j++) {
9349 if (idList[j-1] != j) {
9350 tmpIdx = j;
9351 break;
9352 }
9353 }
9354 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009355 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009356 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009357 }
9358
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009359 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009360 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009361 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009362 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9363 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9364 throw new SecurityException("Media status can only be updated by the system");
9365 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009366 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009367 Log.i(TAG, "Updating external media status from " +
9368 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9369 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009370 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9371 mediaStatus+", mMediaMounted=" + mMediaMounted);
9372 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009373 if (reportStatus) {
9374 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9375 }
9376 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009377 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009378 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009379 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009380 // Queue up an async operation since the package installation may take a little while.
9381 mHandler.post(new Runnable() {
9382 public void run() {
9383 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009384 try {
9385 updateExternalMediaStatusInner(mediaStatus);
9386 } finally {
9387 if (reportStatus) {
9388 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9389 }
9390 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009391 }
9392 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009393 }
9394
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009395 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009396 // If we are up here that means there are packages to be
9397 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009398 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009399 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009400 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009401 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009402 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009403
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009404 int uidList[] = new int[list.length];
9405 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009406 HashSet<String> removeCids = new HashSet<String>();
9407 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009408 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009409 for (String cid : list) {
9410 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009411 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9412 boolean failed = true;
9413 try {
9414 String pkgName = args.getPackageName();
9415 if (pkgName == null) {
9416 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009417 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009418 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9419 PackageSetting ps = mSettings.mPackages.get(pkgName);
9420 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009421 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009422 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9423 " corresponds to pkg : " + pkgName +
9424 " at code path: " + ps.codePathString);
9425 // We do have a valid package installed on sdcard
9426 processCids.put(args, ps.codePathString);
9427 failed = false;
9428 int uid = ps.userId;
9429 if (uid != -1) {
9430 uidList[num++] = uid;
9431 }
9432 }
9433 } finally {
9434 if (failed) {
9435 // Stale container on sdcard. Just delete
9436 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9437 removeCids.add(cid);
9438 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009439 }
9440 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009441 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009442 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009443 int uidArr[] = null;
9444 if (num > 0) {
9445 // Sort uid list
9446 Arrays.sort(uidList, 0, num);
9447 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009448 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009449 uidArr[0] = uidList[0];
9450 int di = 0;
9451 for (int i = 1; i < num; i++) {
9452 if (uidList[i-1] != uidList[i]) {
9453 uidArr[di++] = uidList[i];
9454 }
9455 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009456 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009457 // Process packages with valid entries.
9458 if (mediaStatus) {
9459 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009460 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009461 startCleaningPackages();
9462 } else {
9463 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009464 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009465 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009466 }
9467
9468 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9469 ArrayList<String> pkgList, int uidArr[]) {
9470 int size = pkgList.size();
9471 if (size > 0) {
9472 // Send broadcasts here
9473 Bundle extras = new Bundle();
9474 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9475 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009476 if (uidArr != null) {
9477 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9478 }
9479 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9480 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009481 sendPackageBroadcast(action, null, extras);
9482 }
9483 }
9484
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009485 /*
9486 * Look at potentially valid container ids from processCids
9487 * If package information doesn't match the one on record
9488 * or package scanning fails, the cid is added to list of
9489 * removeCids and cleaned up. Since cleaning up containers
9490 * involves destroying them, we do not want any parse
9491 * references to such stale containers. So force gc's
9492 * to avoid unnecessary crashes.
9493 */
9494 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009495 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009496 ArrayList<String> pkgList = new ArrayList<String>();
9497 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009498 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009499 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009500 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009501 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9502 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009503 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009504 try {
9505 // Make sure there are no container errors first.
9506 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9507 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009508 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009509 " when installing from sdcard");
9510 continue;
9511 }
9512 // Check code path here.
9513 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009514 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009515 " does not match one in settings " + codePath);
9516 continue;
9517 }
9518 // Parse package
9519 int parseFlags = PackageParser.PARSE_CHATTY |
Jeff Brown07330792010-03-30 19:57:08 -07009520 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009521 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009522 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009523 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9524 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009525 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009526 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009528 retCode = PackageManager.INSTALL_SUCCEEDED;
9529 pkgList.add(pkg.packageName);
9530 // Post process args
9531 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9532 }
9533 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009534 Slog.i(TAG, "Failed to install pkg from " +
9535 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009536 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009537 }
9538
9539 } finally {
9540 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9541 // Don't destroy container here. Wait till gc clears things up.
9542 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009543 }
9544 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009546 synchronized (mPackages) {
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009547 // Make sure group IDs have been assigned, and any permission
9548 // changes in other apps are accounted for
9549 updatePermissionsLP(null, null, true, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009550 // Persist settings
9551 mSettings.writeLP();
9552 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009553 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009554 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009555 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9556 }
9557 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009558 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009560 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 if (removeCids != null) {
9562 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009563 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009565 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009566 }
9567
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009568 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009569 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009570 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009571 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009572 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009573 Set<SdInstallArgs> keys = processCids.keySet();
9574 for (SdInstallArgs args : keys) {
9575 String cid = args.cid;
9576 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009577 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 // Delete package internally
9579 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9580 synchronized (mInstallLock) {
9581 boolean res = deletePackageLI(pkgName, false,
9582 PackageManager.DONT_DELETE_DATA, outInfo);
9583 if (res) {
9584 pkgList.add(pkgName);
9585 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009586 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009587 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009588 }
9589 }
9590 }
9591 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009592 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009593 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009594 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009595 // Force gc
9596 Runtime.getRuntime().gc();
9597 // Just unmount all valid containers.
9598 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009599 synchronized (mInstallLock) {
9600 args.doPostDeleteLI(false);
9601 }
9602 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009603 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009604
9605 public void movePackage(final String packageName,
9606 final IPackageMoveObserver observer, final int flags) {
9607 if (packageName == null) {
9608 return;
9609 }
9610 mContext.enforceCallingOrSelfPermission(
9611 android.Manifest.permission.MOVE_PACKAGE, null);
9612 int returnCode = PackageManager.MOVE_SUCCEEDED;
9613 int currFlags = 0;
9614 int newFlags = 0;
9615 synchronized (mPackages) {
9616 PackageParser.Package pkg = mPackages.get(packageName);
9617 if (pkg == null) {
9618 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9619 }
9620 // Disable moving fwd locked apps and system packages
9621 if (pkg.applicationInfo != null &&
9622 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009623 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009624 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9625 } else if (pkg.applicationInfo != null &&
9626 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009627 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009628 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9629 } else {
9630 // Find install location first
9631 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9632 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009633 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009634 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9635 } else {
9636 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9637 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009638 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009639 PackageManager.INSTALL_EXTERNAL : 0;
9640 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009641 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009642 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9643 }
9644 }
9645 }
9646 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9647 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9648 } else {
9649 Message msg = mHandler.obtainMessage(INIT_COPY);
9650 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9651 pkg.applicationInfo.publicSourceDir);
9652 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9653 packageName);
9654 msg.obj = mp;
9655 mHandler.sendMessage(msg);
9656 }
9657 }
9658 }
9659
9660 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9661 // Queue up an async operation since the package deletion may take a little while.
9662 mHandler.post(new Runnable() {
9663 public void run() {
9664 mHandler.removeCallbacks(this);
9665 int returnCode = currentStatus;
9666 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9667 if (moveSucceeded) {
9668 int uid = -1;
9669 synchronized (mPackages) {
9670 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9671 }
9672 ArrayList<String> pkgList = new ArrayList<String>();
9673 pkgList.add(mp.packageName);
9674 int uidArr[] = new int[] { uid };
9675 // Send resources unavailable broadcast
9676 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9677
9678 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009679 synchronized (mInstallLock) {
9680 synchronized (mPackages) {
9681 PackageParser.Package pkg = mPackages.get(mp.packageName);
9682 if (pkg != null) {
9683 String oldCodePath = pkg.mPath;
9684 String newCodePath = mp.targetArgs.getCodePath();
9685 String newResPath = mp.targetArgs.getResourcePath();
9686 pkg.mPath = newCodePath;
9687 // Move dex files around
9688 if (moveDexFilesLI(pkg)
9689 != PackageManager.INSTALL_SUCCEEDED) {
9690 // Moving of dex files failed. Set
9691 // error code and abort move.
9692 pkg.mPath = pkg.mScanPath;
9693 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9694 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009695 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009696 pkg.mScanPath = newCodePath;
9697 pkg.applicationInfo.sourceDir = newCodePath;
9698 pkg.applicationInfo.publicSourceDir = newResPath;
9699 PackageSetting ps = (PackageSetting) pkg.mExtras;
9700 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9701 ps.codePathString = ps.codePath.getPath();
9702 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9703 ps.resourcePathString = ps.resourcePath.getPath();
9704 // Set the application info flag correctly.
9705 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9706 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9707 } else {
9708 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9709 }
9710 ps.setFlags(pkg.applicationInfo.flags);
9711 mAppDirs.remove(oldCodePath);
9712 mAppDirs.put(newCodePath, pkg);
9713 // Persist settings
9714 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009715 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009716 }
9717 }
9718 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009719 // Send resources available broadcast
9720 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009721 }
9722 if (!moveSucceeded){
9723 // Clean up failed installation
9724 if (mp.targetArgs != null) {
9725 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009726 returnCode);
9727 }
9728 } else {
9729 // Force a gc to clear things up.
9730 Runtime.getRuntime().gc();
9731 // Delete older code
9732 synchronized (mInstallLock) {
9733 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009734 }
9735 }
9736 IPackageMoveObserver observer = mp.observer;
9737 if (observer != null) {
9738 try {
9739 observer.packageMoved(mp.packageName, returnCode);
9740 } catch (RemoteException e) {
9741 Log.i(TAG, "Observer no longer exists.");
9742 }
9743 }
9744 }
9745 });
9746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009747}