blob: 79b012ba8828c580afe4f7f6a0ce17be4eac14c0 [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;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800341
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700342 // Delay time in millisecs
343 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344 final private DefaultContainerConnection mDefContainerConn =
345 new DefaultContainerConnection();
346 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800348 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800349 IMediaContainerService imcs =
350 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 }
353
354 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 }
357 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700358
Christopher Tate1bb69062010-02-19 17:02:12 -0800359 // Recordkeeping of restore-after-install operations that are currently in flight
360 // between the Package Manager and the Backup Manager
361 class PostInstallData {
362 public InstallArgs args;
363 public PackageInstalledInfo res;
364
365 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
366 args = _a;
367 res = _r;
368 }
369 };
370 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
371 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
372
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700373 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800374 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800375 final ArrayList<HandlerParams> mPendingInstalls =
376 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800377
378 private boolean connectToService() {
379 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
380 " DefaultContainerService");
381 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
382 if (mContext.bindService(service, mDefContainerConn,
383 Context.BIND_AUTO_CREATE)) {
384 mBound = true;
385 return true;
386 }
387 return false;
388 }
389
390 private void disconnectService() {
391 mContainerService = null;
392 mBound = false;
393 mContext.unbindService(mDefContainerConn);
394 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800395
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700396 PackageHandler(Looper looper) {
397 super(looper);
398 }
399 public void handleMessage(Message msg) {
400 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800401 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800403 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800404 int idx = mPendingInstalls.size();
405 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
406 // If a bind was already initiated we dont really
407 // need to do anything. The pending install
408 // will be processed later on.
409 if (!mBound) {
410 // If this is the only one pending we might
411 // have to bind to the service again.
412 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800413 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 params.serviceError();
415 return;
416 } else {
417 // Once we bind to the service, the first
418 // pending request will be processed.
419 mPendingInstalls.add(idx, params);
420 }
421 } else {
422 mPendingInstalls.add(idx, params);
423 // Already bound to the service. Just make
424 // sure we trigger off processing the first request.
425 if (idx == 0) {
426 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800427 }
428 }
429 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800430 }
431 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800432 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800433 if (msg.obj != null) {
434 mContainerService = (IMediaContainerService) msg.obj;
435 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (mContainerService == null) {
437 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800438 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800439 for (HandlerParams params : mPendingInstalls) {
440 mPendingInstalls.remove(0);
441 // Indicate service bind error
442 params.serviceError();
443 }
444 mPendingInstalls.clear();
445 } else if (mPendingInstalls.size() > 0) {
446 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800447 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800448 params.startCopy();
449 }
450 } else {
451 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800452 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 }
454 break;
455 }
456 case MCS_RECONNECT : {
457 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
458 if (mPendingInstalls.size() > 0) {
459 if (mBound) {
460 disconnectService();
461 }
462 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800463 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800464 for (HandlerParams params : mPendingInstalls) {
465 mPendingInstalls.remove(0);
466 // Indicate service bind error
467 params.serviceError();
468 }
469 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800470 }
471 }
472 break;
473 }
474 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
476 // Delete pending install
477 if (mPendingInstalls.size() > 0) {
478 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800479 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800480 if (mPendingInstalls.size() == 0) {
481 if (mBound) {
482 disconnectService();
483 }
484 } else {
485 // There are more pending requests in queue.
486 // Just post MCS_BOUND message to trigger processing
487 // of next pending install.
488 mHandler.sendEmptyMessage(MCS_BOUND);
489 }
490 break;
491 }
492 case MCS_GIVE_UP: {
493 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
494 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800495 break;
496 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700497 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800498 String packages[];
499 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700500 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700501 int uids[];
502 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800503 if (mPendingBroadcasts == null) {
504 return;
505 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700506 size = mPendingBroadcasts.size();
507 if (size <= 0) {
508 // Nothing to be done. Just return
509 return;
510 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800511 packages = new String[size];
512 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700513 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800514 Iterator<HashMap.Entry<String, ArrayList<String>>>
515 it = mPendingBroadcasts.entrySet().iterator();
516 int i = 0;
517 while (it.hasNext() && i < size) {
518 HashMap.Entry<String, ArrayList<String>> ent = it.next();
519 packages[i] = ent.getKey();
520 components[i] = ent.getValue();
521 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700522 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800523 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800525 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700526 mPendingBroadcasts.clear();
527 }
528 // Send broadcasts
529 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800530 sendPackageChangedBroadcast(packages[i], true,
531 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700532 }
533 break;
534 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800535 case START_CLEANING_PACKAGE: {
536 String packageName = (String)msg.obj;
537 synchronized (mPackages) {
538 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
539 mSettings.mPackagesToBeCleaned.add(packageName);
540 }
541 }
542 startCleaningPackages();
543 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800544 case POST_INSTALL: {
545 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
546 PostInstallData data = mRunningInstalls.get(msg.arg1);
547 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800548 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800549
550 if (data != null) {
551 InstallArgs args = data.args;
552 PackageInstalledInfo res = data.res;
553
554 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
555 res.removedInfo.sendBroadcast(false, true);
556 Bundle extras = new Bundle(1);
557 extras.putInt(Intent.EXTRA_UID, res.uid);
558 final boolean update = res.removedInfo.removedPackage != null;
559 if (update) {
560 extras.putBoolean(Intent.EXTRA_REPLACING, true);
561 }
562 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
563 res.pkg.applicationInfo.packageName,
564 extras);
565 if (update) {
566 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
567 res.pkg.applicationInfo.packageName,
568 extras);
569 }
570 if (res.removedInfo.args != null) {
571 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800572 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800573 }
574 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800575 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800576 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800577 // We delete after a gc for applications on sdcard.
578 if (deleteOld) {
579 synchronized (mInstallLock) {
580 res.removedInfo.args.doPostDeleteLI(true);
581 }
582 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800583 if (args.observer != null) {
584 try {
585 args.observer.packageInstalled(res.name, res.returnCode);
586 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800587 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800588 }
589 }
590 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800591 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800592 }
593 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700594 case UPDATED_MEDIA_STATUS: {
595 try {
596 PackageHelper.getMountService().finishMediaUpdate();
597 } catch (RemoteException e) {
598 Log.e(TAG, "MountService not running?");
599 }
600 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700601 }
602 }
603 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800604
605 static boolean installOnSd(int flags) {
606 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700607 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800608 return false;
609 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700610 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
611 return true;
612 }
613 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800614 }
615
616 static boolean isFwdLocked(int flags) {
617 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
618 return true;
619 }
620 return false;
621 }
622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 public static final IPackageManager main(Context context, boolean factoryTest) {
624 PackageManagerService m = new PackageManagerService(context, factoryTest);
625 ServiceManager.addService("package", m);
626 return m;
627 }
628
629 static String[] splitString(String str, char sep) {
630 int count = 1;
631 int i = 0;
632 while ((i=str.indexOf(sep, i)) >= 0) {
633 count++;
634 i++;
635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 String[] res = new String[count];
638 i=0;
639 count = 0;
640 int lastI=0;
641 while ((i=str.indexOf(sep, i)) >= 0) {
642 res[count] = str.substring(lastI, i);
643 count++;
644 i++;
645 lastI = i;
646 }
647 res[count] = str.substring(lastI, str.length());
648 return res;
649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800652 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800656 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 mContext = context;
660 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700661 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 mMetrics = new DisplayMetrics();
663 mSettings = new Settings();
664 mSettings.addSharedUserLP("android.uid.system",
665 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
666 mSettings.addSharedUserLP("android.uid.phone",
667 MULTIPLE_APPLICATION_UIDS
668 ? RADIO_UID : FIRST_APPLICATION_UID,
669 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400670 mSettings.addSharedUserLP("android.uid.log",
671 MULTIPLE_APPLICATION_UIDS
672 ? LOG_UID : FIRST_APPLICATION_UID,
673 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674
675 String separateProcesses = SystemProperties.get("debug.separate_processes");
676 if (separateProcesses != null && separateProcesses.length() > 0) {
677 if ("*".equals(separateProcesses)) {
678 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
679 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800680 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 } else {
682 mDefParseFlags = 0;
683 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800684 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 + separateProcesses);
686 }
687 } else {
688 mDefParseFlags = 0;
689 mSeparateProcesses = null;
690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 Installer installer = new Installer();
693 // Little hacky thing to check if installd is here, to determine
694 // whether we are running on the simulator and thus need to take
695 // care of building the /data file structure ourself.
696 // (apparently the sim now has a working installer)
697 if (installer.ping() && Process.supportsProcesses()) {
698 mInstaller = installer;
699 } else {
700 mInstaller = null;
701 }
702
703 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
704 Display d = wm.getDefaultDisplay();
705 d.getMetrics(mMetrics);
706
707 synchronized (mInstallLock) {
708 synchronized (mPackages) {
709 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700710 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 File dataDir = Environment.getDataDirectory();
713 mAppDataDir = new File(dataDir, "data");
714 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
715
716 if (mInstaller == null) {
717 // Make sure these dirs exist, when we are running in
718 // the simulator.
719 // Make a wide-open directory for random misc stuff.
720 File miscDir = new File(dataDir, "misc");
721 miscDir.mkdirs();
722 mAppDataDir.mkdirs();
723 mDrmAppPrivateInstallDir.mkdirs();
724 }
725
726 readPermissions();
727
728 mRestoredSettings = mSettings.readLP();
729 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800730
731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800733
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800734 // Set flag to monitor and not change apk file paths when
735 // scanning install directories.
736 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700737 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800738 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800739 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700745 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700748 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 /**
751 * Out of paranoia, ensure that everything in the boot class
752 * path has been dexed.
753 */
754 String bootClassPath = System.getProperty("java.boot.class.path");
755 if (bootClassPath != null) {
756 String[] paths = splitString(bootClassPath, ':');
757 for (int i=0; i<paths.length; i++) {
758 try {
759 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
760 libFiles.add(paths[i]);
761 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700762 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 }
764 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800765 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800767 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 }
770 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800771 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 /**
775 * Also ensure all external libraries have had dexopt run on them.
776 */
777 if (mSharedLibraries.size() > 0) {
778 Iterator<String> libs = mSharedLibraries.values().iterator();
779 while (libs.hasNext()) {
780 String lib = libs.next();
781 try {
782 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
783 libFiles.add(lib);
784 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700785 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 }
787 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800788 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800790 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 }
793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 // Gross hack for now: we know this file doesn't contain any
796 // code, so don't dexopt it to avoid the resulting log spew.
797 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 /**
800 * And there are a number of commands implemented in Java, which
801 * we currently need to do the dexopt on so that they can be
802 * run from a non-root shell.
803 */
804 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700805 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 for (int i=0; i<frameworkFiles.length; i++) {
807 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
808 String path = libPath.getPath();
809 // Skip the file if we alrady did it.
810 if (libFiles.contains(path)) {
811 continue;
812 }
813 // Skip the file if it is not a type we want to dexopt.
814 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
815 continue;
816 }
817 try {
818 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
819 mInstaller.dexopt(path, 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, "Jar not found: " + path);
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 jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700830 if (didDexOpt) {
831 // If we had to do a dexopt of one of the previous
832 // things, then something on the system has changed.
833 // Consider this significant, and wipe away all other
834 // existing dexopt files to ensure we don't leave any
835 // dangling around.
836 String[] files = mDalvikCacheDir.list();
837 if (files != null) {
838 for (int i=0; i<files.length; i++) {
839 String fn = files[i];
840 if (fn.startsWith("data@app@")
841 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800842 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700843 (new File(mDalvikCacheDir, fn)).delete();
844 }
845 }
846 }
847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800850 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 mFrameworkInstallObserver = new AppDirObserver(
852 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
853 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700854 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
855 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800856 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800857
858 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
860 mSystemInstallObserver = new AppDirObserver(
861 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
862 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700863 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
864 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800865
866 if (mInstaller != null) {
867 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
868 mInstaller.moveFiles();
869 }
870
871 // Prune any system packages that no longer exist.
872 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
873 while (psit.hasNext()) {
874 PackageSetting ps = psit.next();
875 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800876 && !mPackages.containsKey(ps.name)
877 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800878 psit.remove();
879 String msg = "System package " + ps.name
880 + " no longer exists; wiping its data";
881 reportSettingsProblem(Log.WARN, msg);
882 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700883 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800884 }
885 }
886 }
887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 mAppInstallDir = new File(dataDir, "app");
889 if (mInstaller == null) {
890 // Make sure these dirs exist, when we are running in
891 // the simulator.
892 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
893 }
894 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800895 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 //clean up list
897 for(int i = 0; i < deletePkgsList.size(); i++) {
898 //clean up here
899 cleanupInstallFailedPackage(deletePkgsList.get(i));
900 }
901 //delete tmp files
902 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800903
904 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 SystemClock.uptimeMillis());
906 mAppInstallObserver = new AppDirObserver(
907 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
908 mAppInstallObserver.startWatching();
909 scanDirLI(mAppInstallDir, 0, scanMode);
910
911 mDrmAppInstallObserver = new AppDirObserver(
912 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
913 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800914 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800916 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800918 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 + ((SystemClock.uptimeMillis()-startTime)/1000f)
920 + " seconds");
921
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700922 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
924 mSettings.writeLP();
925
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800926 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 // Now after opening every single application zip, make sure they
930 // are all flushed. Not really needed, but keeps things nice and
931 // tidy.
932 Runtime.getRuntime().gc();
933 } // synchronized (mPackages)
934 } // synchronized (mInstallLock)
935 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 @Override
938 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
939 throws RemoteException {
940 try {
941 return super.onTransact(code, data, reply, flags);
942 } catch (RuntimeException e) {
943 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800944 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 }
946 throw e;
947 }
948 }
949
Dianne Hackborne6620b22010-01-22 14:46:21 -0800950 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800951 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700953 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800955 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800956 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958 } else {
959 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800960 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 File dataDir = new File(pkg.applicationInfo.dataDir);
962 dataDir.delete();
963 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800964 if (ps.codePath != null) {
965 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800966 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800967 }
968 }
969 if (ps.resourcePath != null) {
970 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800971 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -0800972 }
973 }
974 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976
977 void readPermissions() {
978 // Read permissions from .../etc/permission directory.
979 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
980 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800981 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 return;
983 }
984 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800985 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 return;
987 }
988
989 // Iterate over the files in the directory and scan .xml files
990 for (File f : libraryDir.listFiles()) {
991 // We'll read platform.xml last
992 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
993 continue;
994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800997 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 continue;
999 }
1000 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001001 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 continue;
1003 }
1004
1005 readPermissionsFromXml(f);
1006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1009 final File permFile = new File(Environment.getRootDirectory(),
1010 "etc/permissions/platform.xml");
1011 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001012
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001013 StringBuilder sb = new StringBuilder(128);
1014 sb.append("Libs:");
1015 Iterator<String> it = mSharedLibraries.keySet().iterator();
1016 while (it.hasNext()) {
1017 sb.append(' ');
1018 String name = it.next();
1019 sb.append(name);
1020 sb.append(':');
1021 sb.append(mSharedLibraries.get(name));
1022 }
1023 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001024
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001025 sb.setLength(0);
1026 sb.append("Features:");
1027 it = mAvailableFeatures.keySet().iterator();
1028 while (it.hasNext()) {
1029 sb.append(' ');
1030 sb.append(it.next());
1031 }
1032 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001034
1035 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 FileReader permReader = null;
1037 try {
1038 permReader = new FileReader(permFile);
1039 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001040 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 return;
1042 }
1043
1044 try {
1045 XmlPullParser parser = Xml.newPullParser();
1046 parser.setInput(permReader);
1047
1048 XmlUtils.beginDocument(parser, "permissions");
1049
1050 while (true) {
1051 XmlUtils.nextElement(parser);
1052 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1053 break;
1054 }
1055
1056 String name = parser.getName();
1057 if ("group".equals(name)) {
1058 String gidStr = parser.getAttributeValue(null, "gid");
1059 if (gidStr != null) {
1060 int gid = Integer.parseInt(gidStr);
1061 mGlobalGids = appendInt(mGlobalGids, gid);
1062 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 + parser.getPositionDescription());
1065 }
1066
1067 XmlUtils.skipCurrentTag(parser);
1068 continue;
1069 } else if ("permission".equals(name)) {
1070 String perm = parser.getAttributeValue(null, "name");
1071 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001072 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 + parser.getPositionDescription());
1074 XmlUtils.skipCurrentTag(parser);
1075 continue;
1076 }
1077 perm = perm.intern();
1078 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 } else if ("assign-permission".equals(name)) {
1081 String perm = parser.getAttributeValue(null, "name");
1082 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001083 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 + parser.getPositionDescription());
1085 XmlUtils.skipCurrentTag(parser);
1086 continue;
1087 }
1088 String uidStr = parser.getAttributeValue(null, "uid");
1089 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001090 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 + parser.getPositionDescription());
1092 XmlUtils.skipCurrentTag(parser);
1093 continue;
1094 }
1095 int uid = Process.getUidForName(uidStr);
1096 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001097 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 + uidStr + "\" at "
1099 + parser.getPositionDescription());
1100 XmlUtils.skipCurrentTag(parser);
1101 continue;
1102 }
1103 perm = perm.intern();
1104 HashSet<String> perms = mSystemPermissions.get(uid);
1105 if (perms == null) {
1106 perms = new HashSet<String>();
1107 mSystemPermissions.put(uid, perms);
1108 }
1109 perms.add(perm);
1110 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 } else if ("library".equals(name)) {
1113 String lname = parser.getAttributeValue(null, "name");
1114 String lfile = parser.getAttributeValue(null, "file");
1115 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001116 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 + parser.getPositionDescription());
1118 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001119 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 + parser.getPositionDescription());
1121 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001122 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001123 mSharedLibraries.put(lname, lfile);
1124 }
1125 XmlUtils.skipCurrentTag(parser);
1126 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001127
Dianne Hackborn49237342009-08-27 20:08:01 -07001128 } else if ("feature".equals(name)) {
1129 String fname = parser.getAttributeValue(null, "name");
1130 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001131 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001132 + parser.getPositionDescription());
1133 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001134 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001135 FeatureInfo fi = new FeatureInfo();
1136 fi.name = fname;
1137 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139 XmlUtils.skipCurrentTag(parser);
1140 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 } else {
1143 XmlUtils.skipCurrentTag(parser);
1144 continue;
1145 }
1146
1147 }
1148 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001149 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001151 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 }
1153 }
1154
1155 void readPermission(XmlPullParser parser, String name)
1156 throws IOException, XmlPullParserException {
1157
1158 name = name.intern();
1159
1160 BasePermission bp = mSettings.mPermissions.get(name);
1161 if (bp == null) {
1162 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1163 mSettings.mPermissions.put(name, bp);
1164 }
1165 int outerDepth = parser.getDepth();
1166 int type;
1167 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1168 && (type != XmlPullParser.END_TAG
1169 || parser.getDepth() > outerDepth)) {
1170 if (type == XmlPullParser.END_TAG
1171 || type == XmlPullParser.TEXT) {
1172 continue;
1173 }
1174
1175 String tagName = parser.getName();
1176 if ("group".equals(tagName)) {
1177 String gidStr = parser.getAttributeValue(null, "gid");
1178 if (gidStr != null) {
1179 int gid = Process.getGidForName(gidStr);
1180 bp.gids = appendInt(bp.gids, gid);
1181 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001182 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 + parser.getPositionDescription());
1184 }
1185 }
1186 XmlUtils.skipCurrentTag(parser);
1187 }
1188 }
1189
1190 static int[] appendInt(int[] cur, int val) {
1191 if (cur == null) {
1192 return new int[] { val };
1193 }
1194 final int N = cur.length;
1195 for (int i=0; i<N; i++) {
1196 if (cur[i] == val) {
1197 return cur;
1198 }
1199 }
1200 int[] ret = new int[N+1];
1201 System.arraycopy(cur, 0, ret, 0, N);
1202 ret[N] = val;
1203 return ret;
1204 }
1205
1206 static int[] appendInts(int[] cur, int[] add) {
1207 if (add == null) return cur;
1208 if (cur == null) return add;
1209 final int N = add.length;
1210 for (int i=0; i<N; i++) {
1211 cur = appendInt(cur, add[i]);
1212 }
1213 return cur;
1214 }
1215
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001216 static int[] removeInt(int[] cur, int val) {
1217 if (cur == null) {
1218 return null;
1219 }
1220 final int N = cur.length;
1221 for (int i=0; i<N; i++) {
1222 if (cur[i] == val) {
1223 int[] ret = new int[N-1];
1224 if (i > 0) {
1225 System.arraycopy(cur, 0, ret, 0, i);
1226 }
1227 if (i < (N-1)) {
1228 System.arraycopy(cur, i, ret, i+1, N-i-1);
1229 }
1230 return ret;
1231 }
1232 }
1233 return cur;
1234 }
1235
1236 static int[] removeInts(int[] cur, int[] rem) {
1237 if (rem == null) return cur;
1238 if (cur == null) return cur;
1239 final int N = rem.length;
1240 for (int i=0; i<N; i++) {
1241 cur = removeInt(cur, rem[i]);
1242 }
1243 return cur;
1244 }
1245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001246 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001247 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1248 // The package has been uninstalled but has retained data and resources.
1249 return PackageParser.generatePackageInfo(p, null, flags);
1250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 final PackageSetting ps = (PackageSetting)p.mExtras;
1252 if (ps == null) {
1253 return null;
1254 }
1255 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1256 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1257 }
1258
1259 public PackageInfo getPackageInfo(String packageName, int flags) {
1260 synchronized (mPackages) {
1261 PackageParser.Package p = mPackages.get(packageName);
1262 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001263 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 + ": " + p);
1265 if (p != null) {
1266 return generatePackageInfo(p, flags);
1267 }
1268 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1269 return generatePackageInfoFromSettingsLP(packageName, flags);
1270 }
1271 }
1272 return null;
1273 }
1274
Dianne Hackborn47096932010-02-11 15:57:09 -08001275 public String[] currentToCanonicalPackageNames(String[] names) {
1276 String[] out = new String[names.length];
1277 synchronized (mPackages) {
1278 for (int i=names.length-1; i>=0; i--) {
1279 PackageSetting ps = mSettings.mPackages.get(names[i]);
1280 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1281 }
1282 }
1283 return out;
1284 }
1285
1286 public String[] canonicalToCurrentPackageNames(String[] names) {
1287 String[] out = new String[names.length];
1288 synchronized (mPackages) {
1289 for (int i=names.length-1; i>=0; i--) {
1290 String cur = mSettings.mRenamedPackages.get(names[i]);
1291 out[i] = cur != null ? cur : names[i];
1292 }
1293 }
1294 return out;
1295 }
1296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 public int getPackageUid(String packageName) {
1298 synchronized (mPackages) {
1299 PackageParser.Package p = mPackages.get(packageName);
1300 if(p != null) {
1301 return p.applicationInfo.uid;
1302 }
1303 PackageSetting ps = mSettings.mPackages.get(packageName);
1304 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1305 return -1;
1306 }
1307 p = ps.pkg;
1308 return p != null ? p.applicationInfo.uid : -1;
1309 }
1310 }
1311
1312 public int[] getPackageGids(String packageName) {
1313 synchronized (mPackages) {
1314 PackageParser.Package p = mPackages.get(packageName);
1315 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001316 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 + ": " + p);
1318 if (p != null) {
1319 final PackageSetting ps = (PackageSetting)p.mExtras;
1320 final SharedUserSetting suid = ps.sharedUser;
1321 return suid != null ? suid.gids : ps.gids;
1322 }
1323 }
1324 // stupid thing to indicate an error.
1325 return new int[0];
1326 }
1327
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001328 static final PermissionInfo generatePermissionInfo(
1329 BasePermission bp, int flags) {
1330 if (bp.perm != null) {
1331 return PackageParser.generatePermissionInfo(bp.perm, flags);
1332 }
1333 PermissionInfo pi = new PermissionInfo();
1334 pi.name = bp.name;
1335 pi.packageName = bp.sourcePackage;
1336 pi.nonLocalizedLabel = bp.name;
1337 pi.protectionLevel = bp.protectionLevel;
1338 return pi;
1339 }
1340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 public PermissionInfo getPermissionInfo(String name, int flags) {
1342 synchronized (mPackages) {
1343 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001344 if (p != null) {
1345 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
1347 return null;
1348 }
1349 }
1350
1351 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1352 synchronized (mPackages) {
1353 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1354 for (BasePermission p : mSettings.mPermissions.values()) {
1355 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001356 if (p.perm == null || p.perm.info.group == null) {
1357 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001360 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1362 }
1363 }
1364 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 if (out.size() > 0) {
1367 return out;
1368 }
1369 return mPermissionGroups.containsKey(group) ? out : null;
1370 }
1371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1374 synchronized (mPackages) {
1375 return PackageParser.generatePermissionGroupInfo(
1376 mPermissionGroups.get(name), flags);
1377 }
1378 }
1379
1380 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1381 synchronized (mPackages) {
1382 final int N = mPermissionGroups.size();
1383 ArrayList<PermissionGroupInfo> out
1384 = new ArrayList<PermissionGroupInfo>(N);
1385 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1386 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1387 }
1388 return out;
1389 }
1390 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1393 PackageSetting ps = mSettings.mPackages.get(packageName);
1394 if(ps != null) {
1395 if(ps.pkg == null) {
1396 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1397 if(pInfo != null) {
1398 return pInfo.applicationInfo;
1399 }
1400 return null;
1401 }
1402 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1403 }
1404 return null;
1405 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1408 PackageSetting ps = mSettings.mPackages.get(packageName);
1409 if(ps != null) {
1410 if(ps.pkg == null) {
1411 ps.pkg = new PackageParser.Package(packageName);
1412 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001413 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1414 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1415 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1416 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 return generatePackageInfo(ps.pkg, flags);
1419 }
1420 return null;
1421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1424 synchronized (mPackages) {
1425 PackageParser.Package p = mPackages.get(packageName);
1426 if (Config.LOGV) Log.v(
1427 TAG, "getApplicationInfo " + packageName
1428 + ": " + p);
1429 if (p != null) {
1430 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001431 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433 if ("android".equals(packageName)||"system".equals(packageName)) {
1434 return mAndroidApplication;
1435 }
1436 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1437 return generateApplicationInfoFromSettingsLP(packageName, flags);
1438 }
1439 }
1440 return null;
1441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001442
1443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1445 mContext.enforceCallingOrSelfPermission(
1446 android.Manifest.permission.CLEAR_APP_CACHE, null);
1447 // Queue up an async operation since clearing cache may take a little while.
1448 mHandler.post(new Runnable() {
1449 public void run() {
1450 mHandler.removeCallbacks(this);
1451 int retCode = -1;
1452 if (mInstaller != null) {
1453 retCode = mInstaller.freeCache(freeStorageSize);
1454 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001455 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
1457 } //end if mInstaller
1458 if (observer != null) {
1459 try {
1460 observer.onRemoveCompleted(null, (retCode >= 0));
1461 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001462 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
1464 }
1465 }
1466 });
1467 }
1468
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001469 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001470 mContext.enforceCallingOrSelfPermission(
1471 android.Manifest.permission.CLEAR_APP_CACHE, null);
1472 // Queue up an async operation since clearing cache may take a little while.
1473 mHandler.post(new Runnable() {
1474 public void run() {
1475 mHandler.removeCallbacks(this);
1476 int retCode = -1;
1477 if (mInstaller != null) {
1478 retCode = mInstaller.freeCache(freeStorageSize);
1479 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001480 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001481 }
1482 }
1483 if(pi != null) {
1484 try {
1485 // Callback via pending intent
1486 int code = (retCode >= 0) ? 1 : 0;
1487 pi.sendIntent(null, code, null,
1488 null, null);
1489 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001490 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001491 }
1492 }
1493 }
1494 });
1495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1498 synchronized (mPackages) {
1499 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001500
1501 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001503 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 }
1505 if (mResolveComponentName.equals(component)) {
1506 return mResolveActivity;
1507 }
1508 }
1509 return null;
1510 }
1511
1512 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1513 synchronized (mPackages) {
1514 PackageParser.Activity a = mReceivers.mActivities.get(component);
1515 if (Config.LOGV) Log.v(
1516 TAG, "getReceiverInfo " + component + ": " + a);
1517 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1518 return PackageParser.generateActivityInfo(a, flags);
1519 }
1520 }
1521 return null;
1522 }
1523
1524 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1525 synchronized (mPackages) {
1526 PackageParser.Service s = mServices.mServices.get(component);
1527 if (Config.LOGV) Log.v(
1528 TAG, "getServiceInfo " + component + ": " + s);
1529 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1530 return PackageParser.generateServiceInfo(s, flags);
1531 }
1532 }
1533 return null;
1534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 public String[] getSystemSharedLibraryNames() {
1537 Set<String> libSet;
1538 synchronized (mPackages) {
1539 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001540 int size = libSet.size();
1541 if (size > 0) {
1542 String[] libs = new String[size];
1543 libSet.toArray(libs);
1544 return libs;
1545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001547 return null;
1548 }
1549
1550 public FeatureInfo[] getSystemAvailableFeatures() {
1551 Collection<FeatureInfo> featSet;
1552 synchronized (mPackages) {
1553 featSet = mAvailableFeatures.values();
1554 int size = featSet.size();
1555 if (size > 0) {
1556 FeatureInfo[] features = new FeatureInfo[size+1];
1557 featSet.toArray(features);
1558 FeatureInfo fi = new FeatureInfo();
1559 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1560 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1561 features[size] = fi;
1562 return features;
1563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 return null;
1566 }
1567
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001568 public boolean hasSystemFeature(String name) {
1569 synchronized (mPackages) {
1570 return mAvailableFeatures.containsKey(name);
1571 }
1572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 public int checkPermission(String permName, String pkgName) {
1575 synchronized (mPackages) {
1576 PackageParser.Package p = mPackages.get(pkgName);
1577 if (p != null && p.mExtras != null) {
1578 PackageSetting ps = (PackageSetting)p.mExtras;
1579 if (ps.sharedUser != null) {
1580 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1581 return PackageManager.PERMISSION_GRANTED;
1582 }
1583 } else if (ps.grantedPermissions.contains(permName)) {
1584 return PackageManager.PERMISSION_GRANTED;
1585 }
1586 }
1587 }
1588 return PackageManager.PERMISSION_DENIED;
1589 }
1590
1591 public int checkUidPermission(String permName, int uid) {
1592 synchronized (mPackages) {
1593 Object obj = mSettings.getUserIdLP(uid);
1594 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001595 GrantedPermissions gp = (GrantedPermissions)obj;
1596 if (gp.grantedPermissions.contains(permName)) {
1597 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599 } else {
1600 HashSet<String> perms = mSystemPermissions.get(uid);
1601 if (perms != null && perms.contains(permName)) {
1602 return PackageManager.PERMISSION_GRANTED;
1603 }
1604 }
1605 }
1606 return PackageManager.PERMISSION_DENIED;
1607 }
1608
1609 private BasePermission findPermissionTreeLP(String permName) {
1610 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1611 if (permName.startsWith(bp.name) &&
1612 permName.length() > bp.name.length() &&
1613 permName.charAt(bp.name.length()) == '.') {
1614 return bp;
1615 }
1616 }
1617 return null;
1618 }
1619
1620 private BasePermission checkPermissionTreeLP(String permName) {
1621 if (permName != null) {
1622 BasePermission bp = findPermissionTreeLP(permName);
1623 if (bp != null) {
1624 if (bp.uid == Binder.getCallingUid()) {
1625 return bp;
1626 }
1627 throw new SecurityException("Calling uid "
1628 + Binder.getCallingUid()
1629 + " is not allowed to add to permission tree "
1630 + bp.name + " owned by uid " + bp.uid);
1631 }
1632 }
1633 throw new SecurityException("No permission tree found for " + permName);
1634 }
1635
1636 public boolean addPermission(PermissionInfo info) {
1637 synchronized (mPackages) {
1638 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1639 throw new SecurityException("Label must be specified in permission");
1640 }
1641 BasePermission tree = checkPermissionTreeLP(info.name);
1642 BasePermission bp = mSettings.mPermissions.get(info.name);
1643 boolean added = bp == null;
1644 if (added) {
1645 bp = new BasePermission(info.name, tree.sourcePackage,
1646 BasePermission.TYPE_DYNAMIC);
1647 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1648 throw new SecurityException(
1649 "Not allowed to modify non-dynamic permission "
1650 + info.name);
1651 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001652 bp.protectionLevel = info.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 bp.perm = new PackageParser.Permission(tree.perm.owner,
1654 new PermissionInfo(info));
1655 bp.perm.info.packageName = tree.perm.info.packageName;
1656 bp.uid = tree.uid;
1657 if (added) {
1658 mSettings.mPermissions.put(info.name, bp);
1659 }
1660 mSettings.writeLP();
1661 return added;
1662 }
1663 }
1664
1665 public void removePermission(String name) {
1666 synchronized (mPackages) {
1667 checkPermissionTreeLP(name);
1668 BasePermission bp = mSettings.mPermissions.get(name);
1669 if (bp != null) {
1670 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1671 throw new SecurityException(
1672 "Not allowed to modify non-dynamic permission "
1673 + name);
1674 }
1675 mSettings.mPermissions.remove(name);
1676 mSettings.writeLP();
1677 }
1678 }
1679 }
1680
Dianne Hackborn854060af2009-07-09 18:14:31 -07001681 public boolean isProtectedBroadcast(String actionName) {
1682 synchronized (mPackages) {
1683 return mProtectedBroadcasts.contains(actionName);
1684 }
1685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 public int checkSignatures(String pkg1, String pkg2) {
1688 synchronized (mPackages) {
1689 PackageParser.Package p1 = mPackages.get(pkg1);
1690 PackageParser.Package p2 = mPackages.get(pkg2);
1691 if (p1 == null || p1.mExtras == null
1692 || p2 == null || p2.mExtras == null) {
1693 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1694 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001695 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697 }
1698
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001699 public int checkUidSignatures(int uid1, int uid2) {
1700 synchronized (mPackages) {
1701 Signature[] s1;
1702 Signature[] s2;
1703 Object obj = mSettings.getUserIdLP(uid1);
1704 if (obj != null) {
1705 if (obj instanceof SharedUserSetting) {
1706 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1707 } else if (obj instanceof PackageSetting) {
1708 s1 = ((PackageSetting)obj).signatures.mSignatures;
1709 } else {
1710 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1711 }
1712 } else {
1713 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1714 }
1715 obj = mSettings.getUserIdLP(uid2);
1716 if (obj != null) {
1717 if (obj instanceof SharedUserSetting) {
1718 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1719 } else if (obj instanceof PackageSetting) {
1720 s2 = ((PackageSetting)obj).signatures.mSignatures;
1721 } else {
1722 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1723 }
1724 } else {
1725 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1726 }
1727 return checkSignaturesLP(s1, s2);
1728 }
1729 }
1730
1731 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1732 if (s1 == null) {
1733 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1735 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1736 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001737 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1739 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001740 final int N1 = s1.length;
1741 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 for (int i=0; i<N1; i++) {
1743 boolean match = false;
1744 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001745 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 match = true;
1747 break;
1748 }
1749 }
1750 if (!match) {
1751 return PackageManager.SIGNATURE_NO_MATCH;
1752 }
1753 }
1754 return PackageManager.SIGNATURE_MATCH;
1755 }
1756
1757 public String[] getPackagesForUid(int uid) {
1758 synchronized (mPackages) {
1759 Object obj = mSettings.getUserIdLP(uid);
1760 if (obj instanceof SharedUserSetting) {
1761 SharedUserSetting sus = (SharedUserSetting)obj;
1762 final int N = sus.packages.size();
1763 String[] res = new String[N];
1764 Iterator<PackageSetting> it = sus.packages.iterator();
1765 int i=0;
1766 while (it.hasNext()) {
1767 res[i++] = it.next().name;
1768 }
1769 return res;
1770 } else if (obj instanceof PackageSetting) {
1771 PackageSetting ps = (PackageSetting)obj;
1772 return new String[] { ps.name };
1773 }
1774 }
1775 return null;
1776 }
1777
1778 public String getNameForUid(int uid) {
1779 synchronized (mPackages) {
1780 Object obj = mSettings.getUserIdLP(uid);
1781 if (obj instanceof SharedUserSetting) {
1782 SharedUserSetting sus = (SharedUserSetting)obj;
1783 return sus.name + ":" + sus.userId;
1784 } else if (obj instanceof PackageSetting) {
1785 PackageSetting ps = (PackageSetting)obj;
1786 return ps.name;
1787 }
1788 }
1789 return null;
1790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 public int getUidForSharedUser(String sharedUserName) {
1793 if(sharedUserName == null) {
1794 return -1;
1795 }
1796 synchronized (mPackages) {
1797 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1798 if(suid == null) {
1799 return -1;
1800 }
1801 return suid.userId;
1802 }
1803 }
1804
1805 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1806 int flags) {
1807 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001808 return chooseBestActivity(intent, resolvedType, flags, query);
1809 }
1810
Mihai Predaeae850c2009-05-13 10:13:48 +02001811 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1812 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 if (query != null) {
1814 final int N = query.size();
1815 if (N == 1) {
1816 return query.get(0);
1817 } else if (N > 1) {
1818 // If there is more than one activity with the same priority,
1819 // then let the user decide between them.
1820 ResolveInfo r0 = query.get(0);
1821 ResolveInfo r1 = query.get(1);
1822 if (false) {
1823 System.out.println(r0.activityInfo.name +
1824 "=" + r0.priority + " vs " +
1825 r1.activityInfo.name +
1826 "=" + r1.priority);
1827 }
1828 // If the first activity has a higher priority, or a different
1829 // default, then it is always desireable to pick it.
1830 if (r0.priority != r1.priority
1831 || r0.preferredOrder != r1.preferredOrder
1832 || r0.isDefault != r1.isDefault) {
1833 return query.get(0);
1834 }
1835 // If we have saved a preference for a preferred activity for
1836 // this Intent, use that.
1837 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1838 flags, query, r0.priority);
1839 if (ri != null) {
1840 return ri;
1841 }
1842 return mResolveInfo;
1843 }
1844 }
1845 return null;
1846 }
1847
1848 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1849 int flags, List<ResolveInfo> query, int priority) {
1850 synchronized (mPackages) {
1851 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1852 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001853 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1855 if (prefs != null && prefs.size() > 0) {
1856 // First figure out how good the original match set is.
1857 // We will only allow preferred activities that came
1858 // from the same match quality.
1859 int match = 0;
1860 final int N = query.size();
1861 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1862 for (int j=0; j<N; j++) {
1863 ResolveInfo ri = query.get(j);
1864 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1865 + ": 0x" + Integer.toHexString(match));
1866 if (ri.match > match) match = ri.match;
1867 }
1868 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1869 + Integer.toHexString(match));
1870 match &= IntentFilter.MATCH_CATEGORY_MASK;
1871 final int M = prefs.size();
1872 for (int i=0; i<M; i++) {
1873 PreferredActivity pa = prefs.get(i);
1874 if (pa.mMatch != match) {
1875 continue;
1876 }
1877 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1878 if (DEBUG_PREFERRED) {
1879 Log.v(TAG, "Got preferred activity:");
1880 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1881 }
1882 if (ai != null) {
1883 for (int j=0; j<N; j++) {
1884 ResolveInfo ri = query.get(j);
1885 if (!ri.activityInfo.applicationInfo.packageName
1886 .equals(ai.applicationInfo.packageName)) {
1887 continue;
1888 }
1889 if (!ri.activityInfo.name.equals(ai.name)) {
1890 continue;
1891 }
1892
1893 // Okay we found a previously set preferred app.
1894 // If the result set is different from when this
1895 // was created, we need to clear it and re-ask the
1896 // user their preference.
1897 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001898 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 + intent + " type " + resolvedType);
1900 mSettings.mPreferredActivities.removeFilter(pa);
1901 return null;
1902 }
1903
1904 // Yay!
1905 return ri;
1906 }
1907 }
1908 }
1909 }
1910 }
1911 return null;
1912 }
1913
1914 public List<ResolveInfo> queryIntentActivities(Intent intent,
1915 String resolvedType, int flags) {
1916 ComponentName comp = intent.getComponent();
1917 if (comp != null) {
1918 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1919 ActivityInfo ai = getActivityInfo(comp, flags);
1920 if (ai != null) {
1921 ResolveInfo ri = new ResolveInfo();
1922 ri.activityInfo = ai;
1923 list.add(ri);
1924 }
1925 return list;
1926 }
1927
1928 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001929 String pkgName = intent.getPackage();
1930 if (pkgName == null) {
1931 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1932 resolvedType, flags);
1933 }
1934 PackageParser.Package pkg = mPackages.get(pkgName);
1935 if (pkg != null) {
1936 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1937 resolvedType, flags, pkg.activities);
1938 }
1939 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 }
1941 }
1942
1943 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1944 Intent[] specifics, String[] specificTypes, Intent intent,
1945 String resolvedType, int flags) {
1946 final String resultsAction = intent.getAction();
1947
1948 List<ResolveInfo> results = queryIntentActivities(
1949 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1950 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1951
1952 int specificsPos = 0;
1953 int N;
1954
1955 // todo: note that the algorithm used here is O(N^2). This
1956 // isn't a problem in our current environment, but if we start running
1957 // into situations where we have more than 5 or 10 matches then this
1958 // should probably be changed to something smarter...
1959
1960 // First we go through and resolve each of the specific items
1961 // that were supplied, taking care of removing any corresponding
1962 // duplicate items in the generic resolve list.
1963 if (specifics != null) {
1964 for (int i=0; i<specifics.length; i++) {
1965 final Intent sintent = specifics[i];
1966 if (sintent == null) {
1967 continue;
1968 }
1969
1970 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1971 String action = sintent.getAction();
1972 if (resultsAction != null && resultsAction.equals(action)) {
1973 // If this action was explicitly requested, then don't
1974 // remove things that have it.
1975 action = null;
1976 }
1977 ComponentName comp = sintent.getComponent();
1978 ResolveInfo ri = null;
1979 ActivityInfo ai = null;
1980 if (comp == null) {
1981 ri = resolveIntent(
1982 sintent,
1983 specificTypes != null ? specificTypes[i] : null,
1984 flags);
1985 if (ri == null) {
1986 continue;
1987 }
1988 if (ri == mResolveInfo) {
1989 // ACK! Must do something better with this.
1990 }
1991 ai = ri.activityInfo;
1992 comp = new ComponentName(ai.applicationInfo.packageName,
1993 ai.name);
1994 } else {
1995 ai = getActivityInfo(comp, flags);
1996 if (ai == null) {
1997 continue;
1998 }
1999 }
2000
2001 // Look for any generic query activities that are duplicates
2002 // of this specific one, and remove them from the results.
2003 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2004 N = results.size();
2005 int j;
2006 for (j=specificsPos; j<N; j++) {
2007 ResolveInfo sri = results.get(j);
2008 if ((sri.activityInfo.name.equals(comp.getClassName())
2009 && sri.activityInfo.applicationInfo.packageName.equals(
2010 comp.getPackageName()))
2011 || (action != null && sri.filter.matchAction(action))) {
2012 results.remove(j);
2013 if (Config.LOGV) Log.v(
2014 TAG, "Removing duplicate item from " + j
2015 + " due to specific " + specificsPos);
2016 if (ri == null) {
2017 ri = sri;
2018 }
2019 j--;
2020 N--;
2021 }
2022 }
2023
2024 // Add this specific item to its proper place.
2025 if (ri == null) {
2026 ri = new ResolveInfo();
2027 ri.activityInfo = ai;
2028 }
2029 results.add(specificsPos, ri);
2030 ri.specificIndex = i;
2031 specificsPos++;
2032 }
2033 }
2034
2035 // Now we go through the remaining generic results and remove any
2036 // duplicate actions that are found here.
2037 N = results.size();
2038 for (int i=specificsPos; i<N-1; i++) {
2039 final ResolveInfo rii = results.get(i);
2040 if (rii.filter == null) {
2041 continue;
2042 }
2043
2044 // Iterate over all of the actions of this result's intent
2045 // filter... typically this should be just one.
2046 final Iterator<String> it = rii.filter.actionsIterator();
2047 if (it == null) {
2048 continue;
2049 }
2050 while (it.hasNext()) {
2051 final String action = it.next();
2052 if (resultsAction != null && resultsAction.equals(action)) {
2053 // If this action was explicitly requested, then don't
2054 // remove things that have it.
2055 continue;
2056 }
2057 for (int j=i+1; j<N; j++) {
2058 final ResolveInfo rij = results.get(j);
2059 if (rij.filter != null && rij.filter.hasAction(action)) {
2060 results.remove(j);
2061 if (Config.LOGV) Log.v(
2062 TAG, "Removing duplicate item from " + j
2063 + " due to action " + action + " at " + i);
2064 j--;
2065 N--;
2066 }
2067 }
2068 }
2069
2070 // If the caller didn't request filter information, drop it now
2071 // so we don't have to marshall/unmarshall it.
2072 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2073 rii.filter = null;
2074 }
2075 }
2076
2077 // Filter out the caller activity if so requested.
2078 if (caller != null) {
2079 N = results.size();
2080 for (int i=0; i<N; i++) {
2081 ActivityInfo ainfo = results.get(i).activityInfo;
2082 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2083 && caller.getClassName().equals(ainfo.name)) {
2084 results.remove(i);
2085 break;
2086 }
2087 }
2088 }
2089
2090 // If the caller didn't request filter information,
2091 // drop them now so we don't have to
2092 // marshall/unmarshall it.
2093 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2094 N = results.size();
2095 for (int i=0; i<N; i++) {
2096 results.get(i).filter = null;
2097 }
2098 }
2099
2100 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2101 return results;
2102 }
2103
2104 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2105 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002106 ComponentName comp = intent.getComponent();
2107 if (comp != null) {
2108 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2109 ActivityInfo ai = getReceiverInfo(comp, flags);
2110 if (ai != null) {
2111 ResolveInfo ri = new ResolveInfo();
2112 ri.activityInfo = ai;
2113 list.add(ri);
2114 }
2115 return list;
2116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002119 String pkgName = intent.getPackage();
2120 if (pkgName == null) {
2121 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2122 resolvedType, flags);
2123 }
2124 PackageParser.Package pkg = mPackages.get(pkgName);
2125 if (pkg != null) {
2126 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2127 resolvedType, flags, pkg.receivers);
2128 }
2129 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131 }
2132
2133 public ResolveInfo resolveService(Intent intent, String resolvedType,
2134 int flags) {
2135 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2136 flags);
2137 if (query != null) {
2138 if (query.size() >= 1) {
2139 // If there is more than one service with the same priority,
2140 // just arbitrarily pick the first one.
2141 return query.get(0);
2142 }
2143 }
2144 return null;
2145 }
2146
2147 public List<ResolveInfo> queryIntentServices(Intent intent,
2148 String resolvedType, int flags) {
2149 ComponentName comp = intent.getComponent();
2150 if (comp != null) {
2151 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2152 ServiceInfo si = getServiceInfo(comp, flags);
2153 if (si != null) {
2154 ResolveInfo ri = new ResolveInfo();
2155 ri.serviceInfo = si;
2156 list.add(ri);
2157 }
2158 return list;
2159 }
2160
2161 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002162 String pkgName = intent.getPackage();
2163 if (pkgName == null) {
2164 return (List<ResolveInfo>)mServices.queryIntent(intent,
2165 resolvedType, flags);
2166 }
2167 PackageParser.Package pkg = mPackages.get(pkgName);
2168 if (pkg != null) {
2169 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2170 resolvedType, flags, pkg.services);
2171 }
2172 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 public List<PackageInfo> getInstalledPackages(int flags) {
2177 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2178
2179 synchronized (mPackages) {
2180 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2181 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2182 while (i.hasNext()) {
2183 final PackageSetting ps = i.next();
2184 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2185 if(psPkg != null) {
2186 finalList.add(psPkg);
2187 }
2188 }
2189 }
2190 else {
2191 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2192 while (i.hasNext()) {
2193 final PackageParser.Package p = i.next();
2194 if (p.applicationInfo != null) {
2195 PackageInfo pi = generatePackageInfo(p, flags);
2196 if(pi != null) {
2197 finalList.add(pi);
2198 }
2199 }
2200 }
2201 }
2202 }
2203 return finalList;
2204 }
2205
2206 public List<ApplicationInfo> getInstalledApplications(int flags) {
2207 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2208 synchronized(mPackages) {
2209 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2210 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2211 while (i.hasNext()) {
2212 final PackageSetting ps = i.next();
2213 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2214 if(ai != null) {
2215 finalList.add(ai);
2216 }
2217 }
2218 }
2219 else {
2220 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2221 while (i.hasNext()) {
2222 final PackageParser.Package p = i.next();
2223 if (p.applicationInfo != null) {
2224 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2225 if(ai != null) {
2226 finalList.add(ai);
2227 }
2228 }
2229 }
2230 }
2231 }
2232 return finalList;
2233 }
2234
2235 public List<ApplicationInfo> getPersistentApplications(int flags) {
2236 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2237
2238 synchronized (mPackages) {
2239 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2240 while (i.hasNext()) {
2241 PackageParser.Package p = i.next();
2242 if (p.applicationInfo != null
2243 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2244 && (!mSafeMode || (p.applicationInfo.flags
2245 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2246 finalList.add(p.applicationInfo);
2247 }
2248 }
2249 }
2250
2251 return finalList;
2252 }
2253
2254 public ProviderInfo resolveContentProvider(String name, int flags) {
2255 synchronized (mPackages) {
2256 final PackageParser.Provider provider = mProviders.get(name);
2257 return provider != null
2258 && mSettings.isEnabledLP(provider.info, flags)
2259 && (!mSafeMode || (provider.info.applicationInfo.flags
2260 &ApplicationInfo.FLAG_SYSTEM) != 0)
2261 ? PackageParser.generateProviderInfo(provider, flags)
2262 : null;
2263 }
2264 }
2265
Fred Quintana718d8a22009-04-29 17:53:20 -07002266 /**
2267 * @deprecated
2268 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 public void querySyncProviders(List outNames, List outInfo) {
2270 synchronized (mPackages) {
2271 Iterator<Map.Entry<String, PackageParser.Provider>> i
2272 = mProviders.entrySet().iterator();
2273
2274 while (i.hasNext()) {
2275 Map.Entry<String, PackageParser.Provider> entry = i.next();
2276 PackageParser.Provider p = entry.getValue();
2277
2278 if (p.syncable
2279 && (!mSafeMode || (p.info.applicationInfo.flags
2280 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2281 outNames.add(entry.getKey());
2282 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2283 }
2284 }
2285 }
2286 }
2287
2288 public List<ProviderInfo> queryContentProviders(String processName,
2289 int uid, int flags) {
2290 ArrayList<ProviderInfo> finalList = null;
2291
2292 synchronized (mPackages) {
2293 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2294 while (i.hasNext()) {
2295 PackageParser.Provider p = i.next();
2296 if (p.info.authority != null
2297 && (processName == null ||
2298 (p.info.processName.equals(processName)
2299 && p.info.applicationInfo.uid == uid))
2300 && mSettings.isEnabledLP(p.info, flags)
2301 && (!mSafeMode || (p.info.applicationInfo.flags
2302 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2303 if (finalList == null) {
2304 finalList = new ArrayList<ProviderInfo>(3);
2305 }
2306 finalList.add(PackageParser.generateProviderInfo(p,
2307 flags));
2308 }
2309 }
2310 }
2311
2312 if (finalList != null) {
2313 Collections.sort(finalList, mProviderInitOrderSorter);
2314 }
2315
2316 return finalList;
2317 }
2318
2319 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2320 int flags) {
2321 synchronized (mPackages) {
2322 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2323 return PackageParser.generateInstrumentationInfo(i, flags);
2324 }
2325 }
2326
2327 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2328 int flags) {
2329 ArrayList<InstrumentationInfo> finalList =
2330 new ArrayList<InstrumentationInfo>();
2331
2332 synchronized (mPackages) {
2333 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2334 while (i.hasNext()) {
2335 PackageParser.Instrumentation p = i.next();
2336 if (targetPackage == null
2337 || targetPackage.equals(p.info.targetPackage)) {
2338 finalList.add(PackageParser.generateInstrumentationInfo(p,
2339 flags));
2340 }
2341 }
2342 }
2343
2344 return finalList;
2345 }
2346
2347 private void scanDirLI(File dir, int flags, int scanMode) {
2348 Log.d(TAG, "Scanning app dir " + dir);
2349
2350 String[] files = dir.list();
2351
2352 int i;
2353 for (i=0; i<files.length; i++) {
2354 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002355 if (!isPackageFilename(files[i])) {
2356 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002357 continue;
2358 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002359 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002361 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002362 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2363 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002364 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002365 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002366 file.delete();
2367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 }
2369 }
2370
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002371 private static File getSettingsProblemFile() {
2372 File dataDir = Environment.getDataDirectory();
2373 File systemDir = new File(dataDir, "system");
2374 File fname = new File(systemDir, "uiderrors.txt");
2375 return fname;
2376 }
2377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 private static void reportSettingsProblem(int priority, String msg) {
2379 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002380 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 FileOutputStream out = new FileOutputStream(fname, true);
2382 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002383 SimpleDateFormat formatter = new SimpleDateFormat();
2384 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2385 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 pw.close();
2387 FileUtils.setPermissions(
2388 fname.toString(),
2389 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2390 -1, -1);
2391 } catch (java.io.IOException e) {
2392 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002393 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
2395
2396 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2397 PackageParser.Package pkg, File srcFile, int parseFlags) {
2398 if (GET_CERTIFICATES) {
2399 if (ps == null || !ps.codePath.equals(srcFile)
2400 || ps.getTimeStamp() != srcFile.lastModified()) {
2401 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2402 if (!pp.collectCertificates(pkg, parseFlags)) {
2403 mLastScanError = pp.getParseError();
2404 return false;
2405 }
2406 }
2407 }
2408 return true;
2409 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 /*
2412 * Scan a package and return the newly parsed package.
2413 * Returns null in case of errors and the error code is stored in mLastScanError
2414 */
2415 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002416 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002418 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002420 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002422 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002423 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 if (pkg == null) {
2425 mLastScanError = pp.getParseError();
2426 return null;
2427 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002428 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 PackageSetting updatedPkg;
2430 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002431 // Look to see if we already know about this package.
2432 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002433 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002434 // This package has been renamed to its original name. Let's
2435 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002436 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002437 }
2438 // If there was no original package, see one for the real package name.
2439 if (ps == null) {
2440 ps = mSettings.peekPackageLP(pkg.packageName);
2441 }
2442 // Check to see if this package could be hiding/updating a system
2443 // package. Must look for it either under the original or real
2444 // package name depending on our state.
2445 updatedPkg = mSettings.mDisabledSysPackages.get(
2446 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002448 // First check if this is a system package that may involve an update
2449 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2450 if (!ps.codePath.equals(scanFile)) {
2451 // The path has changed from what was last scanned... check the
2452 // version of the new path against what we have stored to determine
2453 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002454 if (pkg.mVersionCode < ps.versionCode) {
2455 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002456 // Ignore entry. Skip it.
2457 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2458 + "ignored: updated version " + ps.versionCode
2459 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002460 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2461 return null;
2462 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002463 // The current app on the system partion is better than
2464 // what we have updated to on the data partition; switch
2465 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002466 // At this point, its safely assumed that package installation for
2467 // apps in system partition will go through. If not there won't be a working
2468 // version of the app
2469 synchronized (mPackages) {
2470 // Just remove the loaded entries from package lists.
2471 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002472 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002473 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002474 + "reverting from " + ps.codePathString
2475 + ": new version " + pkg.mVersionCode
2476 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002477 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2478 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002479 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
2482 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002483 if (updatedPkg != null) {
2484 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2485 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2486 }
2487 // Verify certificates against what was last scanned
2488 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002489 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002490 return null;
2491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 // The apk is forward locked (not public) if its code and resources
2493 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002494 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002496 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002497 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002498
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002499 String codePath = null;
2500 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002501 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2502 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002503 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002504 } else {
2505 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002506 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002507 }
2508 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002509 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002510 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002511 codePath = pkg.mScanPath;
2512 // Set application objects path explicitly.
2513 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002515 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002518 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2519 String destCodePath, String destResPath) {
2520 pkg.mPath = pkg.mScanPath = destCodePath;
2521 pkg.applicationInfo.sourceDir = destCodePath;
2522 pkg.applicationInfo.publicSourceDir = destResPath;
2523 }
2524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 private static String fixProcessName(String defProcessName,
2526 String processName, int uid) {
2527 if (processName == null) {
2528 return defProcessName;
2529 }
2530 return processName;
2531 }
2532
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002533 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2535 if (pkg.mSignatures != null) {
2536 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2537 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002538 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 + " signatures do not match the previously installed version; ignoring!");
2540 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2541 return false;
2542 }
2543
2544 if (pkgSetting.sharedUser != null) {
2545 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2546 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002547 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 + " has no signatures that match those in shared user "
2549 + pkgSetting.sharedUser.name + "; ignoring!");
2550 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2551 return false;
2552 }
2553 }
2554 } else {
2555 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2556 }
2557 return true;
2558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002559
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002560 public boolean performDexOpt(String packageName) {
2561 if (!mNoDexOpt) {
2562 return false;
2563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002564
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002565 PackageParser.Package p;
2566 synchronized (mPackages) {
2567 p = mPackages.get(packageName);
2568 if (p == null || p.mDidDexOpt) {
2569 return false;
2570 }
2571 }
2572 synchronized (mInstallLock) {
2573 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2574 }
2575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002576
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002577 static final int DEX_OPT_SKIPPED = 0;
2578 static final int DEX_OPT_PERFORMED = 1;
2579 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002580
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002581 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2582 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002583 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002584 String path = pkg.mScanPath;
2585 int ret = 0;
2586 try {
2587 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002588 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002589 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002590 pkg.mDidDexOpt = true;
2591 performed = true;
2592 }
2593 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002594 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002595 ret = -1;
2596 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002597 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002598 ret = -1;
2599 }
2600 if (ret < 0) {
2601 //error from installer
2602 return DEX_OPT_FAILED;
2603 }
2604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002605
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002606 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2607 }
2608
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002609 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2610 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002611 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002612 + " to " + newPkg.packageName
2613 + ": old package not in system partition");
2614 return false;
2615 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002616 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002617 + " to " + newPkg.packageName
2618 + ": old package still exists");
2619 return false;
2620 }
2621 return true;
2622 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002623
2624 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002625 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002626 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002627
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002628 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2629 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002630 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002631 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2632 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002633 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002634 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002635 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2636 return null;
2637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 mScanningPath = scanFile;
2639 if (pkg == null) {
2640 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2641 return null;
2642 }
2643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2645 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2646 }
2647
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002648 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 synchronized (mPackages) {
2650 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002651 Slog.w(TAG, "*************************************************");
2652 Slog.w(TAG, "Core android package being redefined. Skipping.");
2653 Slog.w(TAG, " file=" + mScanningPath);
2654 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2656 return null;
2657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 // Set up information for our fall-back user intent resolution
2660 // activity.
2661 mPlatformPackage = pkg;
2662 pkg.mVersionCode = mSdkVersion;
2663 mAndroidApplication = pkg.applicationInfo;
2664 mResolveActivity.applicationInfo = mAndroidApplication;
2665 mResolveActivity.name = ResolverActivity.class.getName();
2666 mResolveActivity.packageName = mAndroidApplication.packageName;
2667 mResolveActivity.processName = mAndroidApplication.processName;
2668 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2669 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2670 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2671 mResolveActivity.exported = true;
2672 mResolveActivity.enabled = true;
2673 mResolveInfo.activityInfo = mResolveActivity;
2674 mResolveInfo.priority = 0;
2675 mResolveInfo.preferredOrder = 0;
2676 mResolveInfo.match = 0;
2677 mResolveComponentName = new ComponentName(
2678 mAndroidApplication.packageName, mResolveActivity.name);
2679 }
2680 }
2681
2682 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002683 TAG, "Scanning package " + pkg.packageName);
2684 if (mPackages.containsKey(pkg.packageName)
2685 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002686 Slog.w(TAG, "*************************************************");
2687 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002689 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2691 return null;
2692 }
2693
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002694 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002695 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2696 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 SharedUserSetting suid = null;
2699 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002700
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002701 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2702 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002703 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002704 pkg.mRealPackage = null;
2705 pkg.mAdoptPermissions = null;
2706 }
2707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002708 synchronized (mPackages) {
2709 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002710 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2711 if (mTmpSharedLibraries == null ||
2712 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2713 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2714 }
2715 int num = 0;
2716 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2717 for (int i=0; i<N; i++) {
2718 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002720 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002722 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2724 return null;
2725 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002726 mTmpSharedLibraries[num] = file;
2727 num++;
2728 }
2729 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2730 for (int i=0; i<N; i++) {
2731 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2732 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002733 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002734 + " desires unavailable shared library "
2735 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2736 } else {
2737 mTmpSharedLibraries[num] = file;
2738 num++;
2739 }
2740 }
2741 if (num > 0) {
2742 pkg.usesLibraryFiles = new String[num];
2743 System.arraycopy(mTmpSharedLibraries, 0,
2744 pkg.usesLibraryFiles, 0, num);
2745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002746
Dianne Hackborn49237342009-08-27 20:08:01 -07002747 if (pkg.reqFeatures != null) {
2748 N = pkg.reqFeatures.size();
2749 for (int i=0; i<N; i++) {
2750 FeatureInfo fi = pkg.reqFeatures.get(i);
2751 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2752 // Don't care.
2753 continue;
2754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002755
Dianne Hackborn49237342009-08-27 20:08:01 -07002756 if (fi.name != null) {
2757 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002758 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002759 + " requires unavailable feature "
2760 + fi.name + "; failing!");
2761 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2762 return null;
2763 }
2764 }
2765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 }
2767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if (pkg.mSharedUserId != null) {
2770 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2771 pkg.applicationInfo.flags, true);
2772 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002773 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 + " for shared user failed");
2775 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2776 return null;
2777 }
2778 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2779 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2780 + suid.userId + "): packages=" + suid.packages);
2781 }
2782 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002783
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002784 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002785 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002786 Log.w(TAG, "WAITING FOR DEBUGGER");
2787 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002788 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2789 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002790 }
2791 }
2792
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002793 // Check if we are renaming from an original package name.
2794 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002795 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002796 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002797 // This package may need to be renamed to a previously
2798 // installed name. Let's check on that...
2799 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002800 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002801 // This package had originally been installed as the
2802 // original name, and we have already taken care of
2803 // transitioning to the new one. Just update the new
2804 // one to continue using the old name.
2805 realName = pkg.mRealPackage;
2806 if (!pkg.packageName.equals(renamed)) {
2807 // Callers into this function may have already taken
2808 // care of renaming the package; only do it here if
2809 // it is not already done.
2810 pkg.setPackageName(renamed);
2811 }
2812
Dianne Hackbornc1552392010-03-03 16:19:01 -08002813 } else {
2814 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2815 if ((origPackage=mSettings.peekPackageLP(
2816 pkg.mOriginalPackages.get(i))) != null) {
2817 // We do have the package already installed under its
2818 // original name... should we use it?
2819 if (!verifyPackageUpdate(origPackage, pkg)) {
2820 // New package is not compatible with original.
2821 origPackage = null;
2822 continue;
2823 } else if (origPackage.sharedUser != null) {
2824 // Make sure uid is compatible between packages.
2825 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002826 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002827 + " to " + pkg.packageName + ": old uid "
2828 + origPackage.sharedUser.name
2829 + " differs from " + pkg.mSharedUserId);
2830 origPackage = null;
2831 continue;
2832 }
2833 } else {
2834 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2835 + pkg.packageName + " to old name " + origPackage.name);
2836 }
2837 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002838 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002839 }
2840 }
2841 }
2842
2843 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002844 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002845 + " was transferred to another, but its .apk remains");
2846 }
2847
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002848 // Just create the setting, don't add it yet. For already existing packages
2849 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002850 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 destResourceFile, pkg.applicationInfo.flags, true, false);
2852 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002853 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2855 return null;
2856 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002857
2858 if (pkgSetting.origPackage != null) {
2859 // If we are first transitioning from an original package,
2860 // fix up the new package's name now. We need to do this after
2861 // looking up the package under its new name, so getPackageLP
2862 // can take care of fiddling things correctly.
2863 pkg.setPackageName(origPackage.name);
2864
2865 // File a report about this.
2866 String msg = "New package " + pkgSetting.realName
2867 + " renamed to replace old package " + pkgSetting.name;
2868 reportSettingsProblem(Log.WARN, msg);
2869
2870 // Make a note of it.
2871 mTransferedPackages.add(origPackage.name);
2872
2873 // No longer need to retain this.
2874 pkgSetting.origPackage = null;
2875 }
2876
2877 if (realName != null) {
2878 // Make a note of it.
2879 mTransferedPackages.add(pkg.packageName);
2880 }
2881
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002882 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 pkg.applicationInfo.uid = pkgSetting.userId;
2887 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002888
2889 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002891 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2893 return null;
2894 }
2895 // The signature has changed, but this package is in the system
2896 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002897 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898 // However... if this package is part of a shared user, but it
2899 // doesn't match the signature of the shared user, let's fail.
2900 // What this means is that you can't change the signatures
2901 // associated with an overall shared user, which doesn't seem all
2902 // that unreasonable.
2903 if (pkgSetting.sharedUser != null) {
2904 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2905 pkg.mSignatures, false)) {
2906 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2907 return null;
2908 }
2909 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002910 // File a report about this.
2911 String msg = "System package " + pkg.packageName
2912 + " signature changed; retaining data.";
2913 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002915
The Android Open Source Project10592532009-03-18 17:39:46 -07002916 // Verify that this new package doesn't have any content providers
2917 // that conflict with existing packages. Only do this if the
2918 // package isn't already installed, since we don't want to break
2919 // things that are installed.
2920 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2921 int N = pkg.providers.size();
2922 int i;
2923 for (i=0; i<N; i++) {
2924 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002925 if (p.info.authority != null) {
2926 String names[] = p.info.authority.split(";");
2927 for (int j = 0; j < names.length; j++) {
2928 if (mProviders.containsKey(names[j])) {
2929 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002930 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08002931 " (in package " + pkg.applicationInfo.packageName +
2932 ") is already used by "
2933 + ((other != null && other.getComponentName() != null)
2934 ? other.getComponentName().getPackageName() : "?"));
2935 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2936 return null;
2937 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002938 }
2939 }
2940 }
2941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002944 final String pkgName = pkg.packageName;
2945
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002946 if (pkg.mAdoptPermissions != null) {
2947 // This package wants to adopt ownership of permissions from
2948 // another package.
2949 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2950 String origName = pkg.mAdoptPermissions.get(i);
2951 PackageSetting orig = mSettings.peekPackageLP(origName);
2952 if (orig != null) {
2953 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002954 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002955 + origName + " to " + pkg.packageName);
2956 mSettings.transferPermissions(origName, pkg.packageName);
2957 }
2958 }
2959 }
2960 }
2961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 long scanFileTime = scanFile.lastModified();
2963 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2964 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2965 pkg.applicationInfo.processName = fixProcessName(
2966 pkg.applicationInfo.packageName,
2967 pkg.applicationInfo.processName,
2968 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969
2970 File dataPath;
2971 if (mPlatformPackage == pkg) {
2972 // The system package is special.
2973 dataPath = new File (Environment.getDataDirectory(), "system");
2974 pkg.applicationInfo.dataDir = dataPath.getPath();
2975 } else {
2976 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002977 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002978
2979 boolean uidError = false;
2980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 if (dataPath.exists()) {
2982 mOutPermissions[1] = 0;
2983 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2984 if (mOutPermissions[1] == pkg.applicationInfo.uid
2985 || !Process.supportsProcesses()) {
2986 pkg.applicationInfo.dataDir = dataPath.getPath();
2987 } else {
2988 boolean recovered = false;
2989 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2990 // If this is a system app, we can at least delete its
2991 // current data so the application will still work.
2992 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002993 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002994 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 // Old data gone!
2996 String msg = "System package " + pkg.packageName
2997 + " has changed from uid: "
2998 + mOutPermissions[1] + " to "
2999 + pkg.applicationInfo.uid + "; old data erased";
3000 reportSettingsProblem(Log.WARN, msg);
3001 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003004 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 pkg.applicationInfo.uid);
3006 if (ret == -1) {
3007 // Ack should not happen!
3008 msg = "System package " + pkg.packageName
3009 + " could not have data directory re-created after delete.";
3010 reportSettingsProblem(Log.WARN, msg);
3011 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3012 return null;
3013 }
3014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 if (!recovered) {
3017 mHasSystemUidErrors = true;
3018 }
3019 }
3020 if (!recovered) {
3021 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3022 + pkg.applicationInfo.uid + "/fs_"
3023 + mOutPermissions[1];
3024 String msg = "Package " + pkg.packageName
3025 + " has mismatched uid: "
3026 + mOutPermissions[1] + " on disk, "
3027 + pkg.applicationInfo.uid + " in settings";
3028 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003029 mSettings.mReadMessages.append(msg);
3030 mSettings.mReadMessages.append('\n');
3031 uidError = true;
3032 if (!pkgSetting.uidError) {
3033 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 }
3036 }
3037 }
3038 pkg.applicationInfo.dataDir = dataPath.getPath();
3039 } else {
3040 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3041 Log.v(TAG, "Want this data dir: " + dataPath);
3042 //invoke installer to do the actual installation
3043 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003044 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 pkg.applicationInfo.uid);
3046 if(ret < 0) {
3047 // Error from installer
3048 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3049 return null;
3050 }
3051 } else {
3052 dataPath.mkdirs();
3053 if (dataPath.exists()) {
3054 FileUtils.setPermissions(
3055 dataPath.toString(),
3056 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3057 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3058 }
3059 }
3060 if (dataPath.exists()) {
3061 pkg.applicationInfo.dataDir = dataPath.getPath();
3062 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003063 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 pkg.applicationInfo.dataDir = null;
3065 }
3066 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003067
3068 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 }
3070
3071 // Perform shared library installation and dex validation and
3072 // optimization, if this is not a system app.
3073 if (mInstaller != null) {
3074 String path = scanFile.getPath();
3075 if (scanFileNewer) {
3076 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003077 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3078 if (err != PackageManager.INSTALL_SUCCEEDED) {
3079 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 return null;
3081 }
3082 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003083 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003084
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003085 if ((scanMode&SCAN_NO_DEX) == 0) {
3086 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3088 return null;
3089 }
3090 }
3091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 if (mFactoryTest && pkg.requestedPermissions.contains(
3094 android.Manifest.permission.FACTORY_TEST)) {
3095 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3096 }
3097
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003098 // Request the ActivityManager to kill the process(only for existing packages)
3099 // so that we do not end up in a confused state while the user is still using the older
3100 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003101 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003102 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003103 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003104 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003107 // We don't expect installation to fail beyond this point,
3108 if ((scanMode&SCAN_MONITOR) != 0) {
3109 mAppDirs.put(pkg.mPath, pkg);
3110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003112 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003114 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003115 // Make sure we don't accidentally delete its data.
3116 mSettings.mPackagesToBeCleaned.remove(pkgName);
3117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 int N = pkg.providers.size();
3119 StringBuilder r = null;
3120 int i;
3121 for (i=0; i<N; i++) {
3122 PackageParser.Provider p = pkg.providers.get(i);
3123 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3124 p.info.processName, pkg.applicationInfo.uid);
3125 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3126 p.info.name), p);
3127 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003128 if (p.info.authority != null) {
3129 String names[] = p.info.authority.split(";");
3130 p.info.authority = null;
3131 for (int j = 0; j < names.length; j++) {
3132 if (j == 1 && p.syncable) {
3133 // We only want the first authority for a provider to possibly be
3134 // syncable, so if we already added this provider using a different
3135 // authority clear the syncable flag. We copy the provider before
3136 // changing it because the mProviders object contains a reference
3137 // to a provider that we don't want to change.
3138 // Only do this for the second authority since the resulting provider
3139 // object can be the same for all future authorities for this provider.
3140 p = new PackageParser.Provider(p);
3141 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003143 if (!mProviders.containsKey(names[j])) {
3144 mProviders.put(names[j], p);
3145 if (p.info.authority == null) {
3146 p.info.authority = names[j];
3147 } else {
3148 p.info.authority = p.info.authority + ";" + names[j];
3149 }
3150 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3151 Log.d(TAG, "Registered content provider: " + names[j] +
3152 ", className = " + p.info.name +
3153 ", isSyncable = " + p.info.isSyncable);
3154 } else {
3155 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003156 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003157 " (in package " + pkg.applicationInfo.packageName +
3158 "): name already used by "
3159 + ((other != null && other.getComponentName() != null)
3160 ? other.getComponentName().getPackageName() : "?"));
3161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 }
3163 }
3164 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3165 if (r == null) {
3166 r = new StringBuilder(256);
3167 } else {
3168 r.append(' ');
3169 }
3170 r.append(p.info.name);
3171 }
3172 }
3173 if (r != null) {
3174 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 N = pkg.services.size();
3178 r = null;
3179 for (i=0; i<N; i++) {
3180 PackageParser.Service s = pkg.services.get(i);
3181 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3182 s.info.processName, pkg.applicationInfo.uid);
3183 mServices.addService(s);
3184 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3185 if (r == null) {
3186 r = new StringBuilder(256);
3187 } else {
3188 r.append(' ');
3189 }
3190 r.append(s.info.name);
3191 }
3192 }
3193 if (r != null) {
3194 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 N = pkg.receivers.size();
3198 r = null;
3199 for (i=0; i<N; i++) {
3200 PackageParser.Activity a = pkg.receivers.get(i);
3201 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3202 a.info.processName, pkg.applicationInfo.uid);
3203 mReceivers.addActivity(a, "receiver");
3204 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3205 if (r == null) {
3206 r = new StringBuilder(256);
3207 } else {
3208 r.append(' ');
3209 }
3210 r.append(a.info.name);
3211 }
3212 }
3213 if (r != null) {
3214 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 N = pkg.activities.size();
3218 r = null;
3219 for (i=0; i<N; i++) {
3220 PackageParser.Activity a = pkg.activities.get(i);
3221 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3222 a.info.processName, pkg.applicationInfo.uid);
3223 mActivities.addActivity(a, "activity");
3224 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3225 if (r == null) {
3226 r = new StringBuilder(256);
3227 } else {
3228 r.append(' ');
3229 }
3230 r.append(a.info.name);
3231 }
3232 }
3233 if (r != null) {
3234 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237 N = pkg.permissionGroups.size();
3238 r = null;
3239 for (i=0; i<N; i++) {
3240 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3241 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3242 if (cur == null) {
3243 mPermissionGroups.put(pg.info.name, pg);
3244 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3245 if (r == null) {
3246 r = new StringBuilder(256);
3247 } else {
3248 r.append(' ');
3249 }
3250 r.append(pg.info.name);
3251 }
3252 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003253 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 + pg.info.packageName + " ignored: original from "
3255 + cur.info.packageName);
3256 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3257 if (r == null) {
3258 r = new StringBuilder(256);
3259 } else {
3260 r.append(' ');
3261 }
3262 r.append("DUP:");
3263 r.append(pg.info.name);
3264 }
3265 }
3266 }
3267 if (r != null) {
3268 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3269 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 N = pkg.permissions.size();
3272 r = null;
3273 for (i=0; i<N; i++) {
3274 PackageParser.Permission p = pkg.permissions.get(i);
3275 HashMap<String, BasePermission> permissionMap =
3276 p.tree ? mSettings.mPermissionTrees
3277 : mSettings.mPermissions;
3278 p.group = mPermissionGroups.get(p.info.group);
3279 if (p.info.group == null || p.group != null) {
3280 BasePermission bp = permissionMap.get(p.info.name);
3281 if (bp == null) {
3282 bp = new BasePermission(p.info.name, p.info.packageName,
3283 BasePermission.TYPE_NORMAL);
3284 permissionMap.put(p.info.name, bp);
3285 }
3286 if (bp.perm == null) {
3287 if (bp.sourcePackage == null
3288 || bp.sourcePackage.equals(p.info.packageName)) {
3289 BasePermission tree = findPermissionTreeLP(p.info.name);
3290 if (tree == null
3291 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003292 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 bp.perm = p;
3294 bp.uid = pkg.applicationInfo.uid;
3295 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3296 if (r == null) {
3297 r = new StringBuilder(256);
3298 } else {
3299 r.append(' ');
3300 }
3301 r.append(p.info.name);
3302 }
3303 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003304 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 + p.info.packageName + " ignored: base tree "
3306 + tree.name + " is from package "
3307 + tree.sourcePackage);
3308 }
3309 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003310 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 + p.info.packageName + " ignored: original from "
3312 + bp.sourcePackage);
3313 }
3314 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3315 if (r == null) {
3316 r = new StringBuilder(256);
3317 } else {
3318 r.append(' ');
3319 }
3320 r.append("DUP:");
3321 r.append(p.info.name);
3322 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003323 if (bp.perm == p) {
3324 bp.protectionLevel = p.info.protectionLevel;
3325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003327 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 + p.info.packageName + " ignored: no group "
3329 + p.group);
3330 }
3331 }
3332 if (r != null) {
3333 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 N = pkg.instrumentation.size();
3337 r = null;
3338 for (i=0; i<N; i++) {
3339 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3340 a.info.packageName = pkg.applicationInfo.packageName;
3341 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3342 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3343 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003344 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3346 if (r == null) {
3347 r = new StringBuilder(256);
3348 } else {
3349 r.append(' ');
3350 }
3351 r.append(a.info.name);
3352 }
3353 }
3354 if (r != null) {
3355 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003357
Dianne Hackborn854060af2009-07-09 18:14:31 -07003358 if (pkg.protectedBroadcasts != null) {
3359 N = pkg.protectedBroadcasts.size();
3360 for (i=0; i<N; i++) {
3361 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3362 }
3363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 pkgSetting.setTimeStamp(scanFileTime);
3366 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 return pkg;
3369 }
3370
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003371 private void killApplication(String pkgName, int uid) {
3372 // Request the ActivityManager to kill the process(only for existing packages)
3373 // so that we do not end up in a confused state while the user is still using the older
3374 // version of the application while the new one gets installed.
3375 IActivityManager am = ActivityManagerNative.getDefault();
3376 if (am != null) {
3377 try {
3378 am.killApplicationWithUid(pkgName, uid);
3379 } catch (RemoteException e) {
3380 }
3381 }
3382 }
3383
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003384 // The following constants are returned by cachePackageSharedLibsForAbiLI
3385 // to indicate if native shared libraries were found in the package.
3386 // Values are:
3387 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3388 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3389 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3390 // in package (and not installed)
3391 //
3392 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3393 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3394 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003396 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3397 // and automatically copy them to /data/data/<appname>/lib if present.
3398 //
3399 // NOTE: this method may throw an IOException if the library cannot
3400 // be copied to its final destination, e.g. if there isn't enough
3401 // room left on the data partition, or a ZipException if the package
3402 // file is malformed.
3403 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003404 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3405 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003406 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3407 final String apkLib = "lib/";
3408 final int apkLibLen = apkLib.length();
3409 final int cpuAbiLen = cpuAbi.length();
3410 final String libPrefix = "lib";
3411 final int libPrefixLen = libPrefix.length();
3412 final String libSuffix = ".so";
3413 final int libSuffixLen = libSuffix.length();
3414 boolean hasNativeLibraries = false;
3415 boolean installedNativeLibraries = false;
3416
3417 // the minimum length of a valid native shared library of the form
3418 // lib/<something>/lib<name>.so.
3419 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3420
3421 ZipFile zipFile = new ZipFile(scanFile);
3422 Enumeration<ZipEntry> entries =
3423 (Enumeration<ZipEntry>) zipFile.entries();
3424
3425 while (entries.hasMoreElements()) {
3426 ZipEntry entry = entries.nextElement();
3427 // skip directories
3428 if (entry.isDirectory()) {
3429 continue;
3430 }
3431 String entryName = entry.getName();
3432
3433 // check that the entry looks like lib/<something>/lib<name>.so
3434 // here, but don't check the ABI just yet.
3435 //
3436 // - must be sufficiently long
3437 // - must end with libSuffix, i.e. ".so"
3438 // - must start with apkLib, i.e. "lib/"
3439 if (entryName.length() < minEntryLen ||
3440 !entryName.endsWith(libSuffix) ||
3441 !entryName.startsWith(apkLib) ) {
3442 continue;
3443 }
3444
3445 // file name must start with libPrefix, i.e. "lib"
3446 int lastSlash = entryName.lastIndexOf('/');
3447
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003448 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003449 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3450 continue;
3451 }
3452
3453 hasNativeLibraries = true;
3454
3455 // check the cpuAbi now, between lib/ and /lib<name>.so
3456 //
3457 if (lastSlash != apkLibLen + cpuAbiLen ||
3458 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3459 continue;
3460
3461 // extract the library file name, ensure it doesn't contain
3462 // weird characters. we're guaranteed here that it doesn't contain
3463 // a directory separator though.
3464 String libFileName = entryName.substring(lastSlash+1);
3465 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3466 continue;
3467 }
3468
3469 installedNativeLibraries = true;
3470
3471 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3472 File.separator + libFileName;
3473 File sharedLibraryFile = new File(sharedLibraryFilePath);
3474 if (! sharedLibraryFile.exists() ||
3475 sharedLibraryFile.length() != entry.getSize() ||
3476 sharedLibraryFile.lastModified() != entry.getTime()) {
3477 if (Config.LOGD) {
3478 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003480 if (mInstaller == null) {
3481 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003482 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003483 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003484 sharedLibraryFile);
3485 }
3486 }
3487 if (!hasNativeLibraries)
3488 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3489
3490 if (!installedNativeLibraries)
3491 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3492
3493 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3494 }
3495
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003496 // Find the gdbserver executable program in a package at
3497 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3498 //
3499 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3500 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3501 //
3502 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3503 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3504 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3505 final String GDBSERVER = "gdbserver";
3506 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3507
3508 ZipFile zipFile = new ZipFile(scanFile);
3509 Enumeration<ZipEntry> entries =
3510 (Enumeration<ZipEntry>) zipFile.entries();
3511
3512 while (entries.hasMoreElements()) {
3513 ZipEntry entry = entries.nextElement();
3514 // skip directories
3515 if (entry.isDirectory()) {
3516 continue;
3517 }
3518 String entryName = entry.getName();
3519
3520 if (!entryName.equals(apkGdbServerPath)) {
3521 continue;
3522 }
3523
3524 String installGdbServerPath = installGdbServerDir.getPath() +
3525 "/" + GDBSERVER;
3526 File installGdbServerFile = new File(installGdbServerPath);
3527 if (! installGdbServerFile.exists() ||
3528 installGdbServerFile.length() != entry.getSize() ||
3529 installGdbServerFile.lastModified() != entry.getTime()) {
3530 if (Config.LOGD) {
3531 Log.d(TAG, "Caching gdbserver " + entry.getName());
3532 }
3533 if (mInstaller == null) {
3534 installGdbServerDir.mkdir();
3535 }
3536 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3537 installGdbServerFile);
3538 }
3539 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3540 }
3541 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3542 }
3543
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003544 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3545 // and copy them to /data/data/<appname>/lib.
3546 //
3547 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3548 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3549 // one if ro.product.cpu.abi2 is defined.
3550 //
3551 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3552 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003553 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003554 try {
3555 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3556
3557 // some architectures are capable of supporting several CPU ABIs
3558 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3559 // this is indicated by the definition of the ro.product.cpu.abi2
3560 // system property.
3561 //
3562 // only scan the package twice in case of ABI mismatch
3563 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003564 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003565 if (cpuAbi2 != null) {
3566 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003568
3569 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003570 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003571 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003573
3574 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3575 cpuAbi = cpuAbi2;
3576 }
3577 }
3578
3579 // for debuggable packages, also extract gdbserver from lib/<abi>
3580 // into /data/data/<appname>/lib too.
3581 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3582 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3583 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3584 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3585 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003588 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003589 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003590 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003591 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003592 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003593 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003595 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 }
3597
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003598 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003600 File binaryDir,
3601 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 InputStream inputStream = zipFile.getInputStream(entry);
3603 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003604 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003605 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003606 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 // now need to be left as world readable and owned by the system.
3608 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3609 ! tempFile.setLastModified(entry.getTime()) ||
3610 FileUtils.setPermissions(tempFilePath,
3611 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003612 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003614 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 // Failed to properly write file.
3616 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003617 throw new IOException("Couldn't create cached binary "
3618 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 }
3620 } finally {
3621 inputStream.close();
3622 }
3623 }
3624
3625 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3626 if (chatty && Config.LOGD) Log.d(
3627 TAG, "Removing package " + pkg.applicationInfo.packageName );
3628
3629 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 mPackages.remove(pkg.applicationInfo.packageName);
3633 if (pkg.mPath != null) {
3634 mAppDirs.remove(pkg.mPath);
3635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 PackageSetting ps = (PackageSetting)pkg.mExtras;
3638 if (ps != null && ps.sharedUser != null) {
3639 // XXX don't do this until the data is removed.
3640 if (false) {
3641 ps.sharedUser.packages.remove(ps);
3642 if (ps.sharedUser.packages.size() == 0) {
3643 // Remove.
3644 }
3645 }
3646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 int N = pkg.providers.size();
3649 StringBuilder r = null;
3650 int i;
3651 for (i=0; i<N; i++) {
3652 PackageParser.Provider p = pkg.providers.get(i);
3653 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3654 p.info.name));
3655 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 /* The is another ContentProvider with this authority when
3658 * this app was installed so this authority is null,
3659 * Ignore it as we don't have to unregister the provider.
3660 */
3661 continue;
3662 }
3663 String names[] = p.info.authority.split(";");
3664 for (int j = 0; j < names.length; j++) {
3665 if (mProviders.get(names[j]) == p) {
3666 mProviders.remove(names[j]);
3667 if (chatty && Config.LOGD) Log.d(
3668 TAG, "Unregistered content provider: " + names[j] +
3669 ", className = " + p.info.name +
3670 ", isSyncable = " + p.info.isSyncable);
3671 }
3672 }
3673 if (chatty) {
3674 if (r == null) {
3675 r = new StringBuilder(256);
3676 } else {
3677 r.append(' ');
3678 }
3679 r.append(p.info.name);
3680 }
3681 }
3682 if (r != null) {
3683 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 N = pkg.services.size();
3687 r = null;
3688 for (i=0; i<N; i++) {
3689 PackageParser.Service s = pkg.services.get(i);
3690 mServices.removeService(s);
3691 if (chatty) {
3692 if (r == null) {
3693 r = new StringBuilder(256);
3694 } else {
3695 r.append(' ');
3696 }
3697 r.append(s.info.name);
3698 }
3699 }
3700 if (r != null) {
3701 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 N = pkg.receivers.size();
3705 r = null;
3706 for (i=0; i<N; i++) {
3707 PackageParser.Activity a = pkg.receivers.get(i);
3708 mReceivers.removeActivity(a, "receiver");
3709 if (chatty) {
3710 if (r == null) {
3711 r = new StringBuilder(256);
3712 } else {
3713 r.append(' ');
3714 }
3715 r.append(a.info.name);
3716 }
3717 }
3718 if (r != null) {
3719 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 N = pkg.activities.size();
3723 r = null;
3724 for (i=0; i<N; i++) {
3725 PackageParser.Activity a = pkg.activities.get(i);
3726 mActivities.removeActivity(a, "activity");
3727 if (chatty) {
3728 if (r == null) {
3729 r = new StringBuilder(256);
3730 } else {
3731 r.append(' ');
3732 }
3733 r.append(a.info.name);
3734 }
3735 }
3736 if (r != null) {
3737 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 N = pkg.permissions.size();
3741 r = null;
3742 for (i=0; i<N; i++) {
3743 PackageParser.Permission p = pkg.permissions.get(i);
3744 boolean tree = false;
3745 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3746 if (bp == null) {
3747 tree = true;
3748 bp = mSettings.mPermissionTrees.get(p.info.name);
3749 }
3750 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003751 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 if (chatty) {
3753 if (r == null) {
3754 r = new StringBuilder(256);
3755 } else {
3756 r.append(' ');
3757 }
3758 r.append(p.info.name);
3759 }
3760 }
3761 }
3762 if (r != null) {
3763 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003766 N = pkg.instrumentation.size();
3767 r = null;
3768 for (i=0; i<N; i++) {
3769 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003770 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 if (chatty) {
3772 if (r == null) {
3773 r = new StringBuilder(256);
3774 } else {
3775 r.append(' ');
3776 }
3777 r.append(a.info.name);
3778 }
3779 }
3780 if (r != null) {
3781 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3782 }
3783 }
3784 }
3785
3786 private static final boolean isPackageFilename(String name) {
3787 return name != null && name.endsWith(".apk");
3788 }
3789
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003790 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3791 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3792 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3793 return true;
3794 }
3795 }
3796 return false;
3797 }
3798
3799 private void updatePermissionsLP(String changingPkg,
3800 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 // Make sure there are no dangling permission trees.
3802 Iterator<BasePermission> it = mSettings.mPermissionTrees
3803 .values().iterator();
3804 while (it.hasNext()) {
3805 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003806 if (bp.packageSetting == null) {
3807 // We may not yet have parsed the package, so just see if
3808 // we still know about its settings.
3809 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3810 }
3811 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003812 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 + " from package " + bp.sourcePackage);
3814 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003815 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3816 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3817 Slog.i(TAG, "Removing old permission tree: " + bp.name
3818 + " from package " + bp.sourcePackage);
3819 grantPermissions = true;
3820 it.remove();
3821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 }
3823 }
3824
3825 // Make sure all dynamic permissions have been assigned to a package,
3826 // and make sure there are no dangling permissions.
3827 it = mSettings.mPermissions.values().iterator();
3828 while (it.hasNext()) {
3829 BasePermission bp = it.next();
3830 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3831 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3832 + bp.name + " pkg=" + bp.sourcePackage
3833 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003834 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 BasePermission tree = findPermissionTreeLP(bp.name);
3836 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003837 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 bp.perm = new PackageParser.Permission(tree.perm.owner,
3839 new PermissionInfo(bp.pendingInfo));
3840 bp.perm.info.packageName = tree.perm.info.packageName;
3841 bp.perm.info.name = bp.name;
3842 bp.uid = tree.uid;
3843 }
3844 }
3845 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 if (bp.packageSetting == null) {
3847 // We may not yet have parsed the package, so just see if
3848 // we still know about its settings.
3849 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3850 }
3851 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003852 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 + " from package " + bp.sourcePackage);
3854 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003855 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3856 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3857 Slog.i(TAG, "Removing old permission: " + bp.name
3858 + " from package " + bp.sourcePackage);
3859 grantPermissions = true;
3860 it.remove();
3861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 }
3863 }
3864
3865 // Now update the permissions for all packages, in particular
3866 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 if (grantPermissions) {
3868 for (PackageParser.Package pkg : mPackages.values()) {
3869 if (pkg != pkgInfo) {
3870 grantPermissionsLP(pkg, false);
3871 }
3872 }
3873 }
3874
3875 if (pkgInfo != null) {
3876 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 }
3878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3881 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3882 if (ps == null) {
3883 return;
3884 }
3885 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 if (replace) {
3889 ps.permissionsFixed = false;
3890 if (gp == ps) {
3891 gp.grantedPermissions.clear();
3892 gp.gids = mGlobalGids;
3893 }
3894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 if (gp.gids == null) {
3897 gp.gids = mGlobalGids;
3898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 final int N = pkg.requestedPermissions.size();
3901 for (int i=0; i<N; i++) {
3902 String name = pkg.requestedPermissions.get(i);
3903 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 if (false) {
3905 if (gp != ps) {
3906 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003907 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003910 if (bp != null && bp.packageSetting != null) {
3911 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003913 boolean allowedSig = false;
3914 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3915 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003917 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3918 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3919 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003921 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003923 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3925 // For updated system applications, the signatureOrSystem permission
3926 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003927 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3929 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3930 if(sysPs.grantedPermissions.contains(perm)) {
3931 allowed = true;
3932 } else {
3933 allowed = false;
3934 }
3935 } else {
3936 allowed = true;
3937 }
3938 }
3939 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003940 if (allowed) {
3941 allowedSig = true;
3942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 } else {
3944 allowed = false;
3945 }
3946 if (false) {
3947 if (gp != ps) {
3948 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3949 }
3950 }
3951 if (allowed) {
3952 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3953 && ps.permissionsFixed) {
3954 // If this is an existing, non-system package, then
3955 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003956 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003958 // Except... if this is a permission that was added
3959 // to the platform (note: need to only do this when
3960 // updating the platform).
3961 final int NP = PackageParser.NEW_PERMISSIONS.length;
3962 for (int ip=0; ip<NP; ip++) {
3963 final PackageParser.NewPermissionInfo npi
3964 = PackageParser.NEW_PERMISSIONS[ip];
3965 if (npi.name.equals(perm)
3966 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3967 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003968 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003969 + pkg.packageName);
3970 break;
3971 }
3972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 }
3974 }
3975 if (allowed) {
3976 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003977 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 gp.grantedPermissions.add(perm);
3979 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003980 } else if (!ps.haveGids) {
3981 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 }
3983 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003984 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 + " to package " + pkg.packageName
3986 + " because it was previously installed without");
3987 }
3988 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003989 if (gp.grantedPermissions.remove(perm)) {
3990 changedPermission = true;
3991 gp.gids = removeInts(gp.gids, bp.gids);
3992 Slog.i(TAG, "Un-granting permission " + perm
3993 + " from package " + pkg.packageName
3994 + " (protectionLevel=" + bp.protectionLevel
3995 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3996 + ")");
3997 } else {
3998 Slog.w(TAG, "Not granting permission " + perm
3999 + " to package " + pkg.packageName
4000 + " (protectionLevel=" + bp.protectionLevel
4001 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4002 + ")");
4003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 }
4005 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004006 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 + " in package " + pkg.packageName);
4008 }
4009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004010
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004011 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004012 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4013 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 // This is the first that we have heard about this package, so the
4015 // permissions we have now selected are fixed until explicitly
4016 // changed.
4017 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004019 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 private final class ActivityIntentResolver
4023 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004024 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004026 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 }
4028
Mihai Preda074edef2009-05-18 17:13:31 +02004029 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004031 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4033 }
4034
Mihai Predaeae850c2009-05-13 10:13:48 +02004035 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4036 ArrayList<PackageParser.Activity> packageActivities) {
4037 if (packageActivities == null) {
4038 return null;
4039 }
4040 mFlags = flags;
4041 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4042 int N = packageActivities.size();
4043 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4044 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004045
4046 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004047 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004048 intentFilters = packageActivities.get(i).intents;
4049 if (intentFilters != null && intentFilters.size() > 0) {
4050 listCut.add(intentFilters);
4051 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004052 }
4053 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4054 }
4055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004057 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 if (SHOW_INFO || Config.LOGV) Log.v(
4059 TAG, " " + type + " " +
4060 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4061 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4062 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004063 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4065 if (SHOW_INFO || Config.LOGV) {
4066 Log.v(TAG, " IntentFilter:");
4067 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4068 }
4069 if (!intent.debugCheck()) {
4070 Log.w(TAG, "==> For Activity " + a.info.name);
4071 }
4072 addFilter(intent);
4073 }
4074 }
4075
4076 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004077 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 if (SHOW_INFO || Config.LOGV) Log.v(
4079 TAG, " " + type + " " +
4080 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4081 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4082 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004083 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4085 if (SHOW_INFO || Config.LOGV) {
4086 Log.v(TAG, " IntentFilter:");
4087 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4088 }
4089 removeFilter(intent);
4090 }
4091 }
4092
4093 @Override
4094 protected boolean allowFilterResult(
4095 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4096 ActivityInfo filterAi = filter.activity.info;
4097 for (int i=dest.size()-1; i>=0; i--) {
4098 ActivityInfo destAi = dest.get(i).activityInfo;
4099 if (destAi.name == filterAi.name
4100 && destAi.packageName == filterAi.packageName) {
4101 return false;
4102 }
4103 }
4104 return true;
4105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004108 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4109 return info.activity.owner.packageName;
4110 }
4111
4112 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4114 int match) {
4115 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4116 return null;
4117 }
4118 final PackageParser.Activity activity = info.activity;
4119 if (mSafeMode && (activity.info.applicationInfo.flags
4120 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4121 return null;
4122 }
4123 final ResolveInfo res = new ResolveInfo();
4124 res.activityInfo = PackageParser.generateActivityInfo(activity,
4125 mFlags);
4126 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4127 res.filter = info;
4128 }
4129 res.priority = info.getPriority();
4130 res.preferredOrder = activity.owner.mPreferredOrder;
4131 //System.out.println("Result: " + res.activityInfo.className +
4132 // " = " + res.priority);
4133 res.match = match;
4134 res.isDefault = info.hasDefault;
4135 res.labelRes = info.labelRes;
4136 res.nonLocalizedLabel = info.nonLocalizedLabel;
4137 res.icon = info.icon;
4138 return res;
4139 }
4140
4141 @Override
4142 protected void sortResults(List<ResolveInfo> results) {
4143 Collections.sort(results, mResolvePrioritySorter);
4144 }
4145
4146 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004147 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004149 out.print(prefix); out.print(
4150 Integer.toHexString(System.identityHashCode(filter.activity)));
4151 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004152 out.print(filter.activity.getComponentShortName());
4153 out.print(" filter ");
4154 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156
4157// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4158// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4159// final List<ResolveInfo> retList = Lists.newArrayList();
4160// while (i.hasNext()) {
4161// final ResolveInfo resolveInfo = i.next();
4162// if (isEnabledLP(resolveInfo.activityInfo)) {
4163// retList.add(resolveInfo);
4164// }
4165// }
4166// return retList;
4167// }
4168
4169 // Keys are String (activity class name), values are Activity.
4170 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4171 = new HashMap<ComponentName, PackageParser.Activity>();
4172 private int mFlags;
4173 }
4174
4175 private final class ServiceIntentResolver
4176 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004177 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004179 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 }
4181
Mihai Preda074edef2009-05-18 17:13:31 +02004182 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004184 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4186 }
4187
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004188 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4189 ArrayList<PackageParser.Service> packageServices) {
4190 if (packageServices == null) {
4191 return null;
4192 }
4193 mFlags = flags;
4194 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4195 int N = packageServices.size();
4196 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4197 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4198
4199 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4200 for (int i = 0; i < N; ++i) {
4201 intentFilters = packageServices.get(i).intents;
4202 if (intentFilters != null && intentFilters.size() > 0) {
4203 listCut.add(intentFilters);
4204 }
4205 }
4206 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4207 }
4208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004210 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 if (SHOW_INFO || Config.LOGV) Log.v(
4212 TAG, " " + (s.info.nonLocalizedLabel != null
4213 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4214 if (SHOW_INFO || Config.LOGV) Log.v(
4215 TAG, " Class=" + s.info.name);
4216 int NI = s.intents.size();
4217 int j;
4218 for (j=0; j<NI; j++) {
4219 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4220 if (SHOW_INFO || Config.LOGV) {
4221 Log.v(TAG, " IntentFilter:");
4222 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4223 }
4224 if (!intent.debugCheck()) {
4225 Log.w(TAG, "==> For Service " + s.info.name);
4226 }
4227 addFilter(intent);
4228 }
4229 }
4230
4231 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004232 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 if (SHOW_INFO || Config.LOGV) Log.v(
4234 TAG, " " + (s.info.nonLocalizedLabel != null
4235 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4236 if (SHOW_INFO || Config.LOGV) Log.v(
4237 TAG, " Class=" + s.info.name);
4238 int NI = s.intents.size();
4239 int j;
4240 for (j=0; j<NI; j++) {
4241 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4242 if (SHOW_INFO || Config.LOGV) {
4243 Log.v(TAG, " IntentFilter:");
4244 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4245 }
4246 removeFilter(intent);
4247 }
4248 }
4249
4250 @Override
4251 protected boolean allowFilterResult(
4252 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4253 ServiceInfo filterSi = filter.service.info;
4254 for (int i=dest.size()-1; i>=0; i--) {
4255 ServiceInfo destAi = dest.get(i).serviceInfo;
4256 if (destAi.name == filterSi.name
4257 && destAi.packageName == filterSi.packageName) {
4258 return false;
4259 }
4260 }
4261 return true;
4262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004265 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4266 return info.service.owner.packageName;
4267 }
4268
4269 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4271 int match) {
4272 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4273 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4274 return null;
4275 }
4276 final PackageParser.Service service = info.service;
4277 if (mSafeMode && (service.info.applicationInfo.flags
4278 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4279 return null;
4280 }
4281 final ResolveInfo res = new ResolveInfo();
4282 res.serviceInfo = PackageParser.generateServiceInfo(service,
4283 mFlags);
4284 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4285 res.filter = filter;
4286 }
4287 res.priority = info.getPriority();
4288 res.preferredOrder = service.owner.mPreferredOrder;
4289 //System.out.println("Result: " + res.activityInfo.className +
4290 // " = " + res.priority);
4291 res.match = match;
4292 res.isDefault = info.hasDefault;
4293 res.labelRes = info.labelRes;
4294 res.nonLocalizedLabel = info.nonLocalizedLabel;
4295 res.icon = info.icon;
4296 return res;
4297 }
4298
4299 @Override
4300 protected void sortResults(List<ResolveInfo> results) {
4301 Collections.sort(results, mResolvePrioritySorter);
4302 }
4303
4304 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004305 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004307 out.print(prefix); out.print(
4308 Integer.toHexString(System.identityHashCode(filter.service)));
4309 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004310 out.print(filter.service.getComponentShortName());
4311 out.print(" filter ");
4312 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 }
4314
4315// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4316// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4317// final List<ResolveInfo> retList = Lists.newArrayList();
4318// while (i.hasNext()) {
4319// final ResolveInfo resolveInfo = (ResolveInfo) i;
4320// if (isEnabledLP(resolveInfo.serviceInfo)) {
4321// retList.add(resolveInfo);
4322// }
4323// }
4324// return retList;
4325// }
4326
4327 // Keys are String (activity class name), values are Activity.
4328 private final HashMap<ComponentName, PackageParser.Service> mServices
4329 = new HashMap<ComponentName, PackageParser.Service>();
4330 private int mFlags;
4331 };
4332
4333 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4334 new Comparator<ResolveInfo>() {
4335 public int compare(ResolveInfo r1, ResolveInfo r2) {
4336 int v1 = r1.priority;
4337 int v2 = r2.priority;
4338 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4339 if (v1 != v2) {
4340 return (v1 > v2) ? -1 : 1;
4341 }
4342 v1 = r1.preferredOrder;
4343 v2 = r2.preferredOrder;
4344 if (v1 != v2) {
4345 return (v1 > v2) ? -1 : 1;
4346 }
4347 if (r1.isDefault != r2.isDefault) {
4348 return r1.isDefault ? -1 : 1;
4349 }
4350 v1 = r1.match;
4351 v2 = r2.match;
4352 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4353 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4354 }
4355 };
4356
4357 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4358 new Comparator<ProviderInfo>() {
4359 public int compare(ProviderInfo p1, ProviderInfo p2) {
4360 final int v1 = p1.initOrder;
4361 final int v2 = p2.initOrder;
4362 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4363 }
4364 };
4365
4366 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4367 IActivityManager am = ActivityManagerNative.getDefault();
4368 if (am != null) {
4369 try {
4370 final Intent intent = new Intent(action,
4371 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4372 if (extras != null) {
4373 intent.putExtras(extras);
4374 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004375 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 am.broadcastIntent(
4377 null, intent,
4378 null, null, 0, null, null, null, false, false);
4379 } catch (RemoteException ex) {
4380 }
4381 }
4382 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004383
4384 public String nextPackageToClean(String lastPackage) {
4385 synchronized (mPackages) {
4386 if (!mMediaMounted) {
4387 // If the external storage is no longer mounted at this point,
4388 // the caller may not have been able to delete all of this
4389 // packages files and can not delete any more. Bail.
4390 return null;
4391 }
4392 if (lastPackage != null) {
4393 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4394 }
4395 return mSettings.mPackagesToBeCleaned.size() > 0
4396 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4397 }
4398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004400 void schedulePackageCleaning(String packageName) {
4401 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4402 }
4403
4404 void startCleaningPackages() {
4405 synchronized (mPackages) {
4406 if (!mMediaMounted) {
4407 return;
4408 }
4409 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4410 return;
4411 }
4412 }
4413 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4414 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4415 IActivityManager am = ActivityManagerNative.getDefault();
4416 if (am != null) {
4417 try {
4418 am.startService(null, intent, null);
4419 } catch (RemoteException e) {
4420 }
4421 }
4422 }
4423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 private final class AppDirObserver extends FileObserver {
4425 public AppDirObserver(String path, int mask, boolean isrom) {
4426 super(path, mask);
4427 mRootDir = path;
4428 mIsRom = isrom;
4429 }
4430
4431 public void onEvent(int event, String path) {
4432 String removedPackage = null;
4433 int removedUid = -1;
4434 String addedPackage = null;
4435 int addedUid = -1;
4436
4437 synchronized (mInstallLock) {
4438 String fullPathStr = null;
4439 File fullPath = null;
4440 if (path != null) {
4441 fullPath = new File(mRootDir, path);
4442 fullPathStr = fullPath.getPath();
4443 }
4444
4445 if (Config.LOGV) Log.v(
4446 TAG, "File " + fullPathStr + " changed: "
4447 + Integer.toHexString(event));
4448
4449 if (!isPackageFilename(path)) {
4450 if (Config.LOGV) Log.v(
4451 TAG, "Ignoring change of non-package file: " + fullPathStr);
4452 return;
4453 }
4454
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004455 // Ignore packages that are being installed or
4456 // have just been installed.
4457 if (ignoreCodePath(fullPathStr)) {
4458 return;
4459 }
4460 PackageParser.Package p = null;
4461 synchronized (mPackages) {
4462 p = mAppDirs.get(fullPathStr);
4463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004465 if (p != null) {
4466 removePackageLI(p, true);
4467 removedPackage = p.applicationInfo.packageName;
4468 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 }
4470 }
4471
4472 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004474 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004475 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4476 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 PackageParser.PARSE_CHATTY |
4478 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004479 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 if (p != null) {
4481 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004482 updatePermissionsLP(p.packageName, p,
4483 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 }
4485 addedPackage = p.applicationInfo.packageName;
4486 addedUid = p.applicationInfo.uid;
4487 }
4488 }
4489 }
4490
4491 synchronized (mPackages) {
4492 mSettings.writeLP();
4493 }
4494 }
4495
4496 if (removedPackage != null) {
4497 Bundle extras = new Bundle(1);
4498 extras.putInt(Intent.EXTRA_UID, removedUid);
4499 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4500 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4501 }
4502 if (addedPackage != null) {
4503 Bundle extras = new Bundle(1);
4504 extras.putInt(Intent.EXTRA_UID, addedUid);
4505 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4506 }
4507 }
4508
4509 private final String mRootDir;
4510 private final boolean mIsRom;
4511 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 /* Called when a downloaded package installation has been confirmed by the user */
4514 public void installPackage(
4515 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004516 installPackage(packageURI, observer, flags, null);
4517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004518
Jacek Surazski65e13172009-04-28 15:26:38 +02004519 /* Called when a downloaded package installation has been confirmed by the user */
4520 public void installPackage(
4521 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4522 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 mContext.enforceCallingOrSelfPermission(
4524 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004525
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004526 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004527 msg.obj = new InstallParams(packageURI, observer, flags,
4528 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004529 mHandler.sendMessage(msg);
4530 }
4531
Christopher Tate1bb69062010-02-19 17:02:12 -08004532 public void finishPackageInstall(int token) {
4533 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4534 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4535 mHandler.sendMessage(msg);
4536 }
4537
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004538 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 // Queue up an async operation since the package installation may take a little while.
4540 mHandler.post(new Runnable() {
4541 public void run() {
4542 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004543 // Result object to be returned
4544 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004545 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004546 res.uid = -1;
4547 res.pkg = null;
4548 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004549 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004550 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004551 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004552 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004553 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004554 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004556
4557 // A restore should be performed at this point if (a) the install
4558 // succeeded, (b) the operation is not an update, and (c) the new
4559 // package has a backupAgent defined.
4560 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004561 boolean doRestore = (!update
4562 && res.pkg != null
4563 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004564
4565 // Set up the post-install work request bookkeeping. This will be used
4566 // and cleaned up by the post-install event handling regardless of whether
4567 // there's a restore pass performed. Token values are >= 1.
4568 int token;
4569 if (mNextInstallToken < 0) mNextInstallToken = 1;
4570 token = mNextInstallToken++;
4571
4572 PostInstallData data = new PostInstallData(args, res);
4573 mRunningInstalls.put(token, data);
4574 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4575
4576 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4577 // Pass responsibility to the Backup Manager. It will perform a
4578 // restore if appropriate, then pass responsibility back to the
4579 // Package Manager to run the post-install observer callbacks
4580 // and broadcasts.
4581 IBackupManager bm = IBackupManager.Stub.asInterface(
4582 ServiceManager.getService(Context.BACKUP_SERVICE));
4583 if (bm != null) {
4584 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4585 + " to BM for possible restore");
4586 try {
4587 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4588 } catch (RemoteException e) {
4589 // can't happen; the backup manager is local
4590 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004591 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004592 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004593 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004594 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004595 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004596 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004598 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004599
4600 if (!doRestore) {
4601 // No restore possible, or the Backup Manager was mysteriously not
4602 // available -- just fire the post-install work request directly.
4603 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4604 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4605 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 }
4608 });
4609 }
4610
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004611 abstract class HandlerParams {
4612 final static int MAX_RETRIES = 4;
4613 int retry = 0;
4614 final void startCopy() {
4615 try {
4616 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4617 retry++;
4618 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004619 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004620 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4621 handleServiceError();
4622 return;
4623 } else {
4624 handleStartCopy();
4625 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4626 mHandler.sendEmptyMessage(MCS_UNBIND);
4627 }
4628 } catch (RemoteException e) {
4629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4630 mHandler.sendEmptyMessage(MCS_RECONNECT);
4631 }
4632 handleReturnCode();
4633 }
4634
4635 final void serviceError() {
4636 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4637 handleServiceError();
4638 handleReturnCode();
4639 }
4640 abstract void handleStartCopy() throws RemoteException;
4641 abstract void handleServiceError();
4642 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004643 }
4644
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004645 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004646 final IPackageInstallObserver observer;
4647 int flags;
4648 final Uri packageURI;
4649 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004650 private InstallArgs mArgs;
4651 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004652 InstallParams(Uri packageURI,
4653 IPackageInstallObserver observer, int flags,
4654 String installerPackageName) {
4655 this.packageURI = packageURI;
4656 this.flags = flags;
4657 this.observer = observer;
4658 this.installerPackageName = installerPackageName;
4659 }
4660
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004661 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4662 String packageName = pkgLite.packageName;
4663 int installLocation = pkgLite.installLocation;
4664 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4665 synchronized (mPackages) {
4666 PackageParser.Package pkg = mPackages.get(packageName);
4667 if (pkg != null) {
4668 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4669 // Check for updated system application.
4670 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4671 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004672 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004673 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4674 }
4675 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4676 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004677 if (onSd) {
4678 // Install flag overrides everything.
4679 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4680 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004681 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004682 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4683 // Application explicitly specified internal.
4684 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4685 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4686 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004687 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004688 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004689 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4690 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4691 }
4692 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004693 }
4694 }
4695 } else {
4696 // Invalid install. Return error code
4697 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4698 }
4699 }
4700 }
4701 // All the special cases have been taken care of.
4702 // Return result based on recommended install location.
4703 if (onSd) {
4704 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4705 }
4706 return pkgLite.recommendedInstallLocation;
4707 }
4708
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004709 /*
4710 * Invoke remote method to get package information and install
4711 * location values. Override install location based on default
4712 * policy if needed and then create install arguments based
4713 * on the install location.
4714 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004715 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004716 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004717 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4718 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004719 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4720 if (onInt && onSd) {
4721 // Check if both bits are set.
4722 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4723 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4724 } else if (fwdLocked && onSd) {
4725 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004726 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004727 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004728 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004729 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004730 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004731 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004732 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4733 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4734 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4735 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4736 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004737 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4738 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4739 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004740 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4741 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004742 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004743 // Override with defaults if needed.
4744 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004745 if (!onSd && !onInt) {
4746 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004747 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4748 // Set the flag to install on external media.
4749 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004750 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004751 } else {
4752 // Make sure the flag for installing on external
4753 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004754 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004755 flags &= ~PackageManager.INSTALL_EXTERNAL;
4756 }
4757 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 }
4759 }
4760 // Create the file args now.
4761 mArgs = createInstallArgs(this);
4762 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4763 // Create copy only if we are not in an erroneous state.
4764 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004765 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004766 }
4767 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004768 }
4769
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004770 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 void handleReturnCode() {
4772 processPendingInstall(mArgs, mRet);
4773 }
4774
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004775 @Override
4776 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004777 mArgs = createInstallArgs(this);
4778 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004780 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004781
4782 /*
4783 * Utility class used in movePackage api.
4784 * srcArgs and targetArgs are not set for invalid flags and make
4785 * sure to do null checks when invoking methods on them.
4786 * We probably want to return ErrorPrams for both failed installs
4787 * and moves.
4788 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004789 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 final IPackageMoveObserver observer;
4791 final int flags;
4792 final String packageName;
4793 final InstallArgs srcArgs;
4794 final InstallArgs targetArgs;
4795 int mRet;
4796 MoveParams(InstallArgs srcArgs,
4797 IPackageMoveObserver observer,
4798 int flags, String packageName) {
4799 this.srcArgs = srcArgs;
4800 this.observer = observer;
4801 this.flags = flags;
4802 this.packageName = packageName;
4803 if (srcArgs != null) {
4804 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4805 targetArgs = createInstallArgs(packageUri, flags, packageName);
4806 } else {
4807 targetArgs = null;
4808 }
4809 }
4810
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004811 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004812 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4813 // Check for storage space on target medium
4814 if (!targetArgs.checkFreeStorage(mContainerService)) {
4815 Log.w(TAG, "Insufficient storage to install");
4816 return;
4817 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004818 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004819 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004820 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004821 if (DEBUG_SD_INSTALL) {
4822 StringBuilder builder = new StringBuilder();
4823 if (srcArgs != null) {
4824 builder.append("src: ");
4825 builder.append(srcArgs.getCodePath());
4826 }
4827 if (targetArgs != null) {
4828 builder.append(" target : ");
4829 builder.append(targetArgs.getCodePath());
4830 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004831 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004832 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 }
4834
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004835 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004836 void handleReturnCode() {
4837 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004838 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4839 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4840 currentStatus = PackageManager.MOVE_SUCCEEDED;
4841 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4842 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4843 }
4844 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 }
4846
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004847 @Override
4848 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004849 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004850 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004851 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004852
4853 private InstallArgs createInstallArgs(InstallParams params) {
4854 if (installOnSd(params.flags)) {
4855 return new SdInstallArgs(params);
4856 } else {
4857 return new FileInstallArgs(params);
4858 }
4859 }
4860
4861 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4862 if (installOnSd(flags)) {
4863 return new SdInstallArgs(fullCodePath, fullResourcePath);
4864 } else {
4865 return new FileInstallArgs(fullCodePath, fullResourcePath);
4866 }
4867 }
4868
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004869 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4870 if (installOnSd(flags)) {
4871 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4872 return new SdInstallArgs(packageURI, cid);
4873 } else {
4874 return new FileInstallArgs(packageURI, pkgName);
4875 }
4876 }
4877
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004878 static abstract class InstallArgs {
4879 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004880 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004881 final int flags;
4882 final Uri packageURI;
4883 final String installerPackageName;
4884
4885 InstallArgs(Uri packageURI,
4886 IPackageInstallObserver observer, int flags,
4887 String installerPackageName) {
4888 this.packageURI = packageURI;
4889 this.flags = flags;
4890 this.observer = observer;
4891 this.installerPackageName = installerPackageName;
4892 }
4893
4894 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004895 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004896 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004897 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004898 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004899 abstract String getCodePath();
4900 abstract String getResourcePath();
4901 // Need installer lock especially for dex file removal.
4902 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004903 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004904 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004905 }
4906
4907 class FileInstallArgs extends InstallArgs {
4908 File installDir;
4909 String codeFileName;
4910 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004912
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004913 FileInstallArgs(InstallParams params) {
4914 super(params.packageURI, params.observer,
4915 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004916 }
4917
4918 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4919 super(null, null, 0, null);
4920 File codeFile = new File(fullCodePath);
4921 installDir = codeFile.getParentFile();
4922 codeFileName = fullCodePath;
4923 resourceFileName = fullResourcePath;
4924 }
4925
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004926 FileInstallArgs(Uri packageURI, String pkgName) {
4927 super(packageURI, null, 0, null);
4928 boolean fwdLocked = isFwdLocked(flags);
4929 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4930 String apkName = getNextCodePath(null, pkgName, ".apk");
4931 codeFileName = new File(installDir, apkName + ".apk").getPath();
4932 resourceFileName = getResourcePathFromCodePath();
4933 }
4934
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004935 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4936 return imcs.checkFreeStorage(false, packageURI);
4937 }
4938
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004939 String getCodePath() {
4940 return codeFileName;
4941 }
4942
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004943 void createCopyFile() {
4944 boolean fwdLocked = isFwdLocked(flags);
4945 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4946 codeFileName = createTempPackageFile(installDir).getPath();
4947 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004948 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004949 }
4950
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004951 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004952 if (temp) {
4953 // Generate temp file name
4954 createCopyFile();
4955 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004956 // Get a ParcelFileDescriptor to write to the output file
4957 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004958 if (!created) {
4959 try {
4960 codeFile.createNewFile();
4961 // Set permissions
4962 if (!setPermissions()) {
4963 // Failed setting permissions.
4964 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4965 }
4966 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004967 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004968 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4969 }
4970 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004971 ParcelFileDescriptor out = null;
4972 try {
4973 out = ParcelFileDescriptor.open(codeFile,
4974 ParcelFileDescriptor.MODE_READ_WRITE);
4975 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004976 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4978 }
4979 // Copy the resource now
4980 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4981 try {
4982 if (imcs.copyResource(packageURI, out)) {
4983 ret = PackageManager.INSTALL_SUCCEEDED;
4984 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004985 } finally {
4986 try { if (out != null) out.close(); } catch (IOException e) {}
4987 }
4988 return ret;
4989 }
4990
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004991 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 if (status != PackageManager.INSTALL_SUCCEEDED) {
4993 cleanUp();
4994 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004995 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004996 }
4997
4998 boolean doRename(int status, final String pkgName, String oldCodePath) {
4999 if (status != PackageManager.INSTALL_SUCCEEDED) {
5000 cleanUp();
5001 return false;
5002 } else {
5003 // Rename based on packageName
5004 File codeFile = new File(getCodePath());
5005 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5006 File desFile = new File(installDir, apkName + ".apk");
5007 if (!codeFile.renameTo(desFile)) {
5008 return false;
5009 }
5010 // Reset paths since the file has been renamed.
5011 codeFileName = desFile.getPath();
5012 resourceFileName = getResourcePathFromCodePath();
5013 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005014 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005015 // Failed setting permissions.
5016 return false;
5017 }
5018 return true;
5019 }
5020 }
5021
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005022 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 if (status != PackageManager.INSTALL_SUCCEEDED) {
5024 cleanUp();
5025 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005026 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005027 }
5028
5029 String getResourcePath() {
5030 return resourceFileName;
5031 }
5032
5033 String getResourcePathFromCodePath() {
5034 String codePath = getCodePath();
5035 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5036 String apkNameOnly = getApkName(codePath);
5037 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5038 } else {
5039 return codePath;
5040 }
5041 }
5042
5043 private boolean cleanUp() {
5044 boolean ret = true;
5045 String sourceDir = getCodePath();
5046 String publicSourceDir = getResourcePath();
5047 if (sourceDir != null) {
5048 File sourceFile = new File(sourceDir);
5049 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005050 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 ret = false;
5052 }
5053 // Delete application's code and resources
5054 sourceFile.delete();
5055 }
5056 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5057 final File publicSourceFile = new File(publicSourceDir);
5058 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005059 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005060 }
5061 if (publicSourceFile.exists()) {
5062 publicSourceFile.delete();
5063 }
5064 }
5065 return ret;
5066 }
5067
5068 void cleanUpResourcesLI() {
5069 String sourceDir = getCodePath();
5070 if (cleanUp() && mInstaller != null) {
5071 int retCode = mInstaller.rmdex(sourceDir);
5072 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005073 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005074 + " at location "
5075 + sourceDir + ", retcode=" + retCode);
5076 // we don't consider this to be a failure of the core package deletion
5077 }
5078 }
5079 }
5080
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005081 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005082 // TODO Do this in a more elegant way later on. for now just a hack
5083 if (!isFwdLocked(flags)) {
5084 final int filePermissions =
5085 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5086 |FileUtils.S_IROTH;
5087 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5088 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005089 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 getCodePath()
5091 + ". The return code was: " + retCode);
5092 // TODO Define new internal error
5093 return false;
5094 }
5095 return true;
5096 }
5097 return true;
5098 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005099
5100 boolean doPostDeleteLI(boolean delete) {
5101 cleanUpResourcesLI();
5102 return true;
5103 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 }
5105
5106 class SdInstallArgs extends InstallArgs {
5107 String cid;
5108 String cachePath;
5109 static final String RES_FILE_NAME = "pkg.apk";
5110
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005111 SdInstallArgs(InstallParams params) {
5112 super(params.packageURI, params.observer,
5113 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 }
5115
5116 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005117 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005118 // Extract cid from fullCodePath
5119 int eidx = fullCodePath.lastIndexOf("/");
5120 String subStr1 = fullCodePath.substring(0, eidx);
5121 int sidx = subStr1.lastIndexOf("/");
5122 cid = subStr1.substring(sidx+1, eidx);
5123 cachePath = subStr1;
5124 }
5125
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005126 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005127 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5128 this.cid = cid;
5129 }
5130
5131 SdInstallArgs(Uri packageURI, String cid) {
5132 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005133 this.cid = cid;
5134 }
5135
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 void createCopyFile() {
5137 cid = getTempContainerId();
5138 }
5139
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005140 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5141 return imcs.checkFreeStorage(true, packageURI);
5142 }
5143
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005144 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005145 if (temp) {
5146 createCopyFile();
5147 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005148 cachePath = imcs.copyResourceToContainer(
5149 packageURI, cid,
5150 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005151 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5152 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005153 }
5154
5155 @Override
5156 String getCodePath() {
5157 return cachePath + "/" + RES_FILE_NAME;
5158 }
5159
5160 @Override
5161 String getResourcePath() {
5162 return cachePath + "/" + RES_FILE_NAME;
5163 }
5164
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005165 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005166 if (status != PackageManager.INSTALL_SUCCEEDED) {
5167 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005168 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005169 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005170 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005171 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005172 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005173 if (cachePath == null) {
5174 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5175 }
5176 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005177 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005178 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005179 }
5180
5181 boolean doRename(int status, final String pkgName,
5182 String oldCodePath) {
5183 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005184 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005185 if (PackageHelper.isContainerMounted(cid)) {
5186 // Unmount the container
5187 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005188 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005189 return false;
5190 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005192 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005193 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5194 " which might be stale. Will try to clean up.");
5195 // Clean up the stale container and proceed to recreate.
5196 if (!PackageHelper.destroySdDir(newCacheId)) {
5197 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5198 return false;
5199 }
5200 // Successfully cleaned up stale container. Try to rename again.
5201 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5202 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5203 + " inspite of cleaning it up.");
5204 return false;
5205 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005206 }
5207 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005208 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005209 newCachePath = PackageHelper.mountSdDir(newCacheId,
5210 getEncryptKey(), Process.SYSTEM_UID);
5211 } else {
5212 newCachePath = PackageHelper.getSdDir(newCacheId);
5213 }
5214 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005215 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005216 return false;
5217 }
5218 Log.i(TAG, "Succesfully renamed " + cid +
5219 " at path: " + cachePath + " to " + newCacheId +
5220 " at new path: " + newCachePath);
5221 cid = newCacheId;
5222 cachePath = newCachePath;
5223 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
5225
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005226 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 if (status != PackageManager.INSTALL_SUCCEEDED) {
5228 cleanUp();
5229 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005230 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005231 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005232 PackageHelper.mountSdDir(cid,
5233 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005234 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005235 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005237 }
5238
5239 private void cleanUp() {
5240 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005241 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 }
5243
5244 void cleanUpResourcesLI() {
5245 String sourceFile = getCodePath();
5246 // Remove dex file
5247 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005248 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005249 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005250 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005251 + " at location "
5252 + sourceFile.toString() + ", retcode=" + retCode);
5253 // we don't consider this to be a failure of the core package deletion
5254 }
5255 }
5256 cleanUp();
5257 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005258
5259 boolean matchContainer(String app) {
5260 if (cid.startsWith(app)) {
5261 return true;
5262 }
5263 return false;
5264 }
5265
5266 String getPackageName() {
5267 int idx = cid.lastIndexOf("-");
5268 if (idx == -1) {
5269 return cid;
5270 }
5271 return cid.substring(0, idx);
5272 }
5273
5274 boolean doPostDeleteLI(boolean delete) {
5275 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005276 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005277 if (mounted) {
5278 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005279 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 }
5281 if (ret && delete) {
5282 cleanUpResourcesLI();
5283 }
5284 return ret;
5285 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005286 };
5287
5288 // Utility method used to create code paths based on package name and available index.
5289 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5290 String idxStr = "";
5291 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005292 // Fall back to default value of idx=1 if prefix is not
5293 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005294 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005295 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005296 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005297 if (subStr.endsWith(suffix)) {
5298 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005299 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 // If oldCodePath already contains prefix find out the
5301 // ending index to either increment or decrement.
5302 int sidx = subStr.lastIndexOf(prefix);
5303 if (sidx != -1) {
5304 subStr = subStr.substring(sidx + prefix.length());
5305 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005306 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5307 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005308 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309 try {
5310 idx = Integer.parseInt(subStr);
5311 if (idx <= 1) {
5312 idx++;
5313 } else {
5314 idx--;
5315 }
5316 } catch(NumberFormatException e) {
5317 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005318 }
5319 }
5320 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005321 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 return prefix + idxStr;
5323 }
5324
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005325 // Utility method used to ignore ADD/REMOVE events
5326 // by directory observer.
5327 private static boolean ignoreCodePath(String fullPathStr) {
5328 String apkName = getApkName(fullPathStr);
5329 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5330 if (idx != -1 && ((idx+1) < apkName.length())) {
5331 // Make sure the package ends with a numeral
5332 String version = apkName.substring(idx+1);
5333 try {
5334 Integer.parseInt(version);
5335 return true;
5336 } catch (NumberFormatException e) {}
5337 }
5338 return false;
5339 }
5340
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 // Utility method that returns the relative package path with respect
5342 // to the installation directory. Like say for /data/data/com.test-1.apk
5343 // string com.test-1 is returned.
5344 static String getApkName(String codePath) {
5345 if (codePath == null) {
5346 return null;
5347 }
5348 int sidx = codePath.lastIndexOf("/");
5349 int eidx = codePath.lastIndexOf(".");
5350 if (eidx == -1) {
5351 eidx = codePath.length();
5352 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005353 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005354 return null;
5355 }
5356 return codePath.substring(sidx+1, eidx);
5357 }
5358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 class PackageInstalledInfo {
5360 String name;
5361 int uid;
5362 PackageParser.Package pkg;
5363 int returnCode;
5364 PackageRemovedInfo removedInfo;
5365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005367 /*
5368 * Install a non-existing package.
5369 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005370 private void installNewPackageLI(PackageParser.Package pkg,
5371 int parseFlags,
5372 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005373 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005375 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005376
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005377 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 res.name = pkgName;
5379 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005380 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005382 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 + " without first uninstalling.");
5384 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5385 return;
5386 }
5387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005388 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005389 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005391 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005392 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5393 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5394 }
5395 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005396 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005397 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 res);
5399 // delete the partially installed application. the data directory will have to be
5400 // restored if it was already existing
5401 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5402 // remove package from internal structures. Note that we want deletePackageX to
5403 // delete the package data and cache directories that it created in
5404 // scanPackageLocked, unless those directories existed before we even tried to
5405 // install.
5406 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5409 res.removedInfo);
5410 }
5411 }
5412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005413
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005414 private void replacePackageLI(PackageParser.Package pkg,
5415 int parseFlags,
5416 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005417 String installerPackageName, PackageInstalledInfo res) {
5418
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005419 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005420 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 // First find the old package info and check signatures
5422 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005423 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005424 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005425 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5427 return;
5428 }
5429 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005430 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005431 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005432 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005434 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 }
5436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005439 PackageParser.Package pkg,
5440 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005441 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 PackageParser.Package newPackage = null;
5443 String pkgName = deletedPackage.packageName;
5444 boolean deletedPkg = true;
5445 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005446
Jacek Surazski65e13172009-04-28 15:26:38 +02005447 String oldInstallerPackageName = null;
5448 synchronized (mPackages) {
5449 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005451
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005452 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005454 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 res.removedInfo)) {
5456 // If the existing package was'nt successfully deleted
5457 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5458 deletedPkg = false;
5459 } else {
5460 // Successfully deleted the old package. Now proceed with re-installation
5461 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005462 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005464 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5466 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005467 }
5468 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005469 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005470 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 res);
5472 updatedSettings = true;
5473 }
5474 }
5475
5476 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5477 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005478 // were keeping around in case we needed them (see below) can now be deleted.
5479 // This info will be set on the res.removedInfo to clean up later on as post
5480 // install action.
5481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 //update signature on the new package setting
5483 //this should always succeed, since we checked the
5484 //signature earlier.
5485 synchronized(mPackages) {
5486 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5487 parseFlags, true);
5488 }
5489 } else {
5490 // remove package from internal structures. Note that we want deletePackageX to
5491 // delete the package data and cache directories that it created in
5492 // scanPackageLocked, unless those directories existed before we even tried to
5493 // install.
5494 if(updatedSettings) {
5495 deletePackageLI(
5496 pkgName, true,
5497 PackageManager.DONT_DELETE_DATA,
5498 res.removedInfo);
5499 }
5500 // Since we failed to install the new package we need to restore the old
5501 // package that we deleted.
5502 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005503 File restoreFile = new File(deletedPackage.mPath);
5504 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005505 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005506 return;
5507 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005508 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5509 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005510 // Parse old package
5511 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5512 scanPackageLI(restoreFile, parseFlags, scanMode);
5513 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005514 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5515 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005516 mSettings.writeLP();
5517 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005518 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005519 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 }
5522 }
5523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005526 PackageParser.Package pkg,
5527 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005528 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 PackageParser.Package newPackage = null;
5530 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 PackageParser.PARSE_IS_SYSTEM;
5533 String packageName = deletedPackage.packageName;
5534 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5535 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005536 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 return;
5538 }
5539 PackageParser.Package oldPkg;
5540 PackageSetting oldPkgSetting;
5541 synchronized (mPackages) {
5542 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005543 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5545 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005546 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 return;
5548 }
5549 }
5550 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5551 res.removedInfo.removedPackage = packageName;
5552 // Remove existing system package
5553 removePackageLI(oldPkg, true);
5554 synchronized (mPackages) {
5555 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5556 }
5557
5558 // Successfully disabled the old package. Now proceed with re-installation
5559 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5560 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005561 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005563 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5565 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5566 }
5567 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005568 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 updatedSettings = true;
5570 }
5571
5572 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5573 //update signature on the new package setting
5574 //this should always succeed, since we checked the
5575 //signature earlier.
5576 synchronized(mPackages) {
5577 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5578 parseFlags, true);
5579 }
5580 } else {
5581 // Re installation failed. Restore old information
5582 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005583 if (newPackage != null) {
5584 removePackageLI(newPackage, true);
5585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005587 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005588 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005589 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 // Restore the old system information in Settings
5591 synchronized(mPackages) {
5592 if(updatedSettings) {
5593 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005594 mSettings.setInstallerPackageName(packageName,
5595 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 }
5597 mSettings.writeLP();
5598 }
5599 }
5600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005601
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005602 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005603 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005604 int retCode;
5605 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5606 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5607 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005608 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005609 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5610 }
5611 }
5612 return PackageManager.INSTALL_SUCCEEDED;
5613 }
5614
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005615 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005616 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005617 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 synchronized (mPackages) {
5619 //write settings. the installStatus will be incomplete at this stage.
5620 //note that the new package setting would have already been
5621 //added to mPackages. It hasn't been persisted yet.
5622 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5623 mSettings.writeLP();
5624 }
5625
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005626 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005627 != PackageManager.INSTALL_SUCCEEDED) {
5628 // Discontinue if moving dex files failed.
5629 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005631 if((res.returnCode = setPermissionsLI(newPackage))
5632 != PackageManager.INSTALL_SUCCEEDED) {
5633 if (mInstaller != null) {
5634 mInstaller.rmdex(newPackage.mScanPath);
5635 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005636 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005638 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005641 updatePermissionsLP(newPackage.packageName, newPackage,
5642 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 res.name = pkgName;
5644 res.uid = newPackage.applicationInfo.uid;
5645 res.pkg = newPackage;
5646 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005647 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5649 //to update install status
5650 mSettings.writeLP();
5651 }
5652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005653
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005654 private void installPackageLI(InstallArgs args,
5655 boolean newInstall, PackageInstalledInfo res) {
5656 int pFlags = args.flags;
5657 String installerPackageName = args.installerPackageName;
5658 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005659 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005660 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005661 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005662 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5663 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005664 // Result object to be returned
5665 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5666
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005667 // Retrieve PackageSettings and parse package
5668 int parseFlags = PackageParser.PARSE_CHATTY |
5669 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5670 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5671 parseFlags |= mDefParseFlags;
5672 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5673 pp.setSeparateProcesses(mSeparateProcesses);
5674 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5675 null, mMetrics, parseFlags);
5676 if (pkg == null) {
5677 res.returnCode = pp.getParseError();
5678 return;
5679 }
5680 String pkgName = res.name = pkg.packageName;
5681 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5682 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5683 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5684 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005686 }
5687 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5688 res.returnCode = pp.getParseError();
5689 return;
5690 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005691 // Get rid of all references to package scan path via parser.
5692 pp = null;
5693 String oldCodePath = null;
5694 boolean systemApp = false;
5695 synchronized (mPackages) {
5696 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005697 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5698 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005699 if (pkg.mOriginalPackages != null
5700 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005701 && mPackages.containsKey(oldName)) {
5702 // This package is derived from an original package,
5703 // and this device has been updating from that original
5704 // name. We must continue using the original name, so
5705 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005706 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005707 pkgName = pkg.packageName;
5708 replace = true;
5709 } else if (mPackages.containsKey(pkgName)) {
5710 // This package, under its official name, already exists
5711 // on the device; we should replace it.
5712 replace = true;
5713 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005714 }
5715 PackageSetting ps = mSettings.mPackages.get(pkgName);
5716 if (ps != null) {
5717 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5718 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5719 systemApp = (ps.pkg.applicationInfo.flags &
5720 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005721 }
5722 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005724
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005725 if (systemApp && onSd) {
5726 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005727 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005728 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5729 return;
5730 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005731
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005732 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5733 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5734 return;
5735 }
5736 // Set application objects path explicitly after the rename
5737 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005738 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005739 replacePackageLI(pkg, parseFlags, scanMode,
5740 installerPackageName, res);
5741 } else {
5742 installNewPackageLI(pkg, parseFlags, scanMode,
5743 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 }
5745 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005746
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005747 private int setPermissionsLI(PackageParser.Package newPackage) {
5748 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005749 int retCode = 0;
5750 // TODO Gross hack but fix later. Ideally move this to be a post installation
5751 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005752 if ((newPackage.applicationInfo.flags
5753 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5754 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 try {
5756 extractPublicFiles(newPackage, destResourceFile);
5757 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005758 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 -08005759 " forward-locked app.");
5760 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5761 } finally {
5762 //TODO clean up the extracted public files
5763 }
5764 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005765 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 newPackage.applicationInfo.uid);
5767 } else {
5768 final int filePermissions =
5769 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005770 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 newPackage.applicationInfo.uid);
5772 }
5773 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005774 // The permissions on the resource file was set when it was copied for
5775 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005776 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005779 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005780 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005782 // TODO Define new internal error
5783 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 }
5785 return PackageManager.INSTALL_SUCCEEDED;
5786 }
5787
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005788 private boolean isForwardLocked(PackageParser.Package pkg) {
5789 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 }
5791
5792 private void extractPublicFiles(PackageParser.Package newPackage,
5793 File publicZipFile) throws IOException {
5794 final ZipOutputStream publicZipOutStream =
5795 new ZipOutputStream(new FileOutputStream(publicZipFile));
5796 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5797
5798 // Copy manifest, resources.arsc and res directory to public zip
5799
5800 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5801 while (privateZipEntries.hasMoreElements()) {
5802 final ZipEntry zipEntry = privateZipEntries.nextElement();
5803 final String zipEntryName = zipEntry.getName();
5804 if ("AndroidManifest.xml".equals(zipEntryName)
5805 || "resources.arsc".equals(zipEntryName)
5806 || zipEntryName.startsWith("res/")) {
5807 try {
5808 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5809 } catch (IOException e) {
5810 try {
5811 publicZipOutStream.close();
5812 throw e;
5813 } finally {
5814 publicZipFile.delete();
5815 }
5816 }
5817 }
5818 }
5819
5820 publicZipOutStream.close();
5821 FileUtils.setPermissions(
5822 publicZipFile.getAbsolutePath(),
5823 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5824 -1, -1);
5825 }
5826
5827 private static void copyZipEntry(ZipEntry zipEntry,
5828 ZipFile inZipFile,
5829 ZipOutputStream outZipStream) throws IOException {
5830 byte[] buffer = new byte[4096];
5831 int num;
5832
5833 ZipEntry newEntry;
5834 if (zipEntry.getMethod() == ZipEntry.STORED) {
5835 // Preserve the STORED method of the input entry.
5836 newEntry = new ZipEntry(zipEntry);
5837 } else {
5838 // Create a new entry so that the compressed len is recomputed.
5839 newEntry = new ZipEntry(zipEntry.getName());
5840 }
5841 outZipStream.putNextEntry(newEntry);
5842
5843 InputStream data = inZipFile.getInputStream(zipEntry);
5844 while ((num = data.read(buffer)) > 0) {
5845 outZipStream.write(buffer, 0, num);
5846 }
5847 outZipStream.flush();
5848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 private void deleteTempPackageFiles() {
5851 FilenameFilter filter = new FilenameFilter() {
5852 public boolean accept(File dir, String name) {
5853 return name.startsWith("vmdl") && name.endsWith(".tmp");
5854 }
5855 };
5856 String tmpFilesList[] = mAppInstallDir.list(filter);
5857 if(tmpFilesList == null) {
5858 return;
5859 }
5860 for(int i = 0; i < tmpFilesList.length; i++) {
5861 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5862 tmpFile.delete();
5863 }
5864 }
5865
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005866 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 File tmpPackageFile;
5868 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005869 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005871 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 return null;
5873 }
5874 try {
5875 FileUtils.setPermissions(
5876 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5877 -1, -1);
5878 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005879 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 return null;
5881 }
5882 return tmpPackageFile;
5883 }
5884
5885 public void deletePackage(final String packageName,
5886 final IPackageDeleteObserver observer,
5887 final int flags) {
5888 mContext.enforceCallingOrSelfPermission(
5889 android.Manifest.permission.DELETE_PACKAGES, null);
5890 // Queue up an async operation since the package deletion may take a little while.
5891 mHandler.post(new Runnable() {
5892 public void run() {
5893 mHandler.removeCallbacks(this);
5894 final boolean succeded = deletePackageX(packageName, true, true, flags);
5895 if (observer != null) {
5896 try {
5897 observer.packageDeleted(succeded);
5898 } catch (RemoteException e) {
5899 Log.i(TAG, "Observer no longer exists.");
5900 } //end catch
5901 } //end if
5902 } //end run
5903 });
5904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 /**
5907 * This method is an internal method that could be get invoked either
5908 * to delete an installed package or to clean up a failed installation.
5909 * After deleting an installed package, a broadcast is sent to notify any
5910 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005911 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 * installation wouldn't have sent the initial broadcast either
5913 * The key steps in deleting a package are
5914 * deleting the package information in internal structures like mPackages,
5915 * deleting the packages base directories through installd
5916 * updating mSettings to reflect current status
5917 * persisting settings for later use
5918 * sending a broadcast if necessary
5919 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5921 boolean deleteCodeAndResources, int flags) {
5922 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005923 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005924
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005925 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5926 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5927 try {
5928 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005929 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005930 return false;
5931 }
5932 } catch (RemoteException e) {
5933 }
5934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 synchronized (mInstallLock) {
5936 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005940 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5941 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5942
5943 // If the removed package was a system update, the old system packaged
5944 // was re-enabled; we need to broadcast this information
5945 if (systemUpdate) {
5946 Bundle extras = new Bundle(1);
5947 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5948 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5949
5950 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5951 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005953 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005954 // Force a gc here.
5955 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005956 // Delete the resources here after sending the broadcast to let
5957 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005958 if (info.args != null) {
5959 synchronized (mInstallLock) {
5960 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005961 }
5962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 return res;
5964 }
5965
5966 static class PackageRemovedInfo {
5967 String removedPackage;
5968 int uid = -1;
5969 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005970 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 // Clean up resources deleted packages.
5972 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 void sendBroadcast(boolean fullRemove, boolean replacing) {
5975 Bundle extras = new Bundle(1);
5976 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5977 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5978 if (replacing) {
5979 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5980 }
5981 if (removedPackage != null) {
5982 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5983 }
5984 if (removedUid >= 0) {
5985 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5986 }
5987 }
5988 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005990 /*
5991 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5992 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005993 * 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 -08005994 * delete a partially installed application.
5995 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005996 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 int flags) {
5998 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005999 if (outInfo != null) {
6000 outInfo.removedPackage = packageName;
6001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 removePackageLI(p, true);
6003 // Retrieve object to delete permissions for shared user later on
6004 PackageSetting deletedPs;
6005 synchronized (mPackages) {
6006 deletedPs = mSettings.mPackages.get(packageName);
6007 }
6008 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6009 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006010 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006012 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 + packageName + ", retcode=" + retCode);
6014 // we don't consider this to be a failure of the core package deletion
6015 }
6016 } else {
6017 //for emulator
6018 PackageParser.Package pkg = mPackages.get(packageName);
6019 File dataDir = new File(pkg.applicationInfo.dataDir);
6020 dataDir.delete();
6021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 }
6023 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006024 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006025 schedulePackageCleaning(packageName);
6026
6027 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6028 if (outInfo != null) {
6029 outInfo.removedUid = mSettings.removePackageLP(packageName);
6030 }
6031 if (deletedPs != null) {
6032 updatePermissionsLP(deletedPs.name, null, false, false);
6033 if (deletedPs.sharedUser != null) {
6034 // remove permissions associated with package
6035 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6036 }
6037 }
6038 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006039 // remove from preferred activities.
6040 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6041 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6042 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6043 removed.add(pa);
6044 }
6045 }
6046 for (PreferredActivity pa : removed) {
6047 mSettings.mPreferredActivities.removeFilter(pa);
6048 }
6049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006051 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 }
6053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 /*
6056 * Tries to delete system package.
6057 */
6058 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006059 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 ApplicationInfo applicationInfo = p.applicationInfo;
6061 //applicable for non-partially installed applications only
6062 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006063 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 return false;
6065 }
6066 PackageSetting ps = null;
6067 // Confirm if the system package has been updated
6068 // An updated system app can be deleted. This will also have to restore
6069 // the system pkg from system partition
6070 synchronized (mPackages) {
6071 ps = mSettings.getDisabledSystemPkg(p.packageName);
6072 }
6073 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006074 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 return false;
6076 } else {
6077 Log.i(TAG, "Deleting system pkg from data partition");
6078 }
6079 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006080 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006081 boolean deleteCodeAndResources = false;
6082 if (ps.versionCode < p.mVersionCode) {
6083 // Delete code and resources for downgrades
6084 deleteCodeAndResources = true;
6085 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6086 flags &= ~PackageManager.DONT_DELETE_DATA;
6087 }
6088 } else {
6089 // Preserve data by setting flag
6090 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6091 flags |= PackageManager.DONT_DELETE_DATA;
6092 }
6093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6095 if (!ret) {
6096 return false;
6097 }
6098 synchronized (mPackages) {
6099 // Reinstate the old system package
6100 mSettings.enableSystemPackageLP(p.packageName);
6101 }
6102 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006103 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006105 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006108 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 return false;
6110 }
6111 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006112 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 mSettings.writeLP();
6114 }
6115 return true;
6116 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6119 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6120 ApplicationInfo applicationInfo = p.applicationInfo;
6121 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006122 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 return false;
6124 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006125 if (outInfo != null) {
6126 outInfo.uid = applicationInfo.uid;
6127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128
6129 // Delete package data from internal structures and also remove data if flag is set
6130 removePackageDataLI(p, outInfo, flags);
6131
6132 // Delete application code and resources
6133 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006134 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006135 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006136 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006137 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6138 PackageManager.INSTALL_FORWARD_LOCK : 0;
6139 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006140 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 }
6142 return true;
6143 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 /*
6146 * This method handles package deletion in general
6147 */
6148 private boolean deletePackageLI(String packageName,
6149 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6150 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006151 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 return false;
6153 }
6154 PackageParser.Package p;
6155 boolean dataOnly = false;
6156 synchronized (mPackages) {
6157 p = mPackages.get(packageName);
6158 if (p == null) {
6159 //this retrieves partially installed apps
6160 dataOnly = true;
6161 PackageSetting ps = mSettings.mPackages.get(packageName);
6162 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006163 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 return false;
6165 }
6166 p = ps.pkg;
6167 }
6168 }
6169 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006170 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 return false;
6172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 if (dataOnly) {
6175 // Delete application data first
6176 removePackageDataLI(p, outInfo, flags);
6177 return true;
6178 }
6179 // At this point the package should have ApplicationInfo associated with it
6180 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006181 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 return false;
6183 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006184 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6186 Log.i(TAG, "Removing system package:"+p.packageName);
6187 // When an updated system application is deleted we delete the existing resources as well and
6188 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006189 ret = deleteSystemPackageLI(p, flags, outInfo);
6190 } else {
6191 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006192 // Kill application pre-emptively especially for apps on sd.
6193 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006194 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006196 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 public void clearApplicationUserData(final String packageName,
6200 final IPackageDataObserver observer) {
6201 mContext.enforceCallingOrSelfPermission(
6202 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6203 // Queue up an async operation since the package deletion may take a little while.
6204 mHandler.post(new Runnable() {
6205 public void run() {
6206 mHandler.removeCallbacks(this);
6207 final boolean succeeded;
6208 synchronized (mInstallLock) {
6209 succeeded = clearApplicationUserDataLI(packageName);
6210 }
6211 if (succeeded) {
6212 // invoke DeviceStorageMonitor's update method to clear any notifications
6213 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6214 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6215 if (dsm != null) {
6216 dsm.updateMemory();
6217 }
6218 }
6219 if(observer != null) {
6220 try {
6221 observer.onRemoveCompleted(packageName, succeeded);
6222 } catch (RemoteException e) {
6223 Log.i(TAG, "Observer no longer exists.");
6224 }
6225 } //end if observer
6226 } //end run
6227 });
6228 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 private boolean clearApplicationUserDataLI(String packageName) {
6231 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006232 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 return false;
6234 }
6235 PackageParser.Package p;
6236 boolean dataOnly = false;
6237 synchronized (mPackages) {
6238 p = mPackages.get(packageName);
6239 if(p == null) {
6240 dataOnly = true;
6241 PackageSetting ps = mSettings.mPackages.get(packageName);
6242 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006243 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 return false;
6245 }
6246 p = ps.pkg;
6247 }
6248 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 if(!dataOnly) {
6251 //need to check this only for fully installed applications
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 }
6256 final ApplicationInfo applicationInfo = p.applicationInfo;
6257 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006258 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 return false;
6260 }
6261 }
6262 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006263 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006265 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 + packageName);
6267 return false;
6268 }
6269 }
6270 return true;
6271 }
6272
6273 public void deleteApplicationCacheFiles(final String packageName,
6274 final IPackageDataObserver observer) {
6275 mContext.enforceCallingOrSelfPermission(
6276 android.Manifest.permission.DELETE_CACHE_FILES, null);
6277 // Queue up an async operation since the package deletion may take a little while.
6278 mHandler.post(new Runnable() {
6279 public void run() {
6280 mHandler.removeCallbacks(this);
6281 final boolean succeded;
6282 synchronized (mInstallLock) {
6283 succeded = deleteApplicationCacheFilesLI(packageName);
6284 }
6285 if(observer != null) {
6286 try {
6287 observer.onRemoveCompleted(packageName, succeded);
6288 } catch (RemoteException e) {
6289 Log.i(TAG, "Observer no longer exists.");
6290 }
6291 } //end if observer
6292 } //end run
6293 });
6294 }
6295
6296 private boolean deleteApplicationCacheFilesLI(String packageName) {
6297 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006298 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 return false;
6300 }
6301 PackageParser.Package p;
6302 synchronized (mPackages) {
6303 p = mPackages.get(packageName);
6304 }
6305 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006306 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 return false;
6308 }
6309 final ApplicationInfo applicationInfo = p.applicationInfo;
6310 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006311 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 return false;
6313 }
6314 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006315 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006317 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 + packageName);
6319 return false;
6320 }
6321 }
6322 return true;
6323 }
6324
6325 public void getPackageSizeInfo(final String packageName,
6326 final IPackageStatsObserver observer) {
6327 mContext.enforceCallingOrSelfPermission(
6328 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6329 // Queue up an async operation since the package deletion may take a little while.
6330 mHandler.post(new Runnable() {
6331 public void run() {
6332 mHandler.removeCallbacks(this);
6333 PackageStats lStats = new PackageStats(packageName);
6334 final boolean succeded;
6335 synchronized (mInstallLock) {
6336 succeded = getPackageSizeInfoLI(packageName, lStats);
6337 }
6338 if(observer != null) {
6339 try {
6340 observer.onGetStatsCompleted(lStats, succeded);
6341 } catch (RemoteException e) {
6342 Log.i(TAG, "Observer no longer exists.");
6343 }
6344 } //end if observer
6345 } //end run
6346 });
6347 }
6348
6349 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6350 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006351 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 return false;
6353 }
6354 PackageParser.Package p;
6355 boolean dataOnly = false;
6356 synchronized (mPackages) {
6357 p = mPackages.get(packageName);
6358 if(p == null) {
6359 dataOnly = true;
6360 PackageSetting ps = mSettings.mPackages.get(packageName);
6361 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006362 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 return false;
6364 }
6365 p = ps.pkg;
6366 }
6367 }
6368 String publicSrcDir = null;
6369 if(!dataOnly) {
6370 final ApplicationInfo applicationInfo = p.applicationInfo;
6371 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006372 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 return false;
6374 }
6375 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6376 }
6377 if (mInstaller != null) {
6378 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006379 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 if (res < 0) {
6381 return false;
6382 } else {
6383 return true;
6384 }
6385 }
6386 return true;
6387 }
6388
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 public void addPackageToPreferred(String packageName) {
6391 mContext.enforceCallingOrSelfPermission(
6392 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 }
6395
6396 public void removePackageFromPreferred(String packageName) {
6397 mContext.enforceCallingOrSelfPermission(
6398 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006399 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
6401
6402 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006403 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 }
6405
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006406 int getUidTargetSdkVersionLockedLP(int uid) {
6407 Object obj = mSettings.getUserIdLP(uid);
6408 if (obj instanceof SharedUserSetting) {
6409 SharedUserSetting sus = (SharedUserSetting)obj;
6410 final int N = sus.packages.size();
6411 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6412 Iterator<PackageSetting> it = sus.packages.iterator();
6413 int i=0;
6414 while (it.hasNext()) {
6415 PackageSetting ps = it.next();
6416 if (ps.pkg != null) {
6417 int v = ps.pkg.applicationInfo.targetSdkVersion;
6418 if (v < vers) vers = v;
6419 }
6420 }
6421 return vers;
6422 } else if (obj instanceof PackageSetting) {
6423 PackageSetting ps = (PackageSetting)obj;
6424 if (ps.pkg != null) {
6425 return ps.pkg.applicationInfo.targetSdkVersion;
6426 }
6427 }
6428 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6429 }
6430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 public void addPreferredActivity(IntentFilter filter, int match,
6432 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006434 if (mContext.checkCallingOrSelfPermission(
6435 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6436 != PackageManager.PERMISSION_GRANTED) {
6437 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6438 < Build.VERSION_CODES.FROYO) {
6439 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6440 + Binder.getCallingUid());
6441 return;
6442 }
6443 mContext.enforceCallingOrSelfPermission(
6444 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6445 }
6446
6447 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6449 mSettings.mPreferredActivities.addFilter(
6450 new PreferredActivity(filter, match, set, activity));
6451 mSettings.writeLP();
6452 }
6453 }
6454
Satish Sampath8dbe6122009-06-02 23:35:54 +01006455 public void replacePreferredActivity(IntentFilter filter, int match,
6456 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006457 if (filter.countActions() != 1) {
6458 throw new IllegalArgumentException(
6459 "replacePreferredActivity expects filter to have only 1 action.");
6460 }
6461 if (filter.countCategories() != 1) {
6462 throw new IllegalArgumentException(
6463 "replacePreferredActivity expects filter to have only 1 category.");
6464 }
6465 if (filter.countDataAuthorities() != 0
6466 || filter.countDataPaths() != 0
6467 || filter.countDataSchemes() != 0
6468 || filter.countDataTypes() != 0) {
6469 throw new IllegalArgumentException(
6470 "replacePreferredActivity expects filter to have no data authorities, " +
6471 "paths, schemes or types.");
6472 }
6473 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006474 if (mContext.checkCallingOrSelfPermission(
6475 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6476 != PackageManager.PERMISSION_GRANTED) {
6477 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6478 < Build.VERSION_CODES.FROYO) {
6479 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6480 + Binder.getCallingUid());
6481 return;
6482 }
6483 mContext.enforceCallingOrSelfPermission(
6484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6485 }
6486
Satish Sampath8dbe6122009-06-02 23:35:54 +01006487 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6488 String action = filter.getAction(0);
6489 String category = filter.getCategory(0);
6490 while (it.hasNext()) {
6491 PreferredActivity pa = it.next();
6492 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6493 it.remove();
6494 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6495 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6496 }
6497 }
6498 addPreferredActivity(filter, match, set, activity);
6499 }
6500 }
6501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006504 int uid = Binder.getCallingUid();
6505 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006506 if (pkg == null || pkg.applicationInfo.uid != uid) {
6507 if (mContext.checkCallingOrSelfPermission(
6508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6509 != PackageManager.PERMISSION_GRANTED) {
6510 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6511 < Build.VERSION_CODES.FROYO) {
6512 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6513 + Binder.getCallingUid());
6514 return;
6515 }
6516 mContext.enforceCallingOrSelfPermission(
6517 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6518 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006519 }
6520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 if (clearPackagePreferredActivitiesLP(packageName)) {
6522 mSettings.writeLP();
6523 }
6524 }
6525 }
6526
6527 boolean clearPackagePreferredActivitiesLP(String packageName) {
6528 boolean changed = false;
6529 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6530 while (it.hasNext()) {
6531 PreferredActivity pa = it.next();
6532 if (pa.mActivity.getPackageName().equals(packageName)) {
6533 it.remove();
6534 changed = true;
6535 }
6536 }
6537 return changed;
6538 }
6539
6540 public int getPreferredActivities(List<IntentFilter> outFilters,
6541 List<ComponentName> outActivities, String packageName) {
6542
6543 int num = 0;
6544 synchronized (mPackages) {
6545 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6546 while (it.hasNext()) {
6547 PreferredActivity pa = it.next();
6548 if (packageName == null
6549 || pa.mActivity.getPackageName().equals(packageName)) {
6550 if (outFilters != null) {
6551 outFilters.add(new IntentFilter(pa));
6552 }
6553 if (outActivities != null) {
6554 outActivities.add(pa.mActivity);
6555 }
6556 }
6557 }
6558 }
6559
6560 return num;
6561 }
6562
6563 public void setApplicationEnabledSetting(String appPackageName,
6564 int newState, int flags) {
6565 setEnabledSetting(appPackageName, null, newState, flags);
6566 }
6567
6568 public void setComponentEnabledSetting(ComponentName componentName,
6569 int newState, int flags) {
6570 setEnabledSetting(componentName.getPackageName(),
6571 componentName.getClassName(), newState, flags);
6572 }
6573
6574 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006575 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6577 || newState == COMPONENT_ENABLED_STATE_ENABLED
6578 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6579 throw new IllegalArgumentException("Invalid new component state: "
6580 + newState);
6581 }
6582 PackageSetting pkgSetting;
6583 final int uid = Binder.getCallingUid();
6584 final int permission = mContext.checkCallingPermission(
6585 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6586 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006587 boolean sendNow = false;
6588 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006589 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006591 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006593 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006595 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006597 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 }
6599 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006600 "Unknown component: " + packageName
6601 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
6603 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6604 throw new SecurityException(
6605 "Permission Denial: attempt to change component state from pid="
6606 + Binder.getCallingPid()
6607 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6608 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006609 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 // We're dealing with an application/package level state change
6611 pkgSetting.enabled = newState;
6612 } else {
6613 // We're dealing with a component level state change
6614 switch (newState) {
6615 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006616 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 break;
6618 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006619 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 break;
6621 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006622 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 break;
6624 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006625 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006626 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 }
6628 }
6629 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006630 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006631 components = mPendingBroadcasts.get(packageName);
6632 boolean newPackage = components == null;
6633 if (newPackage) {
6634 components = new ArrayList<String>();
6635 }
6636 if (!components.contains(componentName)) {
6637 components.add(componentName);
6638 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006639 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6640 sendNow = true;
6641 // Purge entry from pending broadcast list if another one exists already
6642 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006643 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006644 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006645 if (newPackage) {
6646 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006647 }
6648 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6649 // Schedule a message
6650 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6651 }
6652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 long callingId = Binder.clearCallingIdentity();
6656 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006657 if (sendNow) {
6658 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006659 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 } finally {
6662 Binder.restoreCallingIdentity(callingId);
6663 }
6664 }
6665
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006666 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006667 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6668 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6669 + " components=" + componentNames);
6670 Bundle extras = new Bundle(4);
6671 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6672 String nameList[] = new String[componentNames.size()];
6673 componentNames.toArray(nameList);
6674 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006675 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6676 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006677 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 }
6679
Jacek Surazski65e13172009-04-28 15:26:38 +02006680 public String getInstallerPackageName(String packageName) {
6681 synchronized (mPackages) {
6682 PackageSetting pkg = mSettings.mPackages.get(packageName);
6683 if (pkg == null) {
6684 throw new IllegalArgumentException("Unknown package: " + packageName);
6685 }
6686 return pkg.installerPackageName;
6687 }
6688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 public int getApplicationEnabledSetting(String appPackageName) {
6691 synchronized (mPackages) {
6692 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6693 if (pkg == null) {
6694 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6695 }
6696 return pkg.enabled;
6697 }
6698 }
6699
6700 public int getComponentEnabledSetting(ComponentName componentName) {
6701 synchronized (mPackages) {
6702 final String packageNameStr = componentName.getPackageName();
6703 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6704 if (pkg == null) {
6705 throw new IllegalArgumentException("Unknown component: " + componentName);
6706 }
6707 final String classNameStr = componentName.getClassName();
6708 return pkg.currentEnabledStateLP(classNameStr);
6709 }
6710 }
6711
6712 public void enterSafeMode() {
6713 if (!mSystemReady) {
6714 mSafeMode = true;
6715 }
6716 }
6717
6718 public void systemReady() {
6719 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006720
6721 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006722 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006723 mContext.getContentResolver(),
6724 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006725 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006726 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006727 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 }
6730
6731 public boolean isSafeMode() {
6732 return mSafeMode;
6733 }
6734
6735 public boolean hasSystemUidErrors() {
6736 return mHasSystemUidErrors;
6737 }
6738
6739 static String arrayToString(int[] array) {
6740 StringBuffer buf = new StringBuffer(128);
6741 buf.append('[');
6742 if (array != null) {
6743 for (int i=0; i<array.length; i++) {
6744 if (i > 0) buf.append(", ");
6745 buf.append(array[i]);
6746 }
6747 }
6748 buf.append(']');
6749 return buf.toString();
6750 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 @Override
6753 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6754 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6755 != PackageManager.PERMISSION_GRANTED) {
6756 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6757 + Binder.getCallingPid()
6758 + ", uid=" + Binder.getCallingUid()
6759 + " without permission "
6760 + android.Manifest.permission.DUMP);
6761 return;
6762 }
6763
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006764 String packageName = null;
6765
6766 int opti = 0;
6767 while (opti < args.length) {
6768 String opt = args[opti];
6769 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6770 break;
6771 }
6772 opti++;
6773 if ("-a".equals(opt)) {
6774 // Right now we only know how to print all.
6775 } else if ("-h".equals(opt)) {
6776 pw.println("Package manager dump options:");
6777 pw.println(" [-h] [cmd] ...");
6778 pw.println(" cmd may be one of:");
6779 pw.println(" [package.name]: info about given package");
6780 return;
6781 } else {
6782 pw.println("Unknown argument: " + opt + "; use -h for help");
6783 }
6784 }
6785
6786 // Is the caller requesting to dump a particular piece of data?
6787 if (opti < args.length) {
6788 String cmd = args[opti];
6789 opti++;
6790 // Is this a package name?
6791 if ("android".equals(cmd) || cmd.contains(".")) {
6792 packageName = cmd;
6793 }
6794 }
6795
6796 boolean printedTitle = false;
6797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006799 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6800 printedTitle = true;
6801 }
6802 if (mReceivers.dump(pw, printedTitle
6803 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6804 " ", packageName)) {
6805 printedTitle = true;
6806 }
6807 if (mServices.dump(pw, printedTitle
6808 ? "\nService Resolver Table:" : "Service Resolver Table:",
6809 " ", packageName)) {
6810 printedTitle = true;
6811 }
6812 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6813 ? "\nPreferred Activities:" : "Preferred Activities:",
6814 " ", packageName)) {
6815 printedTitle = true;
6816 }
6817 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 {
6819 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006820 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6821 continue;
6822 }
6823 if (!printedSomething) {
6824 if (printedTitle) pw.println(" ");
6825 pw.println("Permissions:");
6826 printedSomething = true;
6827 printedTitle = true;
6828 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006829 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6830 pw.print(Integer.toHexString(System.identityHashCode(p)));
6831 pw.println("):");
6832 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6833 pw.print(" uid="); pw.print(p.uid);
6834 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006835 pw.print(" type="); pw.print(p.type);
6836 pw.print(" prot="); pw.println(p.protectionLevel);
6837 if (p.packageSetting != null) {
6838 pw.print(" packageSetting="); pw.println(p.packageSetting);
6839 }
6840 if (p.perm != null) {
6841 pw.print(" perm="); pw.println(p.perm);
6842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 }
6844 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006845 printedSomething = false;
6846 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 {
6848 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006849 if (packageName != null && !packageName.equals(ps.realName)
6850 && !packageName.equals(ps.name)) {
6851 continue;
6852 }
6853 if (!printedSomething) {
6854 if (printedTitle) pw.println(" ");
6855 pw.println("Packages:");
6856 printedSomething = true;
6857 printedTitle = true;
6858 }
6859 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006860 pw.print(" Package [");
6861 pw.print(ps.realName != null ? ps.realName : ps.name);
6862 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006863 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6864 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006865 if (ps.realName != null) {
6866 pw.print(" compat name="); pw.println(ps.name);
6867 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006868 pw.print(" userId="); pw.print(ps.userId);
6869 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6870 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6871 pw.print(" pkg="); pw.println(ps.pkg);
6872 pw.print(" codePath="); pw.println(ps.codePathString);
6873 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006875 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006876 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006877 pw.print(" supportsScreens=[");
6878 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006879 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006880 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006881 if (!first) pw.print(", ");
6882 first = false;
6883 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006885 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006886 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006887 if (!first) pw.print(", ");
6888 first = false;
6889 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006891 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006892 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006893 if (!first) pw.print(", ");
6894 first = false;
6895 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006897 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006898 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006899 if (!first) pw.print(", ");
6900 first = false;
6901 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006903 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006904 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6905 if (!first) pw.print(", ");
6906 first = false;
6907 pw.print("anyDensity");
6908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006910 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006911 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6912 pw.print(" signatures="); pw.println(ps.signatures);
6913 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07006914 pw.print(" haveGids="); pw.println(ps.haveGids);
6915 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006916 pw.print(" installStatus="); pw.print(ps.installStatus);
6917 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 if (ps.disabledComponents.size() > 0) {
6919 pw.println(" disabledComponents:");
6920 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006921 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006922 }
6923 }
6924 if (ps.enabledComponents.size() > 0) {
6925 pw.println(" enabledComponents:");
6926 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006927 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 }
6929 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006930 if (ps.grantedPermissions.size() > 0) {
6931 pw.println(" grantedPermissions:");
6932 for (String s : ps.grantedPermissions) {
6933 pw.print(" "); pw.println(s);
6934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006936 }
6937 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006938 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006939 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006940 for (HashMap.Entry<String, String> e
6941 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 if (packageName != null && !packageName.equals(e.getKey())
6943 && !packageName.equals(e.getValue())) {
6944 continue;
6945 }
6946 if (!printedSomething) {
6947 if (printedTitle) pw.println(" ");
6948 pw.println("Renamed packages:");
6949 printedSomething = true;
6950 printedTitle = true;
6951 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006952 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6953 pw.println(e.getValue());
6954 }
6955 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006956 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006957 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006958 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006959 if (packageName != null && !packageName.equals(ps.realName)
6960 && !packageName.equals(ps.name)) {
6961 continue;
6962 }
6963 if (!printedSomething) {
6964 if (printedTitle) pw.println(" ");
6965 pw.println("Hidden system packages:");
6966 printedSomething = true;
6967 printedTitle = true;
6968 }
6969 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006970 pw.print(ps.realName != null ? ps.realName : ps.name);
6971 pw.print("] (");
6972 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6973 pw.println("):");
6974 if (ps.realName != null) {
6975 pw.print(" compat name="); pw.println(ps.name);
6976 }
6977 pw.print(" userId="); pw.println(ps.userId);
6978 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6979 pw.print(" codePath="); pw.println(ps.codePathString);
6980 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6981 }
6982 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006983 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 {
6985 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006986 if (packageName != null && su != packageSharedUser) {
6987 continue;
6988 }
6989 if (!printedSomething) {
6990 if (printedTitle) pw.println(" ");
6991 pw.println("Shared users:");
6992 printedSomething = true;
6993 printedTitle = true;
6994 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006995 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6996 pw.print(Integer.toHexString(System.identityHashCode(su)));
6997 pw.println("):");
6998 pw.print(" userId="); pw.print(su.userId);
6999 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007000 pw.println(" grantedPermissions:");
7001 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007002 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007004 }
7005 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007006
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007007 if (packageName == null) {
7008 if (printedTitle) pw.println(" ");
7009 printedTitle = true;
7010 pw.println("Settings parse messages:");
7011 pw.println(mSettings.mReadMessages.toString());
7012
7013 pw.println(" ");
7014 pw.println("Package warning messages:");
7015 File fname = getSettingsProblemFile();
7016 FileInputStream in;
7017 try {
7018 in = new FileInputStream(fname);
7019 int avail = in.available();
7020 byte[] data = new byte[avail];
7021 in.read(data);
7022 pw.println(new String(data));
7023 } catch (FileNotFoundException e) {
7024 } catch (IOException e) {
7025 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007028
7029 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007030 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007031 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007032 if (packageName != null && !packageName.equals(p.info.packageName)) {
7033 continue;
7034 }
7035 if (!printedSomething) {
7036 if (printedTitle) pw.println(" ");
7037 pw.println("Registered ContentProviders:");
7038 printedSomething = true;
7039 printedTitle = true;
7040 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007041 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007042 pw.println(p.toString());
7043 }
7044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 }
7046
7047 static final class BasePermission {
7048 final static int TYPE_NORMAL = 0;
7049 final static int TYPE_BUILTIN = 1;
7050 final static int TYPE_DYNAMIC = 2;
7051
7052 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007053 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007054 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007056 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007057 PackageParser.Permission perm;
7058 PermissionInfo pendingInfo;
7059 int uid;
7060 int[] gids;
7061
7062 BasePermission(String _name, String _sourcePackage, int _type) {
7063 name = _name;
7064 sourcePackage = _sourcePackage;
7065 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007066 // Default to most conservative protection level.
7067 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7068 }
7069
7070 public String toString() {
7071 return "BasePermission{"
7072 + Integer.toHexString(System.identityHashCode(this))
7073 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 }
7075 }
7076
7077 static class PackageSignatures {
7078 private Signature[] mSignatures;
7079
7080 PackageSignatures(Signature[] sigs) {
7081 assignSignatures(sigs);
7082 }
7083
7084 PackageSignatures() {
7085 }
7086
7087 void writeXml(XmlSerializer serializer, String tagName,
7088 ArrayList<Signature> pastSignatures) throws IOException {
7089 if (mSignatures == null) {
7090 return;
7091 }
7092 serializer.startTag(null, tagName);
7093 serializer.attribute(null, "count",
7094 Integer.toString(mSignatures.length));
7095 for (int i=0; i<mSignatures.length; i++) {
7096 serializer.startTag(null, "cert");
7097 final Signature sig = mSignatures[i];
7098 final int sigHash = sig.hashCode();
7099 final int numPast = pastSignatures.size();
7100 int j;
7101 for (j=0; j<numPast; j++) {
7102 Signature pastSig = pastSignatures.get(j);
7103 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7104 serializer.attribute(null, "index", Integer.toString(j));
7105 break;
7106 }
7107 }
7108 if (j >= numPast) {
7109 pastSignatures.add(sig);
7110 serializer.attribute(null, "index", Integer.toString(numPast));
7111 serializer.attribute(null, "key", sig.toCharsString());
7112 }
7113 serializer.endTag(null, "cert");
7114 }
7115 serializer.endTag(null, tagName);
7116 }
7117
7118 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7119 throws IOException, XmlPullParserException {
7120 String countStr = parser.getAttributeValue(null, "count");
7121 if (countStr == null) {
7122 reportSettingsProblem(Log.WARN,
7123 "Error in package manager settings: <signatures> has"
7124 + " no count at " + parser.getPositionDescription());
7125 XmlUtils.skipCurrentTag(parser);
7126 }
7127 final int count = Integer.parseInt(countStr);
7128 mSignatures = new Signature[count];
7129 int pos = 0;
7130
7131 int outerDepth = parser.getDepth();
7132 int type;
7133 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7134 && (type != XmlPullParser.END_TAG
7135 || parser.getDepth() > outerDepth)) {
7136 if (type == XmlPullParser.END_TAG
7137 || type == XmlPullParser.TEXT) {
7138 continue;
7139 }
7140
7141 String tagName = parser.getName();
7142 if (tagName.equals("cert")) {
7143 if (pos < count) {
7144 String index = parser.getAttributeValue(null, "index");
7145 if (index != null) {
7146 try {
7147 int idx = Integer.parseInt(index);
7148 String key = parser.getAttributeValue(null, "key");
7149 if (key == null) {
7150 if (idx >= 0 && idx < pastSignatures.size()) {
7151 Signature sig = pastSignatures.get(idx);
7152 if (sig != null) {
7153 mSignatures[pos] = pastSignatures.get(idx);
7154 pos++;
7155 } else {
7156 reportSettingsProblem(Log.WARN,
7157 "Error in package manager settings: <cert> "
7158 + "index " + index + " is not defined at "
7159 + parser.getPositionDescription());
7160 }
7161 } else {
7162 reportSettingsProblem(Log.WARN,
7163 "Error in package manager settings: <cert> "
7164 + "index " + index + " is out of bounds at "
7165 + parser.getPositionDescription());
7166 }
7167 } else {
7168 while (pastSignatures.size() <= idx) {
7169 pastSignatures.add(null);
7170 }
7171 Signature sig = new Signature(key);
7172 pastSignatures.set(idx, sig);
7173 mSignatures[pos] = sig;
7174 pos++;
7175 }
7176 } catch (NumberFormatException e) {
7177 reportSettingsProblem(Log.WARN,
7178 "Error in package manager settings: <cert> "
7179 + "index " + index + " is not a number at "
7180 + parser.getPositionDescription());
7181 }
7182 } else {
7183 reportSettingsProblem(Log.WARN,
7184 "Error in package manager settings: <cert> has"
7185 + " no index at " + parser.getPositionDescription());
7186 }
7187 } else {
7188 reportSettingsProblem(Log.WARN,
7189 "Error in package manager settings: too "
7190 + "many <cert> tags, expected " + count
7191 + " at " + parser.getPositionDescription());
7192 }
7193 } else {
7194 reportSettingsProblem(Log.WARN,
7195 "Unknown element under <cert>: "
7196 + parser.getName());
7197 }
7198 XmlUtils.skipCurrentTag(parser);
7199 }
7200
7201 if (pos < count) {
7202 // Should never happen -- there is an error in the written
7203 // settings -- but if it does we don't want to generate
7204 // a bad array.
7205 Signature[] newSigs = new Signature[pos];
7206 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7207 mSignatures = newSigs;
7208 }
7209 }
7210
7211 /**
7212 * If any of the given 'sigs' is contained in the existing signatures,
7213 * then completely replace the current signatures with the ones in
7214 * 'sigs'. This is used for updating an existing package to a newly
7215 * installed version.
7216 */
7217 boolean updateSignatures(Signature[] sigs, boolean update) {
7218 if (mSignatures == null) {
7219 if (update) {
7220 assignSignatures(sigs);
7221 }
7222 return true;
7223 }
7224 if (sigs == null) {
7225 return false;
7226 }
7227
7228 for (int i=0; i<sigs.length; i++) {
7229 Signature sig = sigs[i];
7230 for (int j=0; j<mSignatures.length; j++) {
7231 if (mSignatures[j].equals(sig)) {
7232 if (update) {
7233 assignSignatures(sigs);
7234 }
7235 return true;
7236 }
7237 }
7238 }
7239 return false;
7240 }
7241
7242 /**
7243 * If any of the given 'sigs' is contained in the existing signatures,
7244 * then add in any new signatures found in 'sigs'. This is used for
7245 * including a new package into an existing shared user id.
7246 */
7247 boolean mergeSignatures(Signature[] sigs, boolean update) {
7248 if (mSignatures == null) {
7249 if (update) {
7250 assignSignatures(sigs);
7251 }
7252 return true;
7253 }
7254 if (sigs == null) {
7255 return false;
7256 }
7257
7258 Signature[] added = null;
7259 int addedCount = 0;
7260 boolean haveMatch = false;
7261 for (int i=0; i<sigs.length; i++) {
7262 Signature sig = sigs[i];
7263 boolean found = false;
7264 for (int j=0; j<mSignatures.length; j++) {
7265 if (mSignatures[j].equals(sig)) {
7266 found = true;
7267 haveMatch = true;
7268 break;
7269 }
7270 }
7271
7272 if (!found) {
7273 if (added == null) {
7274 added = new Signature[sigs.length];
7275 }
7276 added[i] = sig;
7277 addedCount++;
7278 }
7279 }
7280
7281 if (!haveMatch) {
7282 // Nothing matched -- reject the new signatures.
7283 return false;
7284 }
7285 if (added == null) {
7286 // Completely matched -- nothing else to do.
7287 return true;
7288 }
7289
7290 // Add additional signatures in.
7291 if (update) {
7292 Signature[] total = new Signature[addedCount+mSignatures.length];
7293 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7294 int j = mSignatures.length;
7295 for (int i=0; i<added.length; i++) {
7296 if (added[i] != null) {
7297 total[j] = added[i];
7298 j++;
7299 }
7300 }
7301 mSignatures = total;
7302 }
7303 return true;
7304 }
7305
7306 private void assignSignatures(Signature[] sigs) {
7307 if (sigs == null) {
7308 mSignatures = null;
7309 return;
7310 }
7311 mSignatures = new Signature[sigs.length];
7312 for (int i=0; i<sigs.length; i++) {
7313 mSignatures[i] = sigs[i];
7314 }
7315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007317 @Override
7318 public String toString() {
7319 StringBuffer buf = new StringBuffer(128);
7320 buf.append("PackageSignatures{");
7321 buf.append(Integer.toHexString(System.identityHashCode(this)));
7322 buf.append(" [");
7323 if (mSignatures != null) {
7324 for (int i=0; i<mSignatures.length; i++) {
7325 if (i > 0) buf.append(", ");
7326 buf.append(Integer.toHexString(
7327 System.identityHashCode(mSignatures[i])));
7328 }
7329 }
7330 buf.append("]}");
7331 return buf.toString();
7332 }
7333 }
7334
7335 static class PreferredActivity extends IntentFilter {
7336 final int mMatch;
7337 final String[] mSetPackages;
7338 final String[] mSetClasses;
7339 final String[] mSetComponents;
7340 final ComponentName mActivity;
7341 final String mShortActivity;
7342 String mParseError;
7343
7344 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7345 ComponentName activity) {
7346 super(filter);
7347 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7348 mActivity = activity;
7349 mShortActivity = activity.flattenToShortString();
7350 mParseError = null;
7351 if (set != null) {
7352 final int N = set.length;
7353 String[] myPackages = new String[N];
7354 String[] myClasses = new String[N];
7355 String[] myComponents = new String[N];
7356 for (int i=0; i<N; i++) {
7357 ComponentName cn = set[i];
7358 if (cn == null) {
7359 mSetPackages = null;
7360 mSetClasses = null;
7361 mSetComponents = null;
7362 return;
7363 }
7364 myPackages[i] = cn.getPackageName().intern();
7365 myClasses[i] = cn.getClassName().intern();
7366 myComponents[i] = cn.flattenToShortString().intern();
7367 }
7368 mSetPackages = myPackages;
7369 mSetClasses = myClasses;
7370 mSetComponents = myComponents;
7371 } else {
7372 mSetPackages = null;
7373 mSetClasses = null;
7374 mSetComponents = null;
7375 }
7376 }
7377
7378 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7379 IOException {
7380 mShortActivity = parser.getAttributeValue(null, "name");
7381 mActivity = ComponentName.unflattenFromString(mShortActivity);
7382 if (mActivity == null) {
7383 mParseError = "Bad activity name " + mShortActivity;
7384 }
7385 String matchStr = parser.getAttributeValue(null, "match");
7386 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7387 String setCountStr = parser.getAttributeValue(null, "set");
7388 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7389
7390 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7391 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7392 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7393
7394 int setPos = 0;
7395
7396 int outerDepth = parser.getDepth();
7397 int type;
7398 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7399 && (type != XmlPullParser.END_TAG
7400 || parser.getDepth() > outerDepth)) {
7401 if (type == XmlPullParser.END_TAG
7402 || type == XmlPullParser.TEXT) {
7403 continue;
7404 }
7405
7406 String tagName = parser.getName();
7407 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7408 // + parser.getDepth() + " tag=" + tagName);
7409 if (tagName.equals("set")) {
7410 String name = parser.getAttributeValue(null, "name");
7411 if (name == null) {
7412 if (mParseError == null) {
7413 mParseError = "No name in set tag in preferred activity "
7414 + mShortActivity;
7415 }
7416 } else if (setPos >= setCount) {
7417 if (mParseError == null) {
7418 mParseError = "Too many set tags in preferred activity "
7419 + mShortActivity;
7420 }
7421 } else {
7422 ComponentName cn = ComponentName.unflattenFromString(name);
7423 if (cn == null) {
7424 if (mParseError == null) {
7425 mParseError = "Bad set name " + name + " in preferred activity "
7426 + mShortActivity;
7427 }
7428 } else {
7429 myPackages[setPos] = cn.getPackageName();
7430 myClasses[setPos] = cn.getClassName();
7431 myComponents[setPos] = name;
7432 setPos++;
7433 }
7434 }
7435 XmlUtils.skipCurrentTag(parser);
7436 } else if (tagName.equals("filter")) {
7437 //Log.i(TAG, "Starting to parse filter...");
7438 readFromXml(parser);
7439 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7440 // + parser.getDepth() + " tag=" + parser.getName());
7441 } else {
7442 reportSettingsProblem(Log.WARN,
7443 "Unknown element under <preferred-activities>: "
7444 + parser.getName());
7445 XmlUtils.skipCurrentTag(parser);
7446 }
7447 }
7448
7449 if (setPos != setCount) {
7450 if (mParseError == null) {
7451 mParseError = "Not enough set tags (expected " + setCount
7452 + " but found " + setPos + ") in " + mShortActivity;
7453 }
7454 }
7455
7456 mSetPackages = myPackages;
7457 mSetClasses = myClasses;
7458 mSetComponents = myComponents;
7459 }
7460
7461 public void writeToXml(XmlSerializer serializer) throws IOException {
7462 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7463 serializer.attribute(null, "name", mShortActivity);
7464 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7465 serializer.attribute(null, "set", Integer.toString(NS));
7466 for (int s=0; s<NS; s++) {
7467 serializer.startTag(null, "set");
7468 serializer.attribute(null, "name", mSetComponents[s]);
7469 serializer.endTag(null, "set");
7470 }
7471 serializer.startTag(null, "filter");
7472 super.writeToXml(serializer);
7473 serializer.endTag(null, "filter");
7474 }
7475
7476 boolean sameSet(List<ResolveInfo> query, int priority) {
7477 if (mSetPackages == null) return false;
7478 final int NQ = query.size();
7479 final int NS = mSetPackages.length;
7480 int numMatch = 0;
7481 for (int i=0; i<NQ; i++) {
7482 ResolveInfo ri = query.get(i);
7483 if (ri.priority != priority) continue;
7484 ActivityInfo ai = ri.activityInfo;
7485 boolean good = false;
7486 for (int j=0; j<NS; j++) {
7487 if (mSetPackages[j].equals(ai.packageName)
7488 && mSetClasses[j].equals(ai.name)) {
7489 numMatch++;
7490 good = true;
7491 break;
7492 }
7493 }
7494 if (!good) return false;
7495 }
7496 return numMatch == NS;
7497 }
7498 }
7499
7500 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007501 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 HashSet<String> grantedPermissions = new HashSet<String>();
7504 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007507 setFlags(pkgFlags);
7508 }
7509
7510 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007511 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007512 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Oscar Montemayor1f4df902010-03-26 18:44:14 -07007513 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 }
7515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 /**
7518 * Settings base class for pending and resolved classes.
7519 */
7520 static class PackageSettingBase extends GrantedPermissions {
7521 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007522 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007523 File codePath;
7524 String codePathString;
7525 File resourcePath;
7526 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 private long timeStamp;
7528 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007529 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007531 boolean uidError;
7532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 PackageSignatures signatures = new PackageSignatures();
7534
7535 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007536 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538 /* Explicitly disabled components */
7539 HashSet<String> disabledComponents = new HashSet<String>(0);
7540 /* Explicitly enabled components */
7541 HashSet<String> enabledComponents = new HashSet<String>(0);
7542 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7543 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007544
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007545 PackageSettingBase origPackage;
7546
Jacek Surazski65e13172009-04-28 15:26:38 +02007547 /* package name of the app that installed this package */
7548 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007550 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007551 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 super(pkgFlags);
7553 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007554 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007555 init(codePath, resourcePath, pVersionCode);
7556 }
7557
7558 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007559 this.codePath = codePath;
7560 this.codePathString = codePath.toString();
7561 this.resourcePath = resourcePath;
7562 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007563 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007565
Jacek Surazski65e13172009-04-28 15:26:38 +02007566 public void setInstallerPackageName(String packageName) {
7567 installerPackageName = packageName;
7568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007569
Jacek Surazski65e13172009-04-28 15:26:38 +02007570 String getInstallerPackageName() {
7571 return installerPackageName;
7572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 public void setInstallStatus(int newStatus) {
7575 installStatus = newStatus;
7576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007578 public int getInstallStatus() {
7579 return installStatus;
7580 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 public void setTimeStamp(long newStamp) {
7583 if (newStamp != timeStamp) {
7584 timeStamp = newStamp;
7585 timeStampString = Long.toString(newStamp);
7586 }
7587 }
7588
7589 public void setTimeStamp(long newStamp, String newStampStr) {
7590 timeStamp = newStamp;
7591 timeStampString = newStampStr;
7592 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 public long getTimeStamp() {
7595 return timeStamp;
7596 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 public String getTimeStampStr() {
7599 return timeStampString;
7600 }
7601
7602 public void copyFrom(PackageSettingBase base) {
7603 grantedPermissions = base.grantedPermissions;
7604 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007606 timeStamp = base.timeStamp;
7607 timeStampString = base.timeStampString;
7608 signatures = base.signatures;
7609 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007610 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 disabledComponents = base.disabledComponents;
7612 enabledComponents = base.enabledComponents;
7613 enabled = base.enabled;
7614 installStatus = base.installStatus;
7615 }
7616
7617 void enableComponentLP(String componentClassName) {
7618 disabledComponents.remove(componentClassName);
7619 enabledComponents.add(componentClassName);
7620 }
7621
7622 void disableComponentLP(String componentClassName) {
7623 enabledComponents.remove(componentClassName);
7624 disabledComponents.add(componentClassName);
7625 }
7626
7627 void restoreComponentLP(String componentClassName) {
7628 enabledComponents.remove(componentClassName);
7629 disabledComponents.remove(componentClassName);
7630 }
7631
7632 int currentEnabledStateLP(String componentName) {
7633 if (enabledComponents.contains(componentName)) {
7634 return COMPONENT_ENABLED_STATE_ENABLED;
7635 } else if (disabledComponents.contains(componentName)) {
7636 return COMPONENT_ENABLED_STATE_DISABLED;
7637 } else {
7638 return COMPONENT_ENABLED_STATE_DEFAULT;
7639 }
7640 }
7641 }
7642
7643 /**
7644 * Settings data for a particular package we know about.
7645 */
7646 static final class PackageSetting extends PackageSettingBase {
7647 int userId;
7648 PackageParser.Package pkg;
7649 SharedUserSetting sharedUser;
7650
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007651 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007652 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007653 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 @Override
7657 public String toString() {
7658 return "PackageSetting{"
7659 + Integer.toHexString(System.identityHashCode(this))
7660 + " " + name + "/" + userId + "}";
7661 }
7662 }
7663
7664 /**
7665 * Settings data for a particular shared user ID we know about.
7666 */
7667 static final class SharedUserSetting extends GrantedPermissions {
7668 final String name;
7669 int userId;
7670 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7671 final PackageSignatures signatures = new PackageSignatures();
7672
7673 SharedUserSetting(String _name, int _pkgFlags) {
7674 super(_pkgFlags);
7675 name = _name;
7676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 @Override
7679 public String toString() {
7680 return "SharedUserSetting{"
7681 + Integer.toHexString(System.identityHashCode(this))
7682 + " " + name + "/" + userId + "}";
7683 }
7684 }
7685
7686 /**
7687 * Holds information about dynamic settings.
7688 */
7689 private static final class Settings {
7690 private final File mSettingsFilename;
7691 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007692 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 private final HashMap<String, PackageSetting> mPackages =
7694 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 // List of replaced system applications
7696 final HashMap<String, PackageSetting> mDisabledSysPackages =
7697 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699 // The user's preferred activities associated with particular intent
7700 // filters.
7701 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7702 new IntentResolver<PreferredActivity, PreferredActivity>() {
7703 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007704 protected String packageForFilter(PreferredActivity filter) {
7705 return filter.mActivity.getPackageName();
7706 }
7707 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007708 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007709 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007710 out.print(prefix); out.print(
7711 Integer.toHexString(System.identityHashCode(filter)));
7712 out.print(' ');
7713 out.print(filter.mActivity.flattenToShortString());
7714 out.print(" match=0x");
7715 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007717 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007719 out.print(prefix); out.print(" ");
7720 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 }
7722 }
7723 }
7724 };
7725 private final HashMap<String, SharedUserSetting> mSharedUsers =
7726 new HashMap<String, SharedUserSetting>();
7727 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7728 private final SparseArray<Object> mOtherUserIds =
7729 new SparseArray<Object>();
7730
7731 // For reading/writing settings file.
7732 private final ArrayList<Signature> mPastSignatures =
7733 new ArrayList<Signature>();
7734
7735 // Mapping from permission names to info about them.
7736 final HashMap<String, BasePermission> mPermissions =
7737 new HashMap<String, BasePermission>();
7738
7739 // Mapping from permission tree names to info about them.
7740 final HashMap<String, BasePermission> mPermissionTrees =
7741 new HashMap<String, BasePermission>();
7742
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007743 // Packages that have been uninstalled and still need their external
7744 // storage data deleted.
7745 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7746
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007747 // Packages that have been renamed since they were first installed.
7748 // Keys are the new names of the packages, values are the original
7749 // names. The packages appear everwhere else under their original
7750 // names.
7751 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 private final StringBuilder mReadMessages = new StringBuilder();
7754
7755 private static final class PendingPackage extends PackageSettingBase {
7756 final int sharedId;
7757
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007758 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007759 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007760 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 this.sharedId = sharedId;
7762 }
7763 }
7764 private final ArrayList<PendingPackage> mPendingPackages
7765 = new ArrayList<PendingPackage>();
7766
7767 Settings() {
7768 File dataDir = Environment.getDataDirectory();
7769 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007770 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 systemDir.mkdirs();
7772 FileUtils.setPermissions(systemDir.toString(),
7773 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7774 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7775 -1, -1);
7776 mSettingsFilename = new File(systemDir, "packages.xml");
7777 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007778 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 }
7780
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007781 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007782 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 int pkgFlags, boolean create, boolean add) {
7784 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007785 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007786 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 return p;
7788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007789
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007790 PackageSetting peekPackageLP(String name) {
7791 return mPackages.get(name);
7792 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 PackageSetting p = mPackages.get(name);
7794 if (p != null && p.codePath.getPath().equals(codePath)) {
7795 return p;
7796 }
7797 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007798 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 void setInstallStatus(String pkgName, int status) {
7802 PackageSetting p = mPackages.get(pkgName);
7803 if(p != null) {
7804 if(p.getInstallStatus() != status) {
7805 p.setInstallStatus(status);
7806 }
7807 }
7808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007809
Jacek Surazski65e13172009-04-28 15:26:38 +02007810 void setInstallerPackageName(String pkgName,
7811 String installerPkgName) {
7812 PackageSetting p = mPackages.get(pkgName);
7813 if(p != null) {
7814 p.setInstallerPackageName(installerPkgName);
7815 }
7816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007817
Jacek Surazski65e13172009-04-28 15:26:38 +02007818 String getInstallerPackageName(String pkgName) {
7819 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007820 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007821 }
7822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 int getInstallStatus(String pkgName) {
7824 PackageSetting p = mPackages.get(pkgName);
7825 if(p != null) {
7826 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 return -1;
7829 }
7830
7831 SharedUserSetting getSharedUserLP(String name,
7832 int pkgFlags, boolean create) {
7833 SharedUserSetting s = mSharedUsers.get(name);
7834 if (s == null) {
7835 if (!create) {
7836 return null;
7837 }
7838 s = new SharedUserSetting(name, pkgFlags);
7839 if (MULTIPLE_APPLICATION_UIDS) {
7840 s.userId = newUserIdLP(s);
7841 } else {
7842 s.userId = FIRST_APPLICATION_UID;
7843 }
7844 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7845 // < 0 means we couldn't assign a userid; fall out and return
7846 // s, which is currently null
7847 if (s.userId >= 0) {
7848 mSharedUsers.put(name, s);
7849 }
7850 }
7851
7852 return s;
7853 }
7854
7855 int disableSystemPackageLP(String name) {
7856 PackageSetting p = mPackages.get(name);
7857 if(p == null) {
7858 Log.w(TAG, "Package:"+name+" is not an installed package");
7859 return -1;
7860 }
7861 PackageSetting dp = mDisabledSysPackages.get(name);
7862 // always make sure the system package code and resource paths dont change
7863 if(dp == null) {
7864 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7865 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7866 }
7867 mDisabledSysPackages.put(name, p);
7868 }
7869 return removePackageLP(name);
7870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 PackageSetting enableSystemPackageLP(String name) {
7873 PackageSetting p = mDisabledSysPackages.get(name);
7874 if(p == null) {
7875 Log.w(TAG, "Package:"+name+" is not disabled");
7876 return null;
7877 }
7878 // Reset flag in ApplicationInfo object
7879 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7880 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7881 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007882 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007883 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 mDisabledSysPackages.remove(name);
7885 return ret;
7886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007887
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007888 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007889 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 PackageSetting p = mPackages.get(name);
7891 if (p != null) {
7892 if (p.userId == uid) {
7893 return p;
7894 }
7895 reportSettingsProblem(Log.ERROR,
7896 "Adding duplicate package, keeping first: " + name);
7897 return null;
7898 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007899 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 p.userId = uid;
7901 if (addUserIdLP(uid, p, name)) {
7902 mPackages.put(name, p);
7903 return p;
7904 }
7905 return null;
7906 }
7907
7908 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7909 SharedUserSetting s = mSharedUsers.get(name);
7910 if (s != null) {
7911 if (s.userId == uid) {
7912 return s;
7913 }
7914 reportSettingsProblem(Log.ERROR,
7915 "Adding duplicate shared user, keeping first: " + name);
7916 return null;
7917 }
7918 s = new SharedUserSetting(name, pkgFlags);
7919 s.userId = uid;
7920 if (addUserIdLP(uid, s, name)) {
7921 mSharedUsers.put(name, s);
7922 return s;
7923 }
7924 return null;
7925 }
7926
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007927 // Transfer ownership of permissions from one package to another.
7928 private void transferPermissions(String origPkg, String newPkg) {
7929 // Transfer ownership of permissions to the new package.
7930 for (int i=0; i<2; i++) {
7931 HashMap<String, BasePermission> permissions =
7932 i == 0 ? mPermissionTrees : mPermissions;
7933 for (BasePermission bp : permissions.values()) {
7934 if (origPkg.equals(bp.sourcePackage)) {
7935 if (DEBUG_UPGRADE) Log.v(TAG,
7936 "Moving permission " + bp.name
7937 + " from pkg " + bp.sourcePackage
7938 + " to " + newPkg);
7939 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007940 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007941 bp.perm = null;
7942 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007943 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007944 }
7945 bp.uid = 0;
7946 bp.gids = null;
7947 }
7948 }
7949 }
7950 }
7951
7952 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007953 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007954 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 PackageSetting p = mPackages.get(name);
7956 if (p != null) {
7957 if (!p.codePath.equals(codePath)) {
7958 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007959 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007960 // This is an updated system app with versions in both system
7961 // and data partition. Just let the most recent version
7962 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007963 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007964 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007965 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007966 // Just a change in the code path is not an issue, but
7967 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007968 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007969 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007971 }
7972 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 reportSettingsProblem(Log.WARN,
7974 "Package " + name + " shared user changed from "
7975 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7976 + " to "
7977 + (sharedUser != null ? sharedUser.name : "<nothing>")
7978 + "; replacing with new");
7979 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007980 } else {
7981 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7982 // If what we are scanning is a system package, then
7983 // make it so, regardless of whether it was previously
7984 // installed only in the data partition.
7985 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 }
7988 }
7989 if (p == null) {
7990 // Create a new PackageSettings entry. this can end up here because
7991 // of code path mismatch or user id mismatch of an updated system partition
7992 if (!create) {
7993 return null;
7994 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007995 if (origPackage != null) {
7996 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007997 p = new PackageSetting(origPackage.name, name, codePath,
7998 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007999 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8000 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008001 // Note that we will retain the new package's signature so
8002 // that we can keep its data.
8003 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008004 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008005 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008006 p.sharedUser = origPackage.sharedUser;
8007 p.userId = origPackage.userId;
8008 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008009 mRenamedPackages.put(name, origPackage.name);
8010 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008011 // Update new package state.
8012 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008014 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008015 p.setTimeStamp(codePath.lastModified());
8016 p.sharedUser = sharedUser;
8017 if (sharedUser != null) {
8018 p.userId = sharedUser.userId;
8019 } else if (MULTIPLE_APPLICATION_UIDS) {
8020 // Clone the setting here for disabled system packages
8021 PackageSetting dis = mDisabledSysPackages.get(name);
8022 if (dis != null) {
8023 // For disabled packages a new setting is created
8024 // from the existing user id. This still has to be
8025 // added to list of user id's
8026 // Copy signatures from previous setting
8027 if (dis.signatures.mSignatures != null) {
8028 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8029 }
8030 p.userId = dis.userId;
8031 // Clone permissions
8032 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008033 // Clone component info
8034 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8035 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8036 // Add new setting to list of user ids
8037 addUserIdLP(p.userId, p, name);
8038 } else {
8039 // Assign new user id
8040 p.userId = newUserIdLP(p);
8041 }
8042 } else {
8043 p.userId = FIRST_APPLICATION_UID;
8044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045 }
8046 if (p.userId < 0) {
8047 reportSettingsProblem(Log.WARN,
8048 "Package " + name + " could not be assigned a valid uid");
8049 return null;
8050 }
8051 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008052 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008054 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 }
8056 }
8057 return p;
8058 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008059
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008060 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008061 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008062 String codePath = pkg.applicationInfo.sourceDir;
8063 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008064 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008065 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008066 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008067 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008068 p.codePath = new File(codePath);
8069 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008070 }
8071 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008072 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008073 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008074 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008075 p.resourcePath = new File(resourcePath);
8076 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008077 }
8078 // Update version code if needed
8079 if (pkg.mVersionCode != p.versionCode) {
8080 p.versionCode = pkg.mVersionCode;
8081 }
8082 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8083 }
8084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 // Utility method that adds a PackageSetting to mPackages and
8086 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008087 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 SharedUserSetting sharedUser) {
8089 mPackages.put(name, p);
8090 if (sharedUser != null) {
8091 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8092 reportSettingsProblem(Log.ERROR,
8093 "Package " + p.name + " was user "
8094 + p.sharedUser + " but is now " + sharedUser
8095 + "; I am not changing its files so it will probably fail!");
8096 p.sharedUser.packages.remove(p);
8097 } else if (p.userId != sharedUser.userId) {
8098 reportSettingsProblem(Log.ERROR,
8099 "Package " + p.name + " was user id " + p.userId
8100 + " but is now user " + sharedUser
8101 + " with id " + sharedUser.userId
8102 + "; I am not changing its files so it will probably fail!");
8103 }
8104
8105 sharedUser.packages.add(p);
8106 p.sharedUser = sharedUser;
8107 p.userId = sharedUser.userId;
8108 }
8109 }
8110
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008111 /*
8112 * Update the shared user setting when a package using
8113 * specifying the shared user id is removed. The gids
8114 * associated with each permission of the deleted package
8115 * are removed from the shared user's gid list only if its
8116 * not in use by other permissions of packages in the
8117 * shared user setting.
8118 */
8119 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008120 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008121 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 return;
8123 }
8124 // No sharedUserId
8125 if (deletedPs.sharedUser == null) {
8126 return;
8127 }
8128 SharedUserSetting sus = deletedPs.sharedUser;
8129 // Update permissions
8130 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8131 boolean used = false;
8132 if (!sus.grantedPermissions.contains (eachPerm)) {
8133 continue;
8134 }
8135 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008136 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008137 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008138 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 used = true;
8140 break;
8141 }
8142 }
8143 if (!used) {
8144 // can safely delete this permission from list
8145 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008146 }
8147 }
8148 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008149 int newGids[] = globalGids;
8150 for (String eachPerm : sus.grantedPermissions) {
8151 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008152 if (bp != null) {
8153 newGids = appendInts(newGids, bp.gids);
8154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 }
8156 sus.gids = newGids;
8157 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 private int removePackageLP(String name) {
8160 PackageSetting p = mPackages.get(name);
8161 if (p != null) {
8162 mPackages.remove(name);
8163 if (p.sharedUser != null) {
8164 p.sharedUser.packages.remove(p);
8165 if (p.sharedUser.packages.size() == 0) {
8166 mSharedUsers.remove(p.sharedUser.name);
8167 removeUserIdLP(p.sharedUser.userId);
8168 return p.sharedUser.userId;
8169 }
8170 } else {
8171 removeUserIdLP(p.userId);
8172 return p.userId;
8173 }
8174 }
8175 return -1;
8176 }
8177
8178 private boolean addUserIdLP(int uid, Object obj, Object name) {
8179 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8180 return false;
8181 }
8182
8183 if (uid >= FIRST_APPLICATION_UID) {
8184 int N = mUserIds.size();
8185 final int index = uid - FIRST_APPLICATION_UID;
8186 while (index >= N) {
8187 mUserIds.add(null);
8188 N++;
8189 }
8190 if (mUserIds.get(index) != null) {
8191 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008192 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 + " name=" + name);
8194 return false;
8195 }
8196 mUserIds.set(index, obj);
8197 } else {
8198 if (mOtherUserIds.get(uid) != null) {
8199 reportSettingsProblem(Log.ERROR,
8200 "Adding duplicate shared id: " + uid
8201 + " name=" + name);
8202 return false;
8203 }
8204 mOtherUserIds.put(uid, obj);
8205 }
8206 return true;
8207 }
8208
8209 public Object getUserIdLP(int uid) {
8210 if (uid >= FIRST_APPLICATION_UID) {
8211 int N = mUserIds.size();
8212 final int index = uid - FIRST_APPLICATION_UID;
8213 return index < N ? mUserIds.get(index) : null;
8214 } else {
8215 return mOtherUserIds.get(uid);
8216 }
8217 }
8218
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008219 private Set<String> findPackagesWithFlag(int flag) {
8220 Set<String> ret = new HashSet<String>();
8221 for (PackageSetting ps : mPackages.values()) {
8222 // Has to match atleast all the flag bits set on flag
8223 if ((ps.pkgFlags & flag) == flag) {
8224 ret.add(ps.name);
8225 }
8226 }
8227 return ret;
8228 }
8229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008230 private void removeUserIdLP(int uid) {
8231 if (uid >= FIRST_APPLICATION_UID) {
8232 int N = mUserIds.size();
8233 final int index = uid - FIRST_APPLICATION_UID;
8234 if (index < N) mUserIds.set(index, null);
8235 } else {
8236 mOtherUserIds.remove(uid);
8237 }
8238 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 void writeLP() {
8241 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8242
8243 // Keep the old settings around until we know the new ones have
8244 // been successfully written.
8245 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008246 // Presence of backup settings file indicates that we failed
8247 // to persist settings earlier. So preserve the older
8248 // backup for future reference since the current settings
8249 // might have been corrupted.
8250 if (!mBackupSettingsFilename.exists()) {
8251 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008252 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008253 return;
8254 }
8255 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008256 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008257 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 }
8260
8261 mPastSignatures.clear();
8262
8263 try {
8264 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8265
8266 //XmlSerializer serializer = XmlUtils.serializerInstance();
8267 XmlSerializer serializer = new FastXmlSerializer();
8268 serializer.setOutput(str, "utf-8");
8269 serializer.startDocument(null, true);
8270 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8271
8272 serializer.startTag(null, "packages");
8273
8274 serializer.startTag(null, "permission-trees");
8275 for (BasePermission bp : mPermissionTrees.values()) {
8276 writePermission(serializer, bp);
8277 }
8278 serializer.endTag(null, "permission-trees");
8279
8280 serializer.startTag(null, "permissions");
8281 for (BasePermission bp : mPermissions.values()) {
8282 writePermission(serializer, bp);
8283 }
8284 serializer.endTag(null, "permissions");
8285
8286 for (PackageSetting pkg : mPackages.values()) {
8287 writePackage(serializer, pkg);
8288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8291 writeDisabledSysPackage(serializer, pkg);
8292 }
8293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 serializer.startTag(null, "preferred-activities");
8295 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8296 serializer.startTag(null, "item");
8297 pa.writeToXml(serializer);
8298 serializer.endTag(null, "item");
8299 }
8300 serializer.endTag(null, "preferred-activities");
8301
8302 for (SharedUserSetting usr : mSharedUsers.values()) {
8303 serializer.startTag(null, "shared-user");
8304 serializer.attribute(null, "name", usr.name);
8305 serializer.attribute(null, "userId",
8306 Integer.toString(usr.userId));
8307 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8308 serializer.startTag(null, "perms");
8309 for (String name : usr.grantedPermissions) {
8310 serializer.startTag(null, "item");
8311 serializer.attribute(null, "name", name);
8312 serializer.endTag(null, "item");
8313 }
8314 serializer.endTag(null, "perms");
8315 serializer.endTag(null, "shared-user");
8316 }
8317
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008318 if (mPackagesToBeCleaned.size() > 0) {
8319 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8320 serializer.startTag(null, "cleaning-package");
8321 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8322 serializer.endTag(null, "cleaning-package");
8323 }
8324 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008325
8326 if (mRenamedPackages.size() > 0) {
8327 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8328 serializer.startTag(null, "renamed-package");
8329 serializer.attribute(null, "new", e.getKey());
8330 serializer.attribute(null, "old", e.getValue());
8331 serializer.endTag(null, "renamed-package");
8332 }
8333 }
8334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008335 serializer.endTag(null, "packages");
8336
8337 serializer.endDocument();
8338
8339 str.flush();
8340 str.close();
8341
8342 // New settings successfully written, old ones are no longer
8343 // needed.
8344 mBackupSettingsFilename.delete();
8345 FileUtils.setPermissions(mSettingsFilename.toString(),
8346 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8347 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8348 |FileUtils.S_IROTH,
8349 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008350
8351 // Write package list file now, use a JournaledFile.
8352 //
8353 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8354 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8355
8356 str = new FileOutputStream(journal.chooseForWrite());
8357 try {
8358 StringBuilder sb = new StringBuilder();
8359 for (PackageSetting pkg : mPackages.values()) {
8360 ApplicationInfo ai = pkg.pkg.applicationInfo;
8361 String dataPath = ai.dataDir;
8362 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8363
8364 // Avoid any application that has a space in its path
8365 // or that is handled by the system.
8366 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8367 continue;
8368
8369 // we store on each line the following information for now:
8370 //
8371 // pkgName - package name
8372 // userId - application-specific user id
8373 // debugFlag - 0 or 1 if the package is debuggable.
8374 // dataPath - path to package's data path
8375 //
8376 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8377 //
8378 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8379 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8380 // system/core/run-as/run-as.c
8381 //
8382 sb.setLength(0);
8383 sb.append(ai.packageName);
8384 sb.append(" ");
8385 sb.append((int)ai.uid);
8386 sb.append(isDebug ? " 1 " : " 0 ");
8387 sb.append(dataPath);
8388 sb.append("\n");
8389 str.write(sb.toString().getBytes());
8390 }
8391 str.flush();
8392 str.close();
8393 journal.commit();
8394 }
8395 catch (Exception e) {
8396 journal.rollback();
8397 }
8398
8399 FileUtils.setPermissions(mPackageListFilename.toString(),
8400 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8401 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8402 |FileUtils.S_IROTH,
8403 -1, -1);
8404
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008405 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406
8407 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008408 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 -08008409 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008410 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 -08008411 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008412 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008413 if (mSettingsFilename.exists()) {
8414 if (!mSettingsFilename.delete()) {
8415 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8416 }
8417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 //Debug.stopMethodTracing();
8419 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008420
8421 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008422 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423 serializer.startTag(null, "updated-package");
8424 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008425 if (pkg.realName != null) {
8426 serializer.attribute(null, "realName", pkg.realName);
8427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008428 serializer.attribute(null, "codePath", pkg.codePathString);
8429 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008430 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008431 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8432 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8433 }
8434 if (pkg.sharedUser == null) {
8435 serializer.attribute(null, "userId",
8436 Integer.toString(pkg.userId));
8437 } else {
8438 serializer.attribute(null, "sharedUserId",
8439 Integer.toString(pkg.userId));
8440 }
8441 serializer.startTag(null, "perms");
8442 if (pkg.sharedUser == null) {
8443 // If this is a shared user, the permissions will
8444 // be written there. We still need to write an
8445 // empty permissions list so permissionsFixed will
8446 // be set.
8447 for (final String name : pkg.grantedPermissions) {
8448 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008449 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450 // We only need to write signature or system permissions but this wont
8451 // match the semantics of grantedPermissions. So write all permissions.
8452 serializer.startTag(null, "item");
8453 serializer.attribute(null, "name", name);
8454 serializer.endTag(null, "item");
8455 }
8456 }
8457 }
8458 serializer.endTag(null, "perms");
8459 serializer.endTag(null, "updated-package");
8460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008461
8462 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008463 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 serializer.startTag(null, "package");
8465 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008466 if (pkg.realName != null) {
8467 serializer.attribute(null, "realName", pkg.realName);
8468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008469 serializer.attribute(null, "codePath", pkg.codePathString);
8470 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8471 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8472 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008473 serializer.attribute(null, "flags",
8474 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008476 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 if (pkg.sharedUser == null) {
8478 serializer.attribute(null, "userId",
8479 Integer.toString(pkg.userId));
8480 } else {
8481 serializer.attribute(null, "sharedUserId",
8482 Integer.toString(pkg.userId));
8483 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008484 if (pkg.uidError) {
8485 serializer.attribute(null, "uidError", "true");
8486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8488 serializer.attribute(null, "enabled",
8489 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8490 ? "true" : "false");
8491 }
8492 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8493 serializer.attribute(null, "installStatus", "false");
8494 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008495 if (pkg.installerPackageName != null) {
8496 serializer.attribute(null, "installer", pkg.installerPackageName);
8497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8499 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8500 serializer.startTag(null, "perms");
8501 if (pkg.sharedUser == null) {
8502 // If this is a shared user, the permissions will
8503 // be written there. We still need to write an
8504 // empty permissions list so permissionsFixed will
8505 // be set.
8506 for (final String name : pkg.grantedPermissions) {
8507 serializer.startTag(null, "item");
8508 serializer.attribute(null, "name", name);
8509 serializer.endTag(null, "item");
8510 }
8511 }
8512 serializer.endTag(null, "perms");
8513 }
8514 if (pkg.disabledComponents.size() > 0) {
8515 serializer.startTag(null, "disabled-components");
8516 for (final String name : pkg.disabledComponents) {
8517 serializer.startTag(null, "item");
8518 serializer.attribute(null, "name", name);
8519 serializer.endTag(null, "item");
8520 }
8521 serializer.endTag(null, "disabled-components");
8522 }
8523 if (pkg.enabledComponents.size() > 0) {
8524 serializer.startTag(null, "enabled-components");
8525 for (final String name : pkg.enabledComponents) {
8526 serializer.startTag(null, "item");
8527 serializer.attribute(null, "name", name);
8528 serializer.endTag(null, "item");
8529 }
8530 serializer.endTag(null, "enabled-components");
8531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 serializer.endTag(null, "package");
8534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 void writePermission(XmlSerializer serializer, BasePermission bp)
8537 throws XmlPullParserException, java.io.IOException {
8538 if (bp.type != BasePermission.TYPE_BUILTIN
8539 && bp.sourcePackage != null) {
8540 serializer.startTag(null, "item");
8541 serializer.attribute(null, "name", bp.name);
8542 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008543 if (bp.protectionLevel !=
8544 PermissionInfo.PROTECTION_NORMAL) {
8545 serializer.attribute(null, "protection",
8546 Integer.toString(bp.protectionLevel));
8547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 if (DEBUG_SETTINGS) Log.v(TAG,
8549 "Writing perm: name=" + bp.name + " type=" + bp.type);
8550 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8551 PermissionInfo pi = bp.perm != null ? bp.perm.info
8552 : bp.pendingInfo;
8553 if (pi != null) {
8554 serializer.attribute(null, "type", "dynamic");
8555 if (pi.icon != 0) {
8556 serializer.attribute(null, "icon",
8557 Integer.toString(pi.icon));
8558 }
8559 if (pi.nonLocalizedLabel != null) {
8560 serializer.attribute(null, "label",
8561 pi.nonLocalizedLabel.toString());
8562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 }
8564 }
8565 serializer.endTag(null, "item");
8566 }
8567 }
8568
8569 String getReadMessagesLP() {
8570 return mReadMessages.toString();
8571 }
8572
Oscar Montemayora8529f62009-11-18 10:14:20 -08008573 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8575 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008576 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 while(its.hasNext()) {
8578 String key = its.next();
8579 PackageSetting ps = mPackages.get(key);
8580 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008581 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 }
8583 }
8584 return ret;
8585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 boolean readLP() {
8588 FileInputStream str = null;
8589 if (mBackupSettingsFilename.exists()) {
8590 try {
8591 str = new FileInputStream(mBackupSettingsFilename);
8592 mReadMessages.append("Reading from backup settings file\n");
8593 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008594 if (mSettingsFilename.exists()) {
8595 // If both the backup and settings file exist, we
8596 // ignore the settings since it might have been
8597 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008598 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008599 mSettingsFilename.delete();
8600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 } catch (java.io.IOException e) {
8602 // We'll try for the normal settings file.
8603 }
8604 }
8605
8606 mPastSignatures.clear();
8607
8608 try {
8609 if (str == null) {
8610 if (!mSettingsFilename.exists()) {
8611 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008612 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 return false;
8614 }
8615 str = new FileInputStream(mSettingsFilename);
8616 }
8617 XmlPullParser parser = Xml.newPullParser();
8618 parser.setInput(str, null);
8619
8620 int type;
8621 while ((type=parser.next()) != XmlPullParser.START_TAG
8622 && type != XmlPullParser.END_DOCUMENT) {
8623 ;
8624 }
8625
8626 if (type != XmlPullParser.START_TAG) {
8627 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008628 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 return false;
8630 }
8631
8632 int outerDepth = parser.getDepth();
8633 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8634 && (type != XmlPullParser.END_TAG
8635 || parser.getDepth() > outerDepth)) {
8636 if (type == XmlPullParser.END_TAG
8637 || type == XmlPullParser.TEXT) {
8638 continue;
8639 }
8640
8641 String tagName = parser.getName();
8642 if (tagName.equals("package")) {
8643 readPackageLP(parser);
8644 } else if (tagName.equals("permissions")) {
8645 readPermissionsLP(mPermissions, parser);
8646 } else if (tagName.equals("permission-trees")) {
8647 readPermissionsLP(mPermissionTrees, parser);
8648 } else if (tagName.equals("shared-user")) {
8649 readSharedUserLP(parser);
8650 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008651 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 } else if (tagName.equals("preferred-activities")) {
8653 readPreferredActivitiesLP(parser);
8654 } else if(tagName.equals("updated-package")) {
8655 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008656 } else if (tagName.equals("cleaning-package")) {
8657 String name = parser.getAttributeValue(null, "name");
8658 if (name != null) {
8659 mPackagesToBeCleaned.add(name);
8660 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008661 } else if (tagName.equals("renamed-package")) {
8662 String nname = parser.getAttributeValue(null, "new");
8663 String oname = parser.getAttributeValue(null, "old");
8664 if (nname != null && oname != null) {
8665 mRenamedPackages.put(nname, oname);
8666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008668 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 + parser.getName());
8670 XmlUtils.skipCurrentTag(parser);
8671 }
8672 }
8673
8674 str.close();
8675
8676 } catch(XmlPullParserException e) {
8677 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008678 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008679
8680 } catch(java.io.IOException e) {
8681 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008682 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683
8684 }
8685
8686 int N = mPendingPackages.size();
8687 for (int i=0; i<N; i++) {
8688 final PendingPackage pp = mPendingPackages.get(i);
8689 Object idObj = getUserIdLP(pp.sharedId);
8690 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008691 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008693 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008695 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 + pp.name);
8697 continue;
8698 }
8699 p.copyFrom(pp);
8700 } else if (idObj != null) {
8701 String msg = "Bad package setting: package " + pp.name
8702 + " has shared uid " + pp.sharedId
8703 + " that is not a shared uid\n";
8704 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008705 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 } else {
8707 String msg = "Bad package setting: package " + pp.name
8708 + " has shared uid " + pp.sharedId
8709 + " that is not defined\n";
8710 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008711 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 }
8713 }
8714 mPendingPackages.clear();
8715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 mReadMessages.append("Read completed successfully: "
8717 + mPackages.size() + " packages, "
8718 + mSharedUsers.size() + " shared uids\n");
8719
8720 return true;
8721 }
8722
8723 private int readInt(XmlPullParser parser, String ns, String name,
8724 int defValue) {
8725 String v = parser.getAttributeValue(ns, name);
8726 try {
8727 if (v == null) {
8728 return defValue;
8729 }
8730 return Integer.parseInt(v);
8731 } catch (NumberFormatException e) {
8732 reportSettingsProblem(Log.WARN,
8733 "Error in package manager settings: attribute " +
8734 name + " has bad integer value " + v + " at "
8735 + parser.getPositionDescription());
8736 }
8737 return defValue;
8738 }
8739
8740 private void readPermissionsLP(HashMap<String, BasePermission> out,
8741 XmlPullParser parser)
8742 throws IOException, XmlPullParserException {
8743 int outerDepth = parser.getDepth();
8744 int type;
8745 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8746 && (type != XmlPullParser.END_TAG
8747 || parser.getDepth() > outerDepth)) {
8748 if (type == XmlPullParser.END_TAG
8749 || type == XmlPullParser.TEXT) {
8750 continue;
8751 }
8752
8753 String tagName = parser.getName();
8754 if (tagName.equals("item")) {
8755 String name = parser.getAttributeValue(null, "name");
8756 String sourcePackage = parser.getAttributeValue(null, "package");
8757 String ptype = parser.getAttributeValue(null, "type");
8758 if (name != null && sourcePackage != null) {
8759 boolean dynamic = "dynamic".equals(ptype);
8760 BasePermission bp = new BasePermission(name, sourcePackage,
8761 dynamic
8762 ? BasePermission.TYPE_DYNAMIC
8763 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008764 bp.protectionLevel = readInt(parser, null, "protection",
8765 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 if (dynamic) {
8767 PermissionInfo pi = new PermissionInfo();
8768 pi.packageName = sourcePackage.intern();
8769 pi.name = name.intern();
8770 pi.icon = readInt(parser, null, "icon", 0);
8771 pi.nonLocalizedLabel = parser.getAttributeValue(
8772 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008773 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 bp.pendingInfo = pi;
8775 }
8776 out.put(bp.name, bp);
8777 } else {
8778 reportSettingsProblem(Log.WARN,
8779 "Error in package manager settings: permissions has"
8780 + " no name at " + parser.getPositionDescription());
8781 }
8782 } else {
8783 reportSettingsProblem(Log.WARN,
8784 "Unknown element reading permissions: "
8785 + parser.getName() + " at "
8786 + parser.getPositionDescription());
8787 }
8788 XmlUtils.skipCurrentTag(parser);
8789 }
8790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008793 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008795 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 String codePathStr = parser.getAttributeValue(null, "codePath");
8797 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008798 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 resourcePathStr = codePathStr;
8800 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008801 String version = parser.getAttributeValue(null, "version");
8802 int versionCode = 0;
8803 if (version != null) {
8804 try {
8805 versionCode = Integer.parseInt(version);
8806 } catch (NumberFormatException e) {
8807 }
8808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008810 int pkgFlags = 0;
8811 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008812 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008813 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008814 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 String timeStampStr = parser.getAttributeValue(null, "ts");
8816 if (timeStampStr != null) {
8817 try {
8818 long timeStamp = Long.parseLong(timeStampStr);
8819 ps.setTimeStamp(timeStamp, timeStampStr);
8820 } catch (NumberFormatException e) {
8821 }
8822 }
8823 String idStr = parser.getAttributeValue(null, "userId");
8824 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8825 if(ps.userId <= 0) {
8826 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8827 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8828 }
8829 int outerDepth = parser.getDepth();
8830 int type;
8831 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8832 && (type != XmlPullParser.END_TAG
8833 || parser.getDepth() > outerDepth)) {
8834 if (type == XmlPullParser.END_TAG
8835 || type == XmlPullParser.TEXT) {
8836 continue;
8837 }
8838
8839 String tagName = parser.getName();
8840 if (tagName.equals("perms")) {
8841 readGrantedPermissionsLP(parser,
8842 ps.grantedPermissions);
8843 } else {
8844 reportSettingsProblem(Log.WARN,
8845 "Unknown element under <updated-package>: "
8846 + parser.getName());
8847 XmlUtils.skipCurrentTag(parser);
8848 }
8849 }
8850 mDisabledSysPackages.put(name, ps);
8851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 private void readPackageLP(XmlPullParser parser)
8854 throws XmlPullParserException, IOException {
8855 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008856 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008857 String idStr = null;
8858 String sharedIdStr = null;
8859 String codePathStr = null;
8860 String resourcePathStr = null;
8861 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008862 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008863 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 int pkgFlags = 0;
8865 String timeStampStr;
8866 long timeStamp = 0;
8867 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008868 String version = null;
8869 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 try {
8871 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008872 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008874 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8876 codePathStr = parser.getAttributeValue(null, "codePath");
8877 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008878 version = parser.getAttributeValue(null, "version");
8879 if (version != null) {
8880 try {
8881 versionCode = Integer.parseInt(version);
8882 } catch (NumberFormatException e) {
8883 }
8884 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008885 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008886
8887 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008889 try {
8890 pkgFlags = Integer.parseInt(systemStr);
8891 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 }
8893 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008894 // For backward compatibility
8895 systemStr = parser.getAttributeValue(null, "system");
8896 if (systemStr != null) {
8897 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8898 } else {
8899 // Old settings that don't specify system... just treat
8900 // them as system, good enough.
8901 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 }
8904 timeStampStr = parser.getAttributeValue(null, "ts");
8905 if (timeStampStr != null) {
8906 try {
8907 timeStamp = Long.parseLong(timeStampStr);
8908 } catch (NumberFormatException e) {
8909 }
8910 }
8911 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8912 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8913 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8914 if (resourcePathStr == null) {
8915 resourcePathStr = codePathStr;
8916 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008917 if (realName != null) {
8918 realName = realName.intern();
8919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 if (name == null) {
8921 reportSettingsProblem(Log.WARN,
8922 "Error in package manager settings: <package> has no name at "
8923 + parser.getPositionDescription());
8924 } else if (codePathStr == null) {
8925 reportSettingsProblem(Log.WARN,
8926 "Error in package manager settings: <package> has no codePath at "
8927 + parser.getPositionDescription());
8928 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008929 packageSetting = addPackageLP(name.intern(), realName,
8930 new File(codePathStr), new File(resourcePathStr),
8931 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8933 + ": userId=" + userId + " pkg=" + packageSetting);
8934 if (packageSetting == null) {
8935 reportSettingsProblem(Log.ERROR,
8936 "Failure adding uid " + userId
8937 + " while parsing settings at "
8938 + parser.getPositionDescription());
8939 } else {
8940 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8941 }
8942 } else if (sharedIdStr != null) {
8943 userId = sharedIdStr != null
8944 ? Integer.parseInt(sharedIdStr) : 0;
8945 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008946 packageSetting = new PendingPackage(name.intern(), realName,
8947 new File(codePathStr), new File(resourcePathStr),
8948 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8950 mPendingPackages.add((PendingPackage) packageSetting);
8951 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8952 + ": sharedUserId=" + userId + " pkg="
8953 + packageSetting);
8954 } else {
8955 reportSettingsProblem(Log.WARN,
8956 "Error in package manager settings: package "
8957 + name + " has bad sharedId " + sharedIdStr
8958 + " at " + parser.getPositionDescription());
8959 }
8960 } else {
8961 reportSettingsProblem(Log.WARN,
8962 "Error in package manager settings: package "
8963 + name + " has bad userId " + idStr + " at "
8964 + parser.getPositionDescription());
8965 }
8966 } catch (NumberFormatException e) {
8967 reportSettingsProblem(Log.WARN,
8968 "Error in package manager settings: package "
8969 + name + " has bad userId " + idStr + " at "
8970 + parser.getPositionDescription());
8971 }
8972 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008973 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008974 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 final String enabledStr = parser.getAttributeValue(null, "enabled");
8976 if (enabledStr != null) {
8977 if (enabledStr.equalsIgnoreCase("true")) {
8978 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8979 } else if (enabledStr.equalsIgnoreCase("false")) {
8980 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8981 } else if (enabledStr.equalsIgnoreCase("default")) {
8982 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8983 } else {
8984 reportSettingsProblem(Log.WARN,
8985 "Error in package manager settings: package "
8986 + name + " has bad enabled value: " + idStr
8987 + " at " + parser.getPositionDescription());
8988 }
8989 } else {
8990 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8991 }
8992 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8993 if (installStatusStr != null) {
8994 if (installStatusStr.equalsIgnoreCase("false")) {
8995 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8996 } else {
8997 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8998 }
8999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 int outerDepth = parser.getDepth();
9002 int type;
9003 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9004 && (type != XmlPullParser.END_TAG
9005 || parser.getDepth() > outerDepth)) {
9006 if (type == XmlPullParser.END_TAG
9007 || type == XmlPullParser.TEXT) {
9008 continue;
9009 }
9010
9011 String tagName = parser.getName();
9012 if (tagName.equals("disabled-components")) {
9013 readDisabledComponentsLP(packageSetting, parser);
9014 } else if (tagName.equals("enabled-components")) {
9015 readEnabledComponentsLP(packageSetting, parser);
9016 } else if (tagName.equals("sigs")) {
9017 packageSetting.signatures.readXml(parser, mPastSignatures);
9018 } else if (tagName.equals("perms")) {
9019 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009020 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009021 packageSetting.permissionsFixed = true;
9022 } else {
9023 reportSettingsProblem(Log.WARN,
9024 "Unknown element under <package>: "
9025 + parser.getName());
9026 XmlUtils.skipCurrentTag(parser);
9027 }
9028 }
9029 } else {
9030 XmlUtils.skipCurrentTag(parser);
9031 }
9032 }
9033
9034 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9035 XmlPullParser parser)
9036 throws IOException, XmlPullParserException {
9037 int outerDepth = parser.getDepth();
9038 int type;
9039 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9040 && (type != XmlPullParser.END_TAG
9041 || parser.getDepth() > outerDepth)) {
9042 if (type == XmlPullParser.END_TAG
9043 || type == XmlPullParser.TEXT) {
9044 continue;
9045 }
9046
9047 String tagName = parser.getName();
9048 if (tagName.equals("item")) {
9049 String name = parser.getAttributeValue(null, "name");
9050 if (name != null) {
9051 packageSetting.disabledComponents.add(name.intern());
9052 } else {
9053 reportSettingsProblem(Log.WARN,
9054 "Error in package manager settings: <disabled-components> has"
9055 + " no name at " + parser.getPositionDescription());
9056 }
9057 } else {
9058 reportSettingsProblem(Log.WARN,
9059 "Unknown element under <disabled-components>: "
9060 + parser.getName());
9061 }
9062 XmlUtils.skipCurrentTag(parser);
9063 }
9064 }
9065
9066 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9067 XmlPullParser parser)
9068 throws IOException, XmlPullParserException {
9069 int outerDepth = parser.getDepth();
9070 int type;
9071 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9072 && (type != XmlPullParser.END_TAG
9073 || parser.getDepth() > outerDepth)) {
9074 if (type == XmlPullParser.END_TAG
9075 || type == XmlPullParser.TEXT) {
9076 continue;
9077 }
9078
9079 String tagName = parser.getName();
9080 if (tagName.equals("item")) {
9081 String name = parser.getAttributeValue(null, "name");
9082 if (name != null) {
9083 packageSetting.enabledComponents.add(name.intern());
9084 } else {
9085 reportSettingsProblem(Log.WARN,
9086 "Error in package manager settings: <enabled-components> has"
9087 + " no name at " + parser.getPositionDescription());
9088 }
9089 } else {
9090 reportSettingsProblem(Log.WARN,
9091 "Unknown element under <enabled-components>: "
9092 + parser.getName());
9093 }
9094 XmlUtils.skipCurrentTag(parser);
9095 }
9096 }
9097
9098 private void readSharedUserLP(XmlPullParser parser)
9099 throws XmlPullParserException, IOException {
9100 String name = null;
9101 String idStr = null;
9102 int pkgFlags = 0;
9103 SharedUserSetting su = null;
9104 try {
9105 name = parser.getAttributeValue(null, "name");
9106 idStr = parser.getAttributeValue(null, "userId");
9107 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9108 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9109 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9110 }
9111 if (name == null) {
9112 reportSettingsProblem(Log.WARN,
9113 "Error in package manager settings: <shared-user> has no name at "
9114 + parser.getPositionDescription());
9115 } else if (userId == 0) {
9116 reportSettingsProblem(Log.WARN,
9117 "Error in package manager settings: shared-user "
9118 + name + " has bad userId " + idStr + " at "
9119 + parser.getPositionDescription());
9120 } else {
9121 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9122 reportSettingsProblem(Log.ERROR,
9123 "Occurred while parsing settings at "
9124 + parser.getPositionDescription());
9125 }
9126 }
9127 } catch (NumberFormatException e) {
9128 reportSettingsProblem(Log.WARN,
9129 "Error in package manager settings: package "
9130 + name + " has bad userId " + idStr + " at "
9131 + parser.getPositionDescription());
9132 };
9133
9134 if (su != null) {
9135 int outerDepth = parser.getDepth();
9136 int type;
9137 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9138 && (type != XmlPullParser.END_TAG
9139 || parser.getDepth() > outerDepth)) {
9140 if (type == XmlPullParser.END_TAG
9141 || type == XmlPullParser.TEXT) {
9142 continue;
9143 }
9144
9145 String tagName = parser.getName();
9146 if (tagName.equals("sigs")) {
9147 su.signatures.readXml(parser, mPastSignatures);
9148 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009149 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 } else {
9151 reportSettingsProblem(Log.WARN,
9152 "Unknown element under <shared-user>: "
9153 + parser.getName());
9154 XmlUtils.skipCurrentTag(parser);
9155 }
9156 }
9157
9158 } else {
9159 XmlUtils.skipCurrentTag(parser);
9160 }
9161 }
9162
9163 private void readGrantedPermissionsLP(XmlPullParser parser,
9164 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9165 int outerDepth = parser.getDepth();
9166 int type;
9167 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9168 && (type != XmlPullParser.END_TAG
9169 || parser.getDepth() > outerDepth)) {
9170 if (type == XmlPullParser.END_TAG
9171 || type == XmlPullParser.TEXT) {
9172 continue;
9173 }
9174
9175 String tagName = parser.getName();
9176 if (tagName.equals("item")) {
9177 String name = parser.getAttributeValue(null, "name");
9178 if (name != null) {
9179 outPerms.add(name.intern());
9180 } else {
9181 reportSettingsProblem(Log.WARN,
9182 "Error in package manager settings: <perms> has"
9183 + " no name at " + parser.getPositionDescription());
9184 }
9185 } else {
9186 reportSettingsProblem(Log.WARN,
9187 "Unknown element under <perms>: "
9188 + parser.getName());
9189 }
9190 XmlUtils.skipCurrentTag(parser);
9191 }
9192 }
9193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 private void readPreferredActivitiesLP(XmlPullParser parser)
9195 throws XmlPullParserException, IOException {
9196 int outerDepth = parser.getDepth();
9197 int type;
9198 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9199 && (type != XmlPullParser.END_TAG
9200 || parser.getDepth() > outerDepth)) {
9201 if (type == XmlPullParser.END_TAG
9202 || type == XmlPullParser.TEXT) {
9203 continue;
9204 }
9205
9206 String tagName = parser.getName();
9207 if (tagName.equals("item")) {
9208 PreferredActivity pa = new PreferredActivity(parser);
9209 if (pa.mParseError == null) {
9210 mPreferredActivities.addFilter(pa);
9211 } else {
9212 reportSettingsProblem(Log.WARN,
9213 "Error in package manager settings: <preferred-activity> "
9214 + pa.mParseError + " at "
9215 + parser.getPositionDescription());
9216 }
9217 } else {
9218 reportSettingsProblem(Log.WARN,
9219 "Unknown element under <preferred-activities>: "
9220 + parser.getName());
9221 XmlUtils.skipCurrentTag(parser);
9222 }
9223 }
9224 }
9225
9226 // Returns -1 if we could not find an available UserId to assign
9227 private int newUserIdLP(Object obj) {
9228 // Let's be stupidly inefficient for now...
9229 final int N = mUserIds.size();
9230 for (int i=0; i<N; i++) {
9231 if (mUserIds.get(i) == null) {
9232 mUserIds.set(i, obj);
9233 return FIRST_APPLICATION_UID + i;
9234 }
9235 }
9236
9237 // None left?
9238 if (N >= MAX_APPLICATION_UIDS) {
9239 return -1;
9240 }
9241
9242 mUserIds.add(obj);
9243 return FIRST_APPLICATION_UID + N;
9244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 public PackageSetting getDisabledSystemPkg(String name) {
9247 synchronized(mPackages) {
9248 PackageSetting ps = mDisabledSysPackages.get(name);
9249 return ps;
9250 }
9251 }
9252
9253 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9254 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9255 if (Config.LOGV) {
9256 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9257 + " componentName = " + componentInfo.name);
9258 Log.v(TAG, "enabledComponents: "
9259 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9260 Log.v(TAG, "disabledComponents: "
9261 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9262 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009263 if (packageSettings == null) {
9264 if (false) {
9265 Log.w(TAG, "WAITING FOR DEBUGGER");
9266 Debug.waitForDebugger();
9267 Log.i(TAG, "We will crash!");
9268 }
9269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9271 || ((componentInfo.enabled
9272 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9273 || (componentInfo.applicationInfo.enabled
9274 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9275 && !packageSettings.disabledComponents.contains(componentInfo.name))
9276 || packageSettings.enabledComponents.contains(componentInfo.name));
9277 }
9278 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009279
9280 // ------- apps on sdcard specific code -------
9281 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009282 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009283 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009284 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009285 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009286
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009287 private String getEncryptKey() {
9288 try {
9289 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9290 if (sdEncKey == null) {
9291 sdEncKey = SystemKeyStore.getInstance().
9292 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9293 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009294 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009295 return null;
9296 }
9297 }
9298 return sdEncKey;
9299 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009300 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009301 return null;
9302 }
9303 }
9304
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009305 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009306 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009307 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009308 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009309 if (list != null) {
9310 int idx = 0;
9311 int idList[] = new int[MAX_CONTAINERS];
9312 boolean neverFound = true;
9313 for (String name : list) {
9314 // Ignore null entries
9315 if (name == null) {
9316 continue;
9317 }
9318 int sidx = name.indexOf(prefix);
9319 if (sidx == -1) {
9320 // Not a temp file. just ignore
9321 continue;
9322 }
9323 String subStr = name.substring(sidx + prefix.length());
9324 idList[idx] = -1;
9325 if (subStr != null) {
9326 try {
9327 int cid = Integer.parseInt(subStr);
9328 idList[idx++] = cid;
9329 neverFound = false;
9330 } catch (NumberFormatException e) {
9331 }
9332 }
9333 }
9334 if (!neverFound) {
9335 // Sort idList
9336 Arrays.sort(idList);
9337 for (int j = 1; j <= idList.length; j++) {
9338 if (idList[j-1] != j) {
9339 tmpIdx = j;
9340 break;
9341 }
9342 }
9343 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009344 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009345 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009346 }
9347
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009348 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009349 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009350 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009351 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9352 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9353 throw new SecurityException("Media status can only be updated by the system");
9354 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009355 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009356 Log.i(TAG, "Updating external media status from " +
9357 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9358 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009359 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9360 mediaStatus+", mMediaMounted=" + mMediaMounted);
9361 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009362 if (reportStatus) {
9363 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9364 }
9365 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009366 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009367 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009368 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009369 // Queue up an async operation since the package installation may take a little while.
9370 mHandler.post(new Runnable() {
9371 public void run() {
9372 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009373 try {
9374 updateExternalMediaStatusInner(mediaStatus);
9375 } finally {
9376 if (reportStatus) {
9377 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9378 }
9379 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009380 }
9381 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009382 }
9383
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009384 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009385 // If we are up here that means there are packages to be
9386 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009387 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009388 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009389 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009390 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009391 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009392
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009393 int uidList[] = new int[list.length];
9394 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009395 HashSet<String> removeCids = new HashSet<String>();
9396 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009397 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009398 for (String cid : list) {
9399 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009400 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9401 boolean failed = true;
9402 try {
9403 String pkgName = args.getPackageName();
9404 if (pkgName == null) {
9405 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009406 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009407 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9408 PackageSetting ps = mSettings.mPackages.get(pkgName);
9409 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009410 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009411 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9412 " corresponds to pkg : " + pkgName +
9413 " at code path: " + ps.codePathString);
9414 // We do have a valid package installed on sdcard
9415 processCids.put(args, ps.codePathString);
9416 failed = false;
9417 int uid = ps.userId;
9418 if (uid != -1) {
9419 uidList[num++] = uid;
9420 }
9421 }
9422 } finally {
9423 if (failed) {
9424 // Stale container on sdcard. Just delete
9425 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9426 removeCids.add(cid);
9427 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009428 }
9429 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009430 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009431 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009432 int uidArr[] = null;
9433 if (num > 0) {
9434 // Sort uid list
9435 Arrays.sort(uidList, 0, num);
9436 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009437 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009438 uidArr[0] = uidList[0];
9439 int di = 0;
9440 for (int i = 1; i < num; i++) {
9441 if (uidList[i-1] != uidList[i]) {
9442 uidArr[di++] = uidList[i];
9443 }
9444 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009445 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009446 // Process packages with valid entries.
9447 if (mediaStatus) {
9448 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009449 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009450 startCleaningPackages();
9451 } else {
9452 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009453 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009454 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009455 }
9456
9457 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9458 ArrayList<String> pkgList, int uidArr[]) {
9459 int size = pkgList.size();
9460 if (size > 0) {
9461 // Send broadcasts here
9462 Bundle extras = new Bundle();
9463 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9464 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009465 if (uidArr != null) {
9466 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9467 }
9468 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9469 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009470 sendPackageBroadcast(action, null, extras);
9471 }
9472 }
9473
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009474 /*
9475 * Look at potentially valid container ids from processCids
9476 * If package information doesn't match the one on record
9477 * or package scanning fails, the cid is added to list of
9478 * removeCids and cleaned up. Since cleaning up containers
9479 * involves destroying them, we do not want any parse
9480 * references to such stale containers. So force gc's
9481 * to avoid unnecessary crashes.
9482 */
9483 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009484 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009485 ArrayList<String> pkgList = new ArrayList<String>();
9486 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009487 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009488 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009489 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009490 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9491 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009492 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009493 try {
9494 // Make sure there are no container errors first.
9495 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9496 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009497 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009498 " when installing from sdcard");
9499 continue;
9500 }
9501 // Check code path here.
9502 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009503 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009504 " does not match one in settings " + codePath);
9505 continue;
9506 }
9507 // Parse package
9508 int parseFlags = PackageParser.PARSE_CHATTY |
9509 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9510 PackageParser pp = new PackageParser(codePath);
9511 pp.setSeparateProcesses(mSeparateProcesses);
9512 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9513 codePath, mMetrics, parseFlags);
9514 pp = null;
9515 doGc = true;
9516 // Check for parse errors
9517 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009518 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009519 + args.cid + " from " + args.cachePath);
9520 continue;
9521 }
9522 setApplicationInfoPaths(pkg, codePath, codePath);
9523 synchronized (mInstallLock) {
9524 // Scan the package
9525 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9526 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 retCode = PackageManager.INSTALL_SUCCEEDED;
9528 pkgList.add(pkg.packageName);
9529 // Post process args
9530 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9531 }
9532 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009533 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009534 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009535 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009536 }
9537
9538 } finally {
9539 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9540 // Don't destroy container here. Wait till gc clears things up.
9541 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009542 }
9543 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009544 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009545 synchronized (mPackages) {
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009546 // Make sure group IDs have been assigned, and any permission
9547 // changes in other apps are accounted for
9548 updatePermissionsLP(null, null, true, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009549 // Persist settings
9550 mSettings.writeLP();
9551 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009552 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009553 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9555 }
9556 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009557 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009558 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009559 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009560 if (removeCids != null) {
9561 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009562 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009563 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009564 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009565 }
9566
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009568 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009569 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009570 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009571 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 Set<SdInstallArgs> keys = processCids.keySet();
9573 for (SdInstallArgs args : keys) {
9574 String cid = args.cid;
9575 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009576 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009577 // Delete package internally
9578 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9579 synchronized (mInstallLock) {
9580 boolean res = deletePackageLI(pkgName, false,
9581 PackageManager.DONT_DELETE_DATA, outInfo);
9582 if (res) {
9583 pkgList.add(pkgName);
9584 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009585 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009586 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009587 }
9588 }
9589 }
9590 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009591 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009592 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009593 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009594 // Force gc
9595 Runtime.getRuntime().gc();
9596 // Just unmount all valid containers.
9597 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009598 synchronized (mInstallLock) {
9599 args.doPostDeleteLI(false);
9600 }
9601 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009602 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009603
9604 public void movePackage(final String packageName,
9605 final IPackageMoveObserver observer, final int flags) {
9606 if (packageName == null) {
9607 return;
9608 }
9609 mContext.enforceCallingOrSelfPermission(
9610 android.Manifest.permission.MOVE_PACKAGE, null);
9611 int returnCode = PackageManager.MOVE_SUCCEEDED;
9612 int currFlags = 0;
9613 int newFlags = 0;
9614 synchronized (mPackages) {
9615 PackageParser.Package pkg = mPackages.get(packageName);
9616 if (pkg == null) {
9617 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9618 }
9619 // Disable moving fwd locked apps and system packages
9620 if (pkg.applicationInfo != null &&
9621 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009622 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009623 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9624 } else if (pkg.applicationInfo != null &&
9625 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009626 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009627 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9628 } else {
9629 // Find install location first
9630 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9631 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009632 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009633 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9634 } else {
9635 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9636 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009637 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009638 PackageManager.INSTALL_EXTERNAL : 0;
9639 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009640 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009641 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9642 }
9643 }
9644 }
9645 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9646 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9647 } else {
9648 Message msg = mHandler.obtainMessage(INIT_COPY);
9649 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9650 pkg.applicationInfo.publicSourceDir);
9651 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9652 packageName);
9653 msg.obj = mp;
9654 mHandler.sendMessage(msg);
9655 }
9656 }
9657 }
9658
9659 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9660 // Queue up an async operation since the package deletion may take a little while.
9661 mHandler.post(new Runnable() {
9662 public void run() {
9663 mHandler.removeCallbacks(this);
9664 int returnCode = currentStatus;
9665 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9666 if (moveSucceeded) {
9667 int uid = -1;
9668 synchronized (mPackages) {
9669 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9670 }
9671 ArrayList<String> pkgList = new ArrayList<String>();
9672 pkgList.add(mp.packageName);
9673 int uidArr[] = new int[] { uid };
9674 // Send resources unavailable broadcast
9675 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9676
9677 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009678 synchronized (mInstallLock) {
9679 synchronized (mPackages) {
9680 PackageParser.Package pkg = mPackages.get(mp.packageName);
9681 if (pkg != null) {
9682 String oldCodePath = pkg.mPath;
9683 String newCodePath = mp.targetArgs.getCodePath();
9684 String newResPath = mp.targetArgs.getResourcePath();
9685 pkg.mPath = newCodePath;
9686 // Move dex files around
9687 if (moveDexFilesLI(pkg)
9688 != PackageManager.INSTALL_SUCCEEDED) {
9689 // Moving of dex files failed. Set
9690 // error code and abort move.
9691 pkg.mPath = pkg.mScanPath;
9692 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9693 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009694 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009695 pkg.mScanPath = newCodePath;
9696 pkg.applicationInfo.sourceDir = newCodePath;
9697 pkg.applicationInfo.publicSourceDir = newResPath;
9698 PackageSetting ps = (PackageSetting) pkg.mExtras;
9699 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9700 ps.codePathString = ps.codePath.getPath();
9701 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9702 ps.resourcePathString = ps.resourcePath.getPath();
9703 // Set the application info flag correctly.
9704 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9705 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9706 } else {
9707 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9708 }
9709 ps.setFlags(pkg.applicationInfo.flags);
9710 mAppDirs.remove(oldCodePath);
9711 mAppDirs.put(newCodePath, pkg);
9712 // Persist settings
9713 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009714 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009715 }
9716 }
9717 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009718 // Send resources available broadcast
9719 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009720 }
9721 if (!moveSucceeded){
9722 // Clean up failed installation
9723 if (mp.targetArgs != null) {
9724 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009725 returnCode);
9726 }
9727 } else {
9728 // Force a gc to clear things up.
9729 Runtime.getRuntime().gc();
9730 // Delete older code
9731 synchronized (mInstallLock) {
9732 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009733 }
9734 }
9735 IPackageMoveObserver observer = mp.observer;
9736 if (observer != null) {
9737 try {
9738 observer.packageMoved(mp.packageName, returnCode);
9739 } catch (RemoteException e) {
9740 Log.i(TAG, "Observer no longer exists.");
9741 }
9742 }
9743 }
9744 });
9745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746}