blob: 7cd058a4153dfbdad2be339238c7e6e7a9c6739b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070038import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080039import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070044import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.IPackageDataObserver;
46import android.content.pm.IPackageDeleteObserver;
47import android.content.pm.IPackageInstallObserver;
48import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080049import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.content.pm.IPackageStatsObserver;
51import android.content.pm.InstrumentationInfo;
52import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080053import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
55import android.content.pm.PackageStats;
56import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.pm.PackageParser;
60import android.content.pm.PermissionInfo;
61import android.content.pm.PermissionGroupInfo;
62import android.content.pm.ProviderInfo;
63import android.content.pm.ResolveInfo;
64import android.content.pm.ServiceInfo;
65import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.net.Uri;
67import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070068import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080070import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080072import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070073import android.os.Looper;
74import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Parcel;
76import android.os.RemoteException;
77import android.os.Environment;
78import android.os.FileObserver;
79import android.os.FileUtils;
80import android.os.Handler;
81import android.os.ParcelFileDescriptor;
82import android.os.Process;
83import android.os.ServiceManager;
84import android.os.SystemClock;
85import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080086import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.util.*;
88import android.view.Display;
89import android.view.WindowManager;
90
91import java.io.File;
92import java.io.FileDescriptor;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileOutputStream;
96import java.io.FileReader;
97import java.io.FilenameFilter;
98import java.io.IOException;
99import java.io.InputStream;
100import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800101import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800102import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
104import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700105import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Collections;
107import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800108import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Enumeration;
110import java.util.HashMap;
111import java.util.HashSet;
112import java.util.Iterator;
113import java.util.List;
114import java.util.Map;
115import java.util.Set;
116import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800117import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.zip.ZipFile;
119import java.util.zip.ZipOutputStream;
120
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700121/**
122 * Keep track of all those .apks everywhere.
123 *
124 * This is very central to the platform's security; please run the unit
125 * tests whenever making modifications here:
126 *
127mmm frameworks/base/tests/AndroidTests
128adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
129adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
130 *
131 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132class PackageManagerService extends IPackageManager.Stub {
133 private static final String TAG = "PackageManager";
134 private static final boolean DEBUG_SETTINGS = false;
135 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800136 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800137 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
139 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
140 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400141 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int FIRST_APPLICATION_UID =
143 Process.FIRST_APPLICATION_UID;
144 private static final int MAX_APPLICATION_UIDS = 1000;
145
146 private static final boolean SHOW_INFO = false;
147
148 private static final boolean GET_CERTIFICATES = true;
149
150 private static final int REMOVE_EVENTS =
151 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
152 private static final int ADD_EVENTS =
153 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
154
155 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800156 // Suffix used during package installation when copying/moving
157 // package apks to install directory.
158 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800160 /**
161 * Indicates the state of installation. Used by PackageManager to
162 * figure out incomplete installations. Say a package is being installed
163 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
164 * the package installation is successful or unsuccesful lin which case
165 * the PackageManager will no longer maintain state information associated
166 * with the package. If some exception(like device freeze or battery being
167 * pulled out) occurs during installation of a package, the PackageManager
168 * needs this information to clean up the previously failed installation.
169 */
170 private static final int PKG_INSTALL_INCOMPLETE = 0;
171 private static final int PKG_INSTALL_COMPLETE = 1;
172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final int SCAN_MONITOR = 1<<0;
174 static final int SCAN_NO_DEX = 1<<1;
175 static final int SCAN_FORCE_DEX = 1<<2;
176 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800177 static final int SCAN_NEW_INSTALL = 1<<4;
178 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800180 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
181 "com.android.defcontainer",
182 "com.android.defcontainer.DefaultContainerService");
183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
185 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700186 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn851a5412009-05-08 12:06:44 -0700188 final int mSdkVersion = Build.VERSION.SDK_INT;
189 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
190 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 final Context mContext;
193 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700194 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 final DisplayMetrics mMetrics;
196 final int mDefParseFlags;
197 final String[] mSeparateProcesses;
198
199 // This is where all application persistent data goes.
200 final File mAppDataDir;
201
202 // This is the object monitoring the framework dir.
203 final FileObserver mFrameworkInstallObserver;
204
205 // This is the object monitoring the system app dir.
206 final FileObserver mSystemInstallObserver;
207
208 // This is the object monitoring mAppInstallDir.
209 final FileObserver mAppInstallObserver;
210
211 // This is the object monitoring mDrmAppPrivateInstallDir.
212 final FileObserver mDrmAppInstallObserver;
213
214 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
215 // LOCK HELD. Can be called with mInstallLock held.
216 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 final File mFrameworkDir;
219 final File mSystemAppDir;
220 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700221 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
223 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
224 // apps.
225 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // Lock for state used when installing and doing other long running
230 // operations. Methods that must be called with this lock held have
231 // the prefix "LI".
232 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // These are the directories in the 3rd party applications installed dir
235 // that we have currently loaded packages from. Keys are the application's
236 // installed zip file (absolute codePath), and values are Package.
237 final HashMap<String, PackageParser.Package> mAppDirs =
238 new HashMap<String, PackageParser.Package>();
239
240 // Information for the parser to write more useful error messages.
241 File mScanningPath;
242 int mLastScanError;
243
244 final int[] mOutPermissions = new int[3];
245
246 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // Keys are String (package name), values are Package. This also serves
249 // as the lock for the global state. Methods that must be called with
250 // this lock held have the prefix "LP".
251 final HashMap<String, PackageParser.Package> mPackages =
252 new HashMap<String, PackageParser.Package>();
253
254 final Settings mSettings;
255 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256
257 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
258 int[] mGlobalGids;
259
260 // These are the built-in uid -> permission mappings that were read from the
261 // etc/permissions.xml file.
262 final SparseArray<HashSet<String>> mSystemPermissions =
263 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // These are the built-in shared libraries that were read from the
266 // etc/permissions.xml file.
267 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
Dianne Hackborn49237342009-08-27 20:08:01 -0700269 // Temporary for building the final shared libraries for an .apk.
270 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800271
Dianne Hackborn49237342009-08-27 20:08:01 -0700272 // These are the features this devices supports that were read from the
273 // etc/permissions.xml file.
274 final HashMap<String, FeatureInfo> mAvailableFeatures =
275 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277 // All available activities, for your resolving pleasure.
278 final ActivityIntentResolver mActivities =
279 new ActivityIntentResolver();
280
281 // All available receivers, for your resolving pleasure.
282 final ActivityIntentResolver mReceivers =
283 new ActivityIntentResolver();
284
285 // All available services, for your resolving pleasure.
286 final ServiceIntentResolver mServices = new ServiceIntentResolver();
287
288 // Keys are String (provider class name), values are Provider.
289 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
290 new HashMap<ComponentName, PackageParser.Provider>();
291
292 // Mapping from provider base names (first directory in content URI codePath)
293 // to the provider information.
294 final HashMap<String, PackageParser.Provider> mProviders =
295 new HashMap<String, PackageParser.Provider>();
296
297 // Mapping from instrumentation class names to info about them.
298 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
299 new HashMap<ComponentName, PackageParser.Instrumentation>();
300
301 // Mapping from permission names to info about them.
302 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
303 new HashMap<String, PackageParser.PermissionGroup>();
304
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800305 // Packages whose data we have transfered into another package, thus
306 // should no longer exist.
307 final HashSet<String> mTransferedPackages = new HashSet<String>();
308
Dianne Hackborn854060af2009-07-09 18:14:31 -0700309 // Broadcast actions that are only available to the system.
310 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 boolean mSystemReady;
313 boolean mSafeMode;
314 boolean mHasSystemUidErrors;
315
316 ApplicationInfo mAndroidApplication;
317 final ActivityInfo mResolveActivity = new ActivityInfo();
318 final ResolveInfo mResolveInfo = new ResolveInfo();
319 ComponentName mResolveComponentName;
320 PackageParser.Package mPlatformPackage;
321
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700322 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800323 final HashMap<String, ArrayList<String>> mPendingBroadcasts
324 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800325 // Service Connection to remote media container service to copy
326 // package uri's from external media onto secure containers
327 // or internal storage.
328 private IMediaContainerService mContainerService = null;
329
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700330 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800331 static final int MCS_BOUND = 3;
332 static final int END_COPY = 4;
333 static final int INIT_COPY = 5;
334 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800335 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800336 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800337 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800338 static final int MCS_RECONNECT = 10;
339 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700340 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700341 static final int WRITE_SETTINGS = 13;
342
343 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800344
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700345 // Delay time in millisecs
346 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347 final private DefaultContainerConnection mDefContainerConn =
348 new DefaultContainerConnection();
349 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800350 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 IMediaContainerService imcs =
353 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800354 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800355 }
356
357 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800358 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800359 }
360 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700361
Christopher Tate1bb69062010-02-19 17:02:12 -0800362 // Recordkeeping of restore-after-install operations that are currently in flight
363 // between the Package Manager and the Backup Manager
364 class PostInstallData {
365 public InstallArgs args;
366 public PackageInstalledInfo res;
367
368 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
369 args = _a;
370 res = _r;
371 }
372 };
373 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
374 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
375
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700376 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800377 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800378 final ArrayList<HandlerParams> mPendingInstalls =
379 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380
381 private boolean connectToService() {
382 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
383 " DefaultContainerService");
384 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700385 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800386 if (mContext.bindService(service, mDefContainerConn,
387 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700388 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800389 mBound = true;
390 return true;
391 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700392 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800393 return false;
394 }
395
396 private void disconnectService() {
397 mContainerService = null;
398 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800400 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700401 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800403
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700404 PackageHandler(Looper looper) {
405 super(looper);
406 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700408 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 try {
410 doHandleMessage(msg);
411 } finally {
412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
413 }
414 }
415
416 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700417 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800418 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800420 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800421 int idx = mPendingInstalls.size();
422 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
423 // If a bind was already initiated we dont really
424 // need to do anything. The pending install
425 // will be processed later on.
426 if (!mBound) {
427 // If this is the only one pending we might
428 // have to bind to the service again.
429 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800430 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800431 params.serviceError();
432 return;
433 } else {
434 // Once we bind to the service, the first
435 // pending request will be processed.
436 mPendingInstalls.add(idx, params);
437 }
438 } else {
439 mPendingInstalls.add(idx, params);
440 // Already bound to the service. Just make
441 // sure we trigger off processing the first request.
442 if (idx == 0) {
443 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800444 }
445 }
446 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800447 }
448 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800449 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800450 if (msg.obj != null) {
451 mContainerService = (IMediaContainerService) msg.obj;
452 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 if (mContainerService == null) {
454 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800455 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 for (HandlerParams params : mPendingInstalls) {
457 mPendingInstalls.remove(0);
458 // Indicate service bind error
459 params.serviceError();
460 }
461 mPendingInstalls.clear();
462 } else if (mPendingInstalls.size() > 0) {
463 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800464 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800465 params.startCopy();
466 }
467 } else {
468 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800469 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 }
471 break;
472 }
473 case MCS_RECONNECT : {
474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
475 if (mPendingInstalls.size() > 0) {
476 if (mBound) {
477 disconnectService();
478 }
479 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 for (HandlerParams params : mPendingInstalls) {
482 mPendingInstalls.remove(0);
483 // Indicate service bind error
484 params.serviceError();
485 }
486 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800487 }
488 }
489 break;
490 }
491 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
493 // Delete pending install
494 if (mPendingInstalls.size() > 0) {
495 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800496 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800497 if (mPendingInstalls.size() == 0) {
498 if (mBound) {
499 disconnectService();
500 }
501 } else {
502 // There are more pending requests in queue.
503 // Just post MCS_BOUND message to trigger processing
504 // of next pending install.
505 mHandler.sendEmptyMessage(MCS_BOUND);
506 }
507 break;
508 }
509 case MCS_GIVE_UP: {
510 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
511 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 break;
513 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700514 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800515 String packages[];
516 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700517 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700518 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700520 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800521 if (mPendingBroadcasts == null) {
522 return;
523 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700524 size = mPendingBroadcasts.size();
525 if (size <= 0) {
526 // Nothing to be done. Just return
527 return;
528 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800529 packages = new String[size];
530 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 Iterator<HashMap.Entry<String, ArrayList<String>>>
533 it = mPendingBroadcasts.entrySet().iterator();
534 int i = 0;
535 while (it.hasNext() && i < size) {
536 HashMap.Entry<String, ArrayList<String>> ent = it.next();
537 packages[i] = ent.getKey();
538 components[i] = ent.getValue();
539 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800541 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 mPendingBroadcasts.clear();
545 }
546 // Send broadcasts
547 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800548 sendPackageChangedBroadcast(packages[i], true,
549 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700550 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700551 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 break;
553 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800554 case START_CLEANING_PACKAGE: {
555 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700556 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800557 synchronized (mPackages) {
558 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
559 mSettings.mPackagesToBeCleaned.add(packageName);
560 }
561 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700562 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800563 startCleaningPackages();
564 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800565 case POST_INSTALL: {
566 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
567 PostInstallData data = mRunningInstalls.get(msg.arg1);
568 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800569 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800570
571 if (data != null) {
572 InstallArgs args = data.args;
573 PackageInstalledInfo res = data.res;
574
575 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
576 res.removedInfo.sendBroadcast(false, true);
577 Bundle extras = new Bundle(1);
578 extras.putInt(Intent.EXTRA_UID, res.uid);
579 final boolean update = res.removedInfo.removedPackage != null;
580 if (update) {
581 extras.putBoolean(Intent.EXTRA_REPLACING, true);
582 }
583 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
584 res.pkg.applicationInfo.packageName,
585 extras);
586 if (update) {
587 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
588 res.pkg.applicationInfo.packageName,
589 extras);
590 }
591 if (res.removedInfo.args != null) {
592 // Remove the replaced package's older resources safely now
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800593 deleteOld = true;
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 }
595 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800596 // Force a gc to clear up things
Christopher Tate1bb69062010-02-19 17:02:12 -0800597 Runtime.getRuntime().gc();
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800598 // We delete after a gc for applications on sdcard.
599 if (deleteOld) {
600 synchronized (mInstallLock) {
601 res.removedInfo.args.doPostDeleteLI(true);
602 }
603 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800604 if (args.observer != null) {
605 try {
606 args.observer.packageInstalled(res.name, res.returnCode);
607 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800608 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800609 }
610 }
611 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800612 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800613 }
614 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700615 case UPDATED_MEDIA_STATUS: {
616 try {
617 PackageHelper.getMountService().finishMediaUpdate();
618 } catch (RemoteException e) {
619 Log.e(TAG, "MountService not running?");
620 }
621 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700622 case WRITE_SETTINGS: {
623 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
624 synchronized (mPackages) {
625 removeMessages(WRITE_SETTINGS);
626 mSettings.writeLP();
627 }
628 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
629 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700630 }
631 }
632 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800633
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700634 void scheduleWriteSettingsLocked() {
635 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
636 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
637 }
638 }
639
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800640 static boolean installOnSd(int flags) {
641 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700642 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800643 return false;
644 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700645 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
646 return true;
647 }
648 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800649 }
650
651 static boolean isFwdLocked(int flags) {
652 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
653 return true;
654 }
655 return false;
656 }
657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 public static final IPackageManager main(Context context, boolean factoryTest) {
659 PackageManagerService m = new PackageManagerService(context, factoryTest);
660 ServiceManager.addService("package", m);
661 return m;
662 }
663
664 static String[] splitString(String str, char sep) {
665 int count = 1;
666 int i = 0;
667 while ((i=str.indexOf(sep, i)) >= 0) {
668 count++;
669 i++;
670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 String[] res = new String[count];
673 i=0;
674 count = 0;
675 int lastI=0;
676 while ((i=str.indexOf(sep, i)) >= 0) {
677 res[count] = str.substring(lastI, i);
678 count++;
679 i++;
680 lastI = i;
681 }
682 res[count] = str.substring(lastI, str.length());
683 return res;
684 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800687 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800691 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 mContext = context;
695 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700696 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 mMetrics = new DisplayMetrics();
698 mSettings = new Settings();
699 mSettings.addSharedUserLP("android.uid.system",
700 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
701 mSettings.addSharedUserLP("android.uid.phone",
702 MULTIPLE_APPLICATION_UIDS
703 ? RADIO_UID : FIRST_APPLICATION_UID,
704 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400705 mSettings.addSharedUserLP("android.uid.log",
706 MULTIPLE_APPLICATION_UIDS
707 ? LOG_UID : FIRST_APPLICATION_UID,
708 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709
710 String separateProcesses = SystemProperties.get("debug.separate_processes");
711 if (separateProcesses != null && separateProcesses.length() > 0) {
712 if ("*".equals(separateProcesses)) {
713 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
714 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800715 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 } else {
717 mDefParseFlags = 0;
718 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800719 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 + separateProcesses);
721 }
722 } else {
723 mDefParseFlags = 0;
724 mSeparateProcesses = null;
725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 Installer installer = new Installer();
728 // Little hacky thing to check if installd is here, to determine
729 // whether we are running on the simulator and thus need to take
730 // care of building the /data file structure ourself.
731 // (apparently the sim now has a working installer)
732 if (installer.ping() && Process.supportsProcesses()) {
733 mInstaller = installer;
734 } else {
735 mInstaller = null;
736 }
737
738 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
739 Display d = wm.getDefaultDisplay();
740 d.getMetrics(mMetrics);
741
742 synchronized (mInstallLock) {
743 synchronized (mPackages) {
744 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700745 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 File dataDir = Environment.getDataDirectory();
748 mAppDataDir = new File(dataDir, "data");
749 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
750
751 if (mInstaller == null) {
752 // Make sure these dirs exist, when we are running in
753 // the simulator.
754 // Make a wide-open directory for random misc stuff.
755 File miscDir = new File(dataDir, "misc");
756 miscDir.mkdirs();
757 mAppDataDir.mkdirs();
758 mDrmAppPrivateInstallDir.mkdirs();
759 }
760
761 readPermissions();
762
763 mRestoredSettings = mSettings.readLP();
764 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
766 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800768
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800769 // Set flag to monitor and not change apk file paths when
770 // scanning install directories.
771 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700772 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800773 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800774 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700780 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700783 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 /**
786 * Out of paranoia, ensure that everything in the boot class
787 * path has been dexed.
788 */
789 String bootClassPath = System.getProperty("java.boot.class.path");
790 if (bootClassPath != null) {
791 String[] paths = splitString(bootClassPath, ':');
792 for (int i=0; i<paths.length; i++) {
793 try {
794 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
795 libFiles.add(paths[i]);
796 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700797 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 }
799 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800800 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 }
804 }
805 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800806 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 /**
810 * Also ensure all external libraries have had dexopt run on them.
811 */
812 if (mSharedLibraries.size() > 0) {
813 Iterator<String> libs = mSharedLibraries.values().iterator();
814 while (libs.hasNext()) {
815 String lib = libs.next();
816 try {
817 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
818 libFiles.add(lib);
819 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700820 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 }
822 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800823 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800825 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827 }
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 // Gross hack for now: we know this file doesn't contain any
831 // code, so don't dexopt it to avoid the resulting log spew.
832 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 /**
835 * And there are a number of commands implemented in Java, which
836 * we currently need to do the dexopt on so that they can be
837 * run from a non-root shell.
838 */
839 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700840 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 for (int i=0; i<frameworkFiles.length; i++) {
842 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
843 String path = libPath.getPath();
844 // Skip the file if we alrady did it.
845 if (libFiles.contains(path)) {
846 continue;
847 }
848 // Skip the file if it is not a type we want to dexopt.
849 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
850 continue;
851 }
852 try {
853 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
854 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700855 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800858 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800860 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862 }
863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800864
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700865 if (didDexOpt) {
866 // If we had to do a dexopt of one of the previous
867 // things, then something on the system has changed.
868 // Consider this significant, and wipe away all other
869 // existing dexopt files to ensure we don't leave any
870 // dangling around.
871 String[] files = mDalvikCacheDir.list();
872 if (files != null) {
873 for (int i=0; i<files.length; i++) {
874 String fn = files[i];
875 if (fn.startsWith("data@app@")
876 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800877 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700878 (new File(mDalvikCacheDir, fn)).delete();
879 }
880 }
881 }
882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800884
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800885 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 mFrameworkInstallObserver = new AppDirObserver(
887 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
888 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700889 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
890 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800891 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800892
893 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
895 mSystemInstallObserver = new AppDirObserver(
896 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
897 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700898 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
899 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800900
901 if (mInstaller != null) {
902 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
903 mInstaller.moveFiles();
904 }
905
906 // Prune any system packages that no longer exist.
907 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
908 while (psit.hasNext()) {
909 PackageSetting ps = psit.next();
910 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800911 && !mPackages.containsKey(ps.name)
912 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800913 psit.remove();
914 String msg = "System package " + ps.name
915 + " no longer exists; wiping its data";
916 reportSettingsProblem(Log.WARN, msg);
917 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700918 mInstaller.remove(ps.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919 }
920 }
921 }
922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mAppInstallDir = new File(dataDir, "app");
924 if (mInstaller == null) {
925 // Make sure these dirs exist, when we are running in
926 // the simulator.
927 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
928 }
929 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800930 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 //clean up list
932 for(int i = 0; i < deletePkgsList.size(); i++) {
933 //clean up here
934 cleanupInstallFailedPackage(deletePkgsList.get(i));
935 }
936 //delete tmp files
937 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800938
939 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 SystemClock.uptimeMillis());
941 mAppInstallObserver = new AppDirObserver(
942 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
943 mAppInstallObserver.startWatching();
944 scanDirLI(mAppInstallDir, 0, scanMode);
945
946 mDrmAppInstallObserver = new AppDirObserver(
947 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
948 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800949 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800951 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800953 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 + ((SystemClock.uptimeMillis()-startTime)/1000f)
955 + " seconds");
956
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700957 updatePermissionsLP(null, null, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958
959 mSettings.writeLP();
960
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 // Now after opening every single application zip, make sure they
965 // are all flushed. Not really needed, but keeps things nice and
966 // tidy.
967 Runtime.getRuntime().gc();
968 } // synchronized (mPackages)
969 } // synchronized (mInstallLock)
970 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 @Override
973 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
974 throws RemoteException {
975 try {
976 return super.onTransact(code, data, reply, flags);
977 } catch (RuntimeException e) {
978 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800979 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 }
981 throw e;
982 }
983 }
984
Dianne Hackborne6620b22010-01-22 14:46:21 -0800985 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800986 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700988 int retCode = mInstaller.remove(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800990 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800991 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993 } else {
994 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800995 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 File dataDir = new File(pkg.applicationInfo.dataDir);
997 dataDir.delete();
998 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800999 if (ps.codePath != null) {
1000 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001001 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001002 }
1003 }
1004 if (ps.resourcePath != null) {
1005 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001006 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001007 }
1008 }
1009 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 }
1011
1012 void readPermissions() {
1013 // Read permissions from .../etc/permission directory.
1014 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1015 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001016 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 return;
1018 }
1019 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001020 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 return;
1022 }
1023
1024 // Iterate over the files in the directory and scan .xml files
1025 for (File f : libraryDir.listFiles()) {
1026 // We'll read platform.xml last
1027 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1028 continue;
1029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001032 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 continue;
1034 }
1035 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 continue;
1038 }
1039
1040 readPermissionsFromXml(f);
1041 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1044 final File permFile = new File(Environment.getRootDirectory(),
1045 "etc/permissions/platform.xml");
1046 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001047
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001048 StringBuilder sb = new StringBuilder(128);
1049 sb.append("Libs:");
1050 Iterator<String> it = mSharedLibraries.keySet().iterator();
1051 while (it.hasNext()) {
1052 sb.append(' ');
1053 String name = it.next();
1054 sb.append(name);
1055 sb.append(':');
1056 sb.append(mSharedLibraries.get(name));
1057 }
1058 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001059
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001060 sb.setLength(0);
1061 sb.append("Features:");
1062 it = mAvailableFeatures.keySet().iterator();
1063 while (it.hasNext()) {
1064 sb.append(' ');
1065 sb.append(it.next());
1066 }
1067 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001069
1070 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 FileReader permReader = null;
1072 try {
1073 permReader = new FileReader(permFile);
1074 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001075 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return;
1077 }
1078
1079 try {
1080 XmlPullParser parser = Xml.newPullParser();
1081 parser.setInput(permReader);
1082
1083 XmlUtils.beginDocument(parser, "permissions");
1084
1085 while (true) {
1086 XmlUtils.nextElement(parser);
1087 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1088 break;
1089 }
1090
1091 String name = parser.getName();
1092 if ("group".equals(name)) {
1093 String gidStr = parser.getAttributeValue(null, "gid");
1094 if (gidStr != null) {
1095 int gid = Integer.parseInt(gidStr);
1096 mGlobalGids = appendInt(mGlobalGids, gid);
1097 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 + parser.getPositionDescription());
1100 }
1101
1102 XmlUtils.skipCurrentTag(parser);
1103 continue;
1104 } else if ("permission".equals(name)) {
1105 String perm = parser.getAttributeValue(null, "name");
1106 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001107 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 + parser.getPositionDescription());
1109 XmlUtils.skipCurrentTag(parser);
1110 continue;
1111 }
1112 perm = perm.intern();
1113 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 } else if ("assign-permission".equals(name)) {
1116 String perm = parser.getAttributeValue(null, "name");
1117 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001118 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 + parser.getPositionDescription());
1120 XmlUtils.skipCurrentTag(parser);
1121 continue;
1122 }
1123 String uidStr = parser.getAttributeValue(null, "uid");
1124 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001125 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 + parser.getPositionDescription());
1127 XmlUtils.skipCurrentTag(parser);
1128 continue;
1129 }
1130 int uid = Process.getUidForName(uidStr);
1131 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001132 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 + uidStr + "\" at "
1134 + parser.getPositionDescription());
1135 XmlUtils.skipCurrentTag(parser);
1136 continue;
1137 }
1138 perm = perm.intern();
1139 HashSet<String> perms = mSystemPermissions.get(uid);
1140 if (perms == null) {
1141 perms = new HashSet<String>();
1142 mSystemPermissions.put(uid, perms);
1143 }
1144 perms.add(perm);
1145 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 } else if ("library".equals(name)) {
1148 String lname = parser.getAttributeValue(null, "name");
1149 String lfile = parser.getAttributeValue(null, "file");
1150 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001151 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 + parser.getPositionDescription());
1153 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001154 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 + parser.getPositionDescription());
1156 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001157 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001158 mSharedLibraries.put(lname, lfile);
1159 }
1160 XmlUtils.skipCurrentTag(parser);
1161 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001162
Dianne Hackborn49237342009-08-27 20:08:01 -07001163 } else if ("feature".equals(name)) {
1164 String fname = parser.getAttributeValue(null, "name");
1165 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001166 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001167 + parser.getPositionDescription());
1168 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001169 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001170 FeatureInfo fi = new FeatureInfo();
1171 fi.name = fname;
1172 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
1174 XmlUtils.skipCurrentTag(parser);
1175 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 } else {
1178 XmlUtils.skipCurrentTag(parser);
1179 continue;
1180 }
1181
1182 }
1183 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001184 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001186 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
1188 }
1189
1190 void readPermission(XmlPullParser parser, String name)
1191 throws IOException, XmlPullParserException {
1192
1193 name = name.intern();
1194
1195 BasePermission bp = mSettings.mPermissions.get(name);
1196 if (bp == null) {
1197 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1198 mSettings.mPermissions.put(name, bp);
1199 }
1200 int outerDepth = parser.getDepth();
1201 int type;
1202 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1203 && (type != XmlPullParser.END_TAG
1204 || parser.getDepth() > outerDepth)) {
1205 if (type == XmlPullParser.END_TAG
1206 || type == XmlPullParser.TEXT) {
1207 continue;
1208 }
1209
1210 String tagName = parser.getName();
1211 if ("group".equals(tagName)) {
1212 String gidStr = parser.getAttributeValue(null, "gid");
1213 if (gidStr != null) {
1214 int gid = Process.getGidForName(gidStr);
1215 bp.gids = appendInt(bp.gids, gid);
1216 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001217 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 + parser.getPositionDescription());
1219 }
1220 }
1221 XmlUtils.skipCurrentTag(parser);
1222 }
1223 }
1224
1225 static int[] appendInt(int[] cur, int val) {
1226 if (cur == null) {
1227 return new int[] { val };
1228 }
1229 final int N = cur.length;
1230 for (int i=0; i<N; i++) {
1231 if (cur[i] == val) {
1232 return cur;
1233 }
1234 }
1235 int[] ret = new int[N+1];
1236 System.arraycopy(cur, 0, ret, 0, N);
1237 ret[N] = val;
1238 return ret;
1239 }
1240
1241 static int[] appendInts(int[] cur, int[] add) {
1242 if (add == null) return cur;
1243 if (cur == null) return add;
1244 final int N = add.length;
1245 for (int i=0; i<N; i++) {
1246 cur = appendInt(cur, add[i]);
1247 }
1248 return cur;
1249 }
1250
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001251 static int[] removeInt(int[] cur, int val) {
1252 if (cur == null) {
1253 return null;
1254 }
1255 final int N = cur.length;
1256 for (int i=0; i<N; i++) {
1257 if (cur[i] == val) {
1258 int[] ret = new int[N-1];
1259 if (i > 0) {
1260 System.arraycopy(cur, 0, ret, 0, i);
1261 }
1262 if (i < (N-1)) {
1263 System.arraycopy(cur, i, ret, i+1, N-i-1);
1264 }
1265 return ret;
1266 }
1267 }
1268 return cur;
1269 }
1270
1271 static int[] removeInts(int[] cur, int[] rem) {
1272 if (rem == null) return cur;
1273 if (cur == null) return cur;
1274 final int N = rem.length;
1275 for (int i=0; i<N; i++) {
1276 cur = removeInt(cur, rem[i]);
1277 }
1278 return cur;
1279 }
1280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001282 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1283 // The package has been uninstalled but has retained data and resources.
1284 return PackageParser.generatePackageInfo(p, null, flags);
1285 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 final PackageSetting ps = (PackageSetting)p.mExtras;
1287 if (ps == null) {
1288 return null;
1289 }
1290 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1291 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1292 }
1293
1294 public PackageInfo getPackageInfo(String packageName, int flags) {
1295 synchronized (mPackages) {
1296 PackageParser.Package p = mPackages.get(packageName);
1297 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001298 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 + ": " + p);
1300 if (p != null) {
1301 return generatePackageInfo(p, flags);
1302 }
1303 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1304 return generatePackageInfoFromSettingsLP(packageName, flags);
1305 }
1306 }
1307 return null;
1308 }
1309
Dianne Hackborn47096932010-02-11 15:57:09 -08001310 public String[] currentToCanonicalPackageNames(String[] names) {
1311 String[] out = new String[names.length];
1312 synchronized (mPackages) {
1313 for (int i=names.length-1; i>=0; i--) {
1314 PackageSetting ps = mSettings.mPackages.get(names[i]);
1315 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1316 }
1317 }
1318 return out;
1319 }
1320
1321 public String[] canonicalToCurrentPackageNames(String[] names) {
1322 String[] out = new String[names.length];
1323 synchronized (mPackages) {
1324 for (int i=names.length-1; i>=0; i--) {
1325 String cur = mSettings.mRenamedPackages.get(names[i]);
1326 out[i] = cur != null ? cur : names[i];
1327 }
1328 }
1329 return out;
1330 }
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 public int getPackageUid(String packageName) {
1333 synchronized (mPackages) {
1334 PackageParser.Package p = mPackages.get(packageName);
1335 if(p != null) {
1336 return p.applicationInfo.uid;
1337 }
1338 PackageSetting ps = mSettings.mPackages.get(packageName);
1339 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1340 return -1;
1341 }
1342 p = ps.pkg;
1343 return p != null ? p.applicationInfo.uid : -1;
1344 }
1345 }
1346
1347 public int[] getPackageGids(String packageName) {
1348 synchronized (mPackages) {
1349 PackageParser.Package p = mPackages.get(packageName);
1350 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001351 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 + ": " + p);
1353 if (p != null) {
1354 final PackageSetting ps = (PackageSetting)p.mExtras;
1355 final SharedUserSetting suid = ps.sharedUser;
1356 return suid != null ? suid.gids : ps.gids;
1357 }
1358 }
1359 // stupid thing to indicate an error.
1360 return new int[0];
1361 }
1362
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001363 static final PermissionInfo generatePermissionInfo(
1364 BasePermission bp, int flags) {
1365 if (bp.perm != null) {
1366 return PackageParser.generatePermissionInfo(bp.perm, flags);
1367 }
1368 PermissionInfo pi = new PermissionInfo();
1369 pi.name = bp.name;
1370 pi.packageName = bp.sourcePackage;
1371 pi.nonLocalizedLabel = bp.name;
1372 pi.protectionLevel = bp.protectionLevel;
1373 return pi;
1374 }
1375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 public PermissionInfo getPermissionInfo(String name, int flags) {
1377 synchronized (mPackages) {
1378 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001379 if (p != null) {
1380 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382 return null;
1383 }
1384 }
1385
1386 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1387 synchronized (mPackages) {
1388 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1389 for (BasePermission p : mSettings.mPermissions.values()) {
1390 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001391 if (p.perm == null || p.perm.info.group == null) {
1392 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 }
1394 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001395 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1397 }
1398 }
1399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 if (out.size() > 0) {
1402 return out;
1403 }
1404 return mPermissionGroups.containsKey(group) ? out : null;
1405 }
1406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1409 synchronized (mPackages) {
1410 return PackageParser.generatePermissionGroupInfo(
1411 mPermissionGroups.get(name), flags);
1412 }
1413 }
1414
1415 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1416 synchronized (mPackages) {
1417 final int N = mPermissionGroups.size();
1418 ArrayList<PermissionGroupInfo> out
1419 = new ArrayList<PermissionGroupInfo>(N);
1420 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1421 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1422 }
1423 return out;
1424 }
1425 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1428 PackageSetting ps = mSettings.mPackages.get(packageName);
1429 if(ps != null) {
1430 if(ps.pkg == null) {
1431 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1432 if(pInfo != null) {
1433 return pInfo.applicationInfo;
1434 }
1435 return null;
1436 }
1437 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1438 }
1439 return null;
1440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1443 PackageSetting ps = mSettings.mPackages.get(packageName);
1444 if(ps != null) {
1445 if(ps.pkg == null) {
1446 ps.pkg = new PackageParser.Package(packageName);
1447 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001448 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1449 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1450 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1451 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453 return generatePackageInfo(ps.pkg, flags);
1454 }
1455 return null;
1456 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1459 synchronized (mPackages) {
1460 PackageParser.Package p = mPackages.get(packageName);
1461 if (Config.LOGV) Log.v(
1462 TAG, "getApplicationInfo " + packageName
1463 + ": " + p);
1464 if (p != null) {
1465 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001466 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 if ("android".equals(packageName)||"system".equals(packageName)) {
1469 return mAndroidApplication;
1470 }
1471 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1472 return generateApplicationInfoFromSettingsLP(packageName, flags);
1473 }
1474 }
1475 return null;
1476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001477
1478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1480 mContext.enforceCallingOrSelfPermission(
1481 android.Manifest.permission.CLEAR_APP_CACHE, null);
1482 // Queue up an async operation since clearing cache may take a little while.
1483 mHandler.post(new Runnable() {
1484 public void run() {
1485 mHandler.removeCallbacks(this);
1486 int retCode = -1;
1487 if (mInstaller != null) {
1488 retCode = mInstaller.freeCache(freeStorageSize);
1489 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001490 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492 } //end if mInstaller
1493 if (observer != null) {
1494 try {
1495 observer.onRemoveCompleted(null, (retCode >= 0));
1496 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001497 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 }
1499 }
1500 }
1501 });
1502 }
1503
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001504 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001505 mContext.enforceCallingOrSelfPermission(
1506 android.Manifest.permission.CLEAR_APP_CACHE, null);
1507 // Queue up an async operation since clearing cache may take a little while.
1508 mHandler.post(new Runnable() {
1509 public void run() {
1510 mHandler.removeCallbacks(this);
1511 int retCode = -1;
1512 if (mInstaller != null) {
1513 retCode = mInstaller.freeCache(freeStorageSize);
1514 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001515 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001516 }
1517 }
1518 if(pi != null) {
1519 try {
1520 // Callback via pending intent
1521 int code = (retCode >= 0) ? 1 : 0;
1522 pi.sendIntent(null, code, null,
1523 null, null);
1524 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001525 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001526 }
1527 }
1528 }
1529 });
1530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1533 synchronized (mPackages) {
1534 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001535
1536 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001538 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 if (mResolveComponentName.equals(component)) {
1541 return mResolveActivity;
1542 }
1543 }
1544 return null;
1545 }
1546
1547 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1548 synchronized (mPackages) {
1549 PackageParser.Activity a = mReceivers.mActivities.get(component);
1550 if (Config.LOGV) Log.v(
1551 TAG, "getReceiverInfo " + component + ": " + a);
1552 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1553 return PackageParser.generateActivityInfo(a, flags);
1554 }
1555 }
1556 return null;
1557 }
1558
1559 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1560 synchronized (mPackages) {
1561 PackageParser.Service s = mServices.mServices.get(component);
1562 if (Config.LOGV) Log.v(
1563 TAG, "getServiceInfo " + component + ": " + s);
1564 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1565 return PackageParser.generateServiceInfo(s, flags);
1566 }
1567 }
1568 return null;
1569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 public String[] getSystemSharedLibraryNames() {
1572 Set<String> libSet;
1573 synchronized (mPackages) {
1574 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001575 int size = libSet.size();
1576 if (size > 0) {
1577 String[] libs = new String[size];
1578 libSet.toArray(libs);
1579 return libs;
1580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001582 return null;
1583 }
1584
1585 public FeatureInfo[] getSystemAvailableFeatures() {
1586 Collection<FeatureInfo> featSet;
1587 synchronized (mPackages) {
1588 featSet = mAvailableFeatures.values();
1589 int size = featSet.size();
1590 if (size > 0) {
1591 FeatureInfo[] features = new FeatureInfo[size+1];
1592 featSet.toArray(features);
1593 FeatureInfo fi = new FeatureInfo();
1594 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1595 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1596 features[size] = fi;
1597 return features;
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 return null;
1601 }
1602
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001603 public boolean hasSystemFeature(String name) {
1604 synchronized (mPackages) {
1605 return mAvailableFeatures.containsKey(name);
1606 }
1607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 public int checkPermission(String permName, String pkgName) {
1610 synchronized (mPackages) {
1611 PackageParser.Package p = mPackages.get(pkgName);
1612 if (p != null && p.mExtras != null) {
1613 PackageSetting ps = (PackageSetting)p.mExtras;
1614 if (ps.sharedUser != null) {
1615 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1616 return PackageManager.PERMISSION_GRANTED;
1617 }
1618 } else if (ps.grantedPermissions.contains(permName)) {
1619 return PackageManager.PERMISSION_GRANTED;
1620 }
1621 }
1622 }
1623 return PackageManager.PERMISSION_DENIED;
1624 }
1625
1626 public int checkUidPermission(String permName, int uid) {
1627 synchronized (mPackages) {
1628 Object obj = mSettings.getUserIdLP(uid);
1629 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001630 GrantedPermissions gp = (GrantedPermissions)obj;
1631 if (gp.grantedPermissions.contains(permName)) {
1632 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634 } else {
1635 HashSet<String> perms = mSystemPermissions.get(uid);
1636 if (perms != null && perms.contains(permName)) {
1637 return PackageManager.PERMISSION_GRANTED;
1638 }
1639 }
1640 }
1641 return PackageManager.PERMISSION_DENIED;
1642 }
1643
1644 private BasePermission findPermissionTreeLP(String permName) {
1645 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1646 if (permName.startsWith(bp.name) &&
1647 permName.length() > bp.name.length() &&
1648 permName.charAt(bp.name.length()) == '.') {
1649 return bp;
1650 }
1651 }
1652 return null;
1653 }
1654
1655 private BasePermission checkPermissionTreeLP(String permName) {
1656 if (permName != null) {
1657 BasePermission bp = findPermissionTreeLP(permName);
1658 if (bp != null) {
1659 if (bp.uid == Binder.getCallingUid()) {
1660 return bp;
1661 }
1662 throw new SecurityException("Calling uid "
1663 + Binder.getCallingUid()
1664 + " is not allowed to add to permission tree "
1665 + bp.name + " owned by uid " + bp.uid);
1666 }
1667 }
1668 throw new SecurityException("No permission tree found for " + permName);
1669 }
1670
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001671 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1672 if (s1 == null) {
1673 return s2 == null;
1674 }
1675 if (s2 == null) {
1676 return false;
1677 }
1678 if (s1.getClass() != s2.getClass()) {
1679 return false;
1680 }
1681 return s1.equals(s2);
1682 }
1683
1684 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1685 if (pi1.icon != pi2.icon) return false;
1686 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1687 if (!compareStrings(pi1.name, pi2.name)) return false;
1688 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1689 // We'll take care of setting this one.
1690 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1691 // These are not currently stored in settings.
1692 //if (!compareStrings(pi1.group, pi2.group)) return false;
1693 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1694 //if (pi1.labelRes != pi2.labelRes) return false;
1695 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1696 return true;
1697 }
1698
1699 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1700 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1701 throw new SecurityException("Label must be specified in permission");
1702 }
1703 BasePermission tree = checkPermissionTreeLP(info.name);
1704 BasePermission bp = mSettings.mPermissions.get(info.name);
1705 boolean added = bp == null;
1706 boolean changed = true;
1707 if (added) {
1708 bp = new BasePermission(info.name, tree.sourcePackage,
1709 BasePermission.TYPE_DYNAMIC);
1710 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1711 throw new SecurityException(
1712 "Not allowed to modify non-dynamic permission "
1713 + info.name);
1714 } else {
1715 if (bp.protectionLevel == info.protectionLevel
1716 && bp.perm.owner.equals(tree.perm.owner)
1717 && bp.uid == tree.uid
1718 && comparePermissionInfos(bp.perm.info, info)) {
1719 changed = false;
1720 }
1721 }
1722 bp.protectionLevel = info.protectionLevel;
1723 bp.perm = new PackageParser.Permission(tree.perm.owner,
1724 new PermissionInfo(info));
1725 bp.perm.info.packageName = tree.perm.info.packageName;
1726 bp.uid = tree.uid;
1727 if (added) {
1728 mSettings.mPermissions.put(info.name, bp);
1729 }
1730 if (changed) {
1731 if (!async) {
1732 mSettings.writeLP();
1733 } else {
1734 scheduleWriteSettingsLocked();
1735 }
1736 }
1737 return added;
1738 }
1739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 public boolean addPermission(PermissionInfo info) {
1741 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001742 return addPermissionLocked(info, false);
1743 }
1744 }
1745
1746 public boolean addPermissionAsync(PermissionInfo info) {
1747 synchronized (mPackages) {
1748 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
1750 }
1751
1752 public void removePermission(String name) {
1753 synchronized (mPackages) {
1754 checkPermissionTreeLP(name);
1755 BasePermission bp = mSettings.mPermissions.get(name);
1756 if (bp != null) {
1757 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1758 throw new SecurityException(
1759 "Not allowed to modify non-dynamic permission "
1760 + name);
1761 }
1762 mSettings.mPermissions.remove(name);
1763 mSettings.writeLP();
1764 }
1765 }
1766 }
1767
Dianne Hackborn854060af2009-07-09 18:14:31 -07001768 public boolean isProtectedBroadcast(String actionName) {
1769 synchronized (mPackages) {
1770 return mProtectedBroadcasts.contains(actionName);
1771 }
1772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 public int checkSignatures(String pkg1, String pkg2) {
1775 synchronized (mPackages) {
1776 PackageParser.Package p1 = mPackages.get(pkg1);
1777 PackageParser.Package p2 = mPackages.get(pkg2);
1778 if (p1 == null || p1.mExtras == null
1779 || p2 == null || p2.mExtras == null) {
1780 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1781 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001782 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 }
1784 }
1785
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001786 public int checkUidSignatures(int uid1, int uid2) {
1787 synchronized (mPackages) {
1788 Signature[] s1;
1789 Signature[] s2;
1790 Object obj = mSettings.getUserIdLP(uid1);
1791 if (obj != null) {
1792 if (obj instanceof SharedUserSetting) {
1793 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1794 } else if (obj instanceof PackageSetting) {
1795 s1 = ((PackageSetting)obj).signatures.mSignatures;
1796 } else {
1797 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1798 }
1799 } else {
1800 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1801 }
1802 obj = mSettings.getUserIdLP(uid2);
1803 if (obj != null) {
1804 if (obj instanceof SharedUserSetting) {
1805 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1806 } else if (obj instanceof PackageSetting) {
1807 s2 = ((PackageSetting)obj).signatures.mSignatures;
1808 } else {
1809 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1810 }
1811 } else {
1812 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1813 }
1814 return checkSignaturesLP(s1, s2);
1815 }
1816 }
1817
1818 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1819 if (s1 == null) {
1820 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1822 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1823 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001824 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1826 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001827 final int N1 = s1.length;
1828 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 for (int i=0; i<N1; i++) {
1830 boolean match = false;
1831 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001832 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 match = true;
1834 break;
1835 }
1836 }
1837 if (!match) {
1838 return PackageManager.SIGNATURE_NO_MATCH;
1839 }
1840 }
1841 return PackageManager.SIGNATURE_MATCH;
1842 }
1843
1844 public String[] getPackagesForUid(int uid) {
1845 synchronized (mPackages) {
1846 Object obj = mSettings.getUserIdLP(uid);
1847 if (obj instanceof SharedUserSetting) {
1848 SharedUserSetting sus = (SharedUserSetting)obj;
1849 final int N = sus.packages.size();
1850 String[] res = new String[N];
1851 Iterator<PackageSetting> it = sus.packages.iterator();
1852 int i=0;
1853 while (it.hasNext()) {
1854 res[i++] = it.next().name;
1855 }
1856 return res;
1857 } else if (obj instanceof PackageSetting) {
1858 PackageSetting ps = (PackageSetting)obj;
1859 return new String[] { ps.name };
1860 }
1861 }
1862 return null;
1863 }
1864
1865 public String getNameForUid(int uid) {
1866 synchronized (mPackages) {
1867 Object obj = mSettings.getUserIdLP(uid);
1868 if (obj instanceof SharedUserSetting) {
1869 SharedUserSetting sus = (SharedUserSetting)obj;
1870 return sus.name + ":" + sus.userId;
1871 } else if (obj instanceof PackageSetting) {
1872 PackageSetting ps = (PackageSetting)obj;
1873 return ps.name;
1874 }
1875 }
1876 return null;
1877 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 public int getUidForSharedUser(String sharedUserName) {
1880 if(sharedUserName == null) {
1881 return -1;
1882 }
1883 synchronized (mPackages) {
1884 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1885 if(suid == null) {
1886 return -1;
1887 }
1888 return suid.userId;
1889 }
1890 }
1891
1892 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1893 int flags) {
1894 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001895 return chooseBestActivity(intent, resolvedType, flags, query);
1896 }
1897
Mihai Predaeae850c2009-05-13 10:13:48 +02001898 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1899 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 if (query != null) {
1901 final int N = query.size();
1902 if (N == 1) {
1903 return query.get(0);
1904 } else if (N > 1) {
1905 // If there is more than one activity with the same priority,
1906 // then let the user decide between them.
1907 ResolveInfo r0 = query.get(0);
1908 ResolveInfo r1 = query.get(1);
1909 if (false) {
1910 System.out.println(r0.activityInfo.name +
1911 "=" + r0.priority + " vs " +
1912 r1.activityInfo.name +
1913 "=" + r1.priority);
1914 }
1915 // If the first activity has a higher priority, or a different
1916 // default, then it is always desireable to pick it.
1917 if (r0.priority != r1.priority
1918 || r0.preferredOrder != r1.preferredOrder
1919 || r0.isDefault != r1.isDefault) {
1920 return query.get(0);
1921 }
1922 // If we have saved a preference for a preferred activity for
1923 // this Intent, use that.
1924 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1925 flags, query, r0.priority);
1926 if (ri != null) {
1927 return ri;
1928 }
1929 return mResolveInfo;
1930 }
1931 }
1932 return null;
1933 }
1934
1935 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1936 int flags, List<ResolveInfo> query, int priority) {
1937 synchronized (mPackages) {
1938 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1939 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001940 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1942 if (prefs != null && prefs.size() > 0) {
1943 // First figure out how good the original match set is.
1944 // We will only allow preferred activities that came
1945 // from the same match quality.
1946 int match = 0;
1947 final int N = query.size();
1948 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1949 for (int j=0; j<N; j++) {
1950 ResolveInfo ri = query.get(j);
1951 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1952 + ": 0x" + Integer.toHexString(match));
1953 if (ri.match > match) match = ri.match;
1954 }
1955 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1956 + Integer.toHexString(match));
1957 match &= IntentFilter.MATCH_CATEGORY_MASK;
1958 final int M = prefs.size();
1959 for (int i=0; i<M; i++) {
1960 PreferredActivity pa = prefs.get(i);
1961 if (pa.mMatch != match) {
1962 continue;
1963 }
1964 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1965 if (DEBUG_PREFERRED) {
1966 Log.v(TAG, "Got preferred activity:");
1967 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1968 }
1969 if (ai != null) {
1970 for (int j=0; j<N; j++) {
1971 ResolveInfo ri = query.get(j);
1972 if (!ri.activityInfo.applicationInfo.packageName
1973 .equals(ai.applicationInfo.packageName)) {
1974 continue;
1975 }
1976 if (!ri.activityInfo.name.equals(ai.name)) {
1977 continue;
1978 }
1979
1980 // Okay we found a previously set preferred app.
1981 // If the result set is different from when this
1982 // was created, we need to clear it and re-ask the
1983 // user their preference.
1984 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001985 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 + intent + " type " + resolvedType);
1987 mSettings.mPreferredActivities.removeFilter(pa);
1988 return null;
1989 }
1990
1991 // Yay!
1992 return ri;
1993 }
1994 }
1995 }
1996 }
1997 }
1998 return null;
1999 }
2000
2001 public List<ResolveInfo> queryIntentActivities(Intent intent,
2002 String resolvedType, int flags) {
2003 ComponentName comp = intent.getComponent();
2004 if (comp != null) {
2005 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2006 ActivityInfo ai = getActivityInfo(comp, flags);
2007 if (ai != null) {
2008 ResolveInfo ri = new ResolveInfo();
2009 ri.activityInfo = ai;
2010 list.add(ri);
2011 }
2012 return list;
2013 }
2014
2015 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002016 String pkgName = intent.getPackage();
2017 if (pkgName == null) {
2018 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2019 resolvedType, flags);
2020 }
2021 PackageParser.Package pkg = mPackages.get(pkgName);
2022 if (pkg != null) {
2023 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2024 resolvedType, flags, pkg.activities);
2025 }
2026 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028 }
2029
2030 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2031 Intent[] specifics, String[] specificTypes, Intent intent,
2032 String resolvedType, int flags) {
2033 final String resultsAction = intent.getAction();
2034
2035 List<ResolveInfo> results = queryIntentActivities(
2036 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2037 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2038
2039 int specificsPos = 0;
2040 int N;
2041
2042 // todo: note that the algorithm used here is O(N^2). This
2043 // isn't a problem in our current environment, but if we start running
2044 // into situations where we have more than 5 or 10 matches then this
2045 // should probably be changed to something smarter...
2046
2047 // First we go through and resolve each of the specific items
2048 // that were supplied, taking care of removing any corresponding
2049 // duplicate items in the generic resolve list.
2050 if (specifics != null) {
2051 for (int i=0; i<specifics.length; i++) {
2052 final Intent sintent = specifics[i];
2053 if (sintent == null) {
2054 continue;
2055 }
2056
2057 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2058 String action = sintent.getAction();
2059 if (resultsAction != null && resultsAction.equals(action)) {
2060 // If this action was explicitly requested, then don't
2061 // remove things that have it.
2062 action = null;
2063 }
2064 ComponentName comp = sintent.getComponent();
2065 ResolveInfo ri = null;
2066 ActivityInfo ai = null;
2067 if (comp == null) {
2068 ri = resolveIntent(
2069 sintent,
2070 specificTypes != null ? specificTypes[i] : null,
2071 flags);
2072 if (ri == null) {
2073 continue;
2074 }
2075 if (ri == mResolveInfo) {
2076 // ACK! Must do something better with this.
2077 }
2078 ai = ri.activityInfo;
2079 comp = new ComponentName(ai.applicationInfo.packageName,
2080 ai.name);
2081 } else {
2082 ai = getActivityInfo(comp, flags);
2083 if (ai == null) {
2084 continue;
2085 }
2086 }
2087
2088 // Look for any generic query activities that are duplicates
2089 // of this specific one, and remove them from the results.
2090 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2091 N = results.size();
2092 int j;
2093 for (j=specificsPos; j<N; j++) {
2094 ResolveInfo sri = results.get(j);
2095 if ((sri.activityInfo.name.equals(comp.getClassName())
2096 && sri.activityInfo.applicationInfo.packageName.equals(
2097 comp.getPackageName()))
2098 || (action != null && sri.filter.matchAction(action))) {
2099 results.remove(j);
2100 if (Config.LOGV) Log.v(
2101 TAG, "Removing duplicate item from " + j
2102 + " due to specific " + specificsPos);
2103 if (ri == null) {
2104 ri = sri;
2105 }
2106 j--;
2107 N--;
2108 }
2109 }
2110
2111 // Add this specific item to its proper place.
2112 if (ri == null) {
2113 ri = new ResolveInfo();
2114 ri.activityInfo = ai;
2115 }
2116 results.add(specificsPos, ri);
2117 ri.specificIndex = i;
2118 specificsPos++;
2119 }
2120 }
2121
2122 // Now we go through the remaining generic results and remove any
2123 // duplicate actions that are found here.
2124 N = results.size();
2125 for (int i=specificsPos; i<N-1; i++) {
2126 final ResolveInfo rii = results.get(i);
2127 if (rii.filter == null) {
2128 continue;
2129 }
2130
2131 // Iterate over all of the actions of this result's intent
2132 // filter... typically this should be just one.
2133 final Iterator<String> it = rii.filter.actionsIterator();
2134 if (it == null) {
2135 continue;
2136 }
2137 while (it.hasNext()) {
2138 final String action = it.next();
2139 if (resultsAction != null && resultsAction.equals(action)) {
2140 // If this action was explicitly requested, then don't
2141 // remove things that have it.
2142 continue;
2143 }
2144 for (int j=i+1; j<N; j++) {
2145 final ResolveInfo rij = results.get(j);
2146 if (rij.filter != null && rij.filter.hasAction(action)) {
2147 results.remove(j);
2148 if (Config.LOGV) Log.v(
2149 TAG, "Removing duplicate item from " + j
2150 + " due to action " + action + " at " + i);
2151 j--;
2152 N--;
2153 }
2154 }
2155 }
2156
2157 // If the caller didn't request filter information, drop it now
2158 // so we don't have to marshall/unmarshall it.
2159 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2160 rii.filter = null;
2161 }
2162 }
2163
2164 // Filter out the caller activity if so requested.
2165 if (caller != null) {
2166 N = results.size();
2167 for (int i=0; i<N; i++) {
2168 ActivityInfo ainfo = results.get(i).activityInfo;
2169 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2170 && caller.getClassName().equals(ainfo.name)) {
2171 results.remove(i);
2172 break;
2173 }
2174 }
2175 }
2176
2177 // If the caller didn't request filter information,
2178 // drop them now so we don't have to
2179 // marshall/unmarshall it.
2180 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2181 N = results.size();
2182 for (int i=0; i<N; i++) {
2183 results.get(i).filter = null;
2184 }
2185 }
2186
2187 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2188 return results;
2189 }
2190
2191 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2192 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002193 ComponentName comp = intent.getComponent();
2194 if (comp != null) {
2195 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2196 ActivityInfo ai = getReceiverInfo(comp, flags);
2197 if (ai != null) {
2198 ResolveInfo ri = new ResolveInfo();
2199 ri.activityInfo = ai;
2200 list.add(ri);
2201 }
2202 return list;
2203 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002206 String pkgName = intent.getPackage();
2207 if (pkgName == null) {
2208 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2209 resolvedType, flags);
2210 }
2211 PackageParser.Package pkg = mPackages.get(pkgName);
2212 if (pkg != null) {
2213 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2214 resolvedType, flags, pkg.receivers);
2215 }
2216 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 }
2218 }
2219
2220 public ResolveInfo resolveService(Intent intent, String resolvedType,
2221 int flags) {
2222 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2223 flags);
2224 if (query != null) {
2225 if (query.size() >= 1) {
2226 // If there is more than one service with the same priority,
2227 // just arbitrarily pick the first one.
2228 return query.get(0);
2229 }
2230 }
2231 return null;
2232 }
2233
2234 public List<ResolveInfo> queryIntentServices(Intent intent,
2235 String resolvedType, int flags) {
2236 ComponentName comp = intent.getComponent();
2237 if (comp != null) {
2238 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2239 ServiceInfo si = getServiceInfo(comp, flags);
2240 if (si != null) {
2241 ResolveInfo ri = new ResolveInfo();
2242 ri.serviceInfo = si;
2243 list.add(ri);
2244 }
2245 return list;
2246 }
2247
2248 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002249 String pkgName = intent.getPackage();
2250 if (pkgName == null) {
2251 return (List<ResolveInfo>)mServices.queryIntent(intent,
2252 resolvedType, flags);
2253 }
2254 PackageParser.Package pkg = mPackages.get(pkgName);
2255 if (pkg != null) {
2256 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2257 resolvedType, flags, pkg.services);
2258 }
2259 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 }
2261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 public List<PackageInfo> getInstalledPackages(int flags) {
2264 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2265
2266 synchronized (mPackages) {
2267 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2268 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2269 while (i.hasNext()) {
2270 final PackageSetting ps = i.next();
2271 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2272 if(psPkg != null) {
2273 finalList.add(psPkg);
2274 }
2275 }
2276 }
2277 else {
2278 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2279 while (i.hasNext()) {
2280 final PackageParser.Package p = i.next();
2281 if (p.applicationInfo != null) {
2282 PackageInfo pi = generatePackageInfo(p, flags);
2283 if(pi != null) {
2284 finalList.add(pi);
2285 }
2286 }
2287 }
2288 }
2289 }
2290 return finalList;
2291 }
2292
2293 public List<ApplicationInfo> getInstalledApplications(int flags) {
2294 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2295 synchronized(mPackages) {
2296 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2297 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2298 while (i.hasNext()) {
2299 final PackageSetting ps = i.next();
2300 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2301 if(ai != null) {
2302 finalList.add(ai);
2303 }
2304 }
2305 }
2306 else {
2307 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2308 while (i.hasNext()) {
2309 final PackageParser.Package p = i.next();
2310 if (p.applicationInfo != null) {
2311 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2312 if(ai != null) {
2313 finalList.add(ai);
2314 }
2315 }
2316 }
2317 }
2318 }
2319 return finalList;
2320 }
2321
2322 public List<ApplicationInfo> getPersistentApplications(int flags) {
2323 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2324
2325 synchronized (mPackages) {
2326 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2327 while (i.hasNext()) {
2328 PackageParser.Package p = i.next();
2329 if (p.applicationInfo != null
2330 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2331 && (!mSafeMode || (p.applicationInfo.flags
2332 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2333 finalList.add(p.applicationInfo);
2334 }
2335 }
2336 }
2337
2338 return finalList;
2339 }
2340
2341 public ProviderInfo resolveContentProvider(String name, int flags) {
2342 synchronized (mPackages) {
2343 final PackageParser.Provider provider = mProviders.get(name);
2344 return provider != null
2345 && mSettings.isEnabledLP(provider.info, flags)
2346 && (!mSafeMode || (provider.info.applicationInfo.flags
2347 &ApplicationInfo.FLAG_SYSTEM) != 0)
2348 ? PackageParser.generateProviderInfo(provider, flags)
2349 : null;
2350 }
2351 }
2352
Fred Quintana718d8a22009-04-29 17:53:20 -07002353 /**
2354 * @deprecated
2355 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 public void querySyncProviders(List outNames, List outInfo) {
2357 synchronized (mPackages) {
2358 Iterator<Map.Entry<String, PackageParser.Provider>> i
2359 = mProviders.entrySet().iterator();
2360
2361 while (i.hasNext()) {
2362 Map.Entry<String, PackageParser.Provider> entry = i.next();
2363 PackageParser.Provider p = entry.getValue();
2364
2365 if (p.syncable
2366 && (!mSafeMode || (p.info.applicationInfo.flags
2367 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2368 outNames.add(entry.getKey());
2369 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2370 }
2371 }
2372 }
2373 }
2374
2375 public List<ProviderInfo> queryContentProviders(String processName,
2376 int uid, int flags) {
2377 ArrayList<ProviderInfo> finalList = null;
2378
2379 synchronized (mPackages) {
2380 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2381 while (i.hasNext()) {
2382 PackageParser.Provider p = i.next();
2383 if (p.info.authority != null
2384 && (processName == null ||
2385 (p.info.processName.equals(processName)
2386 && p.info.applicationInfo.uid == uid))
2387 && mSettings.isEnabledLP(p.info, flags)
2388 && (!mSafeMode || (p.info.applicationInfo.flags
2389 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2390 if (finalList == null) {
2391 finalList = new ArrayList<ProviderInfo>(3);
2392 }
2393 finalList.add(PackageParser.generateProviderInfo(p,
2394 flags));
2395 }
2396 }
2397 }
2398
2399 if (finalList != null) {
2400 Collections.sort(finalList, mProviderInitOrderSorter);
2401 }
2402
2403 return finalList;
2404 }
2405
2406 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2407 int flags) {
2408 synchronized (mPackages) {
2409 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2410 return PackageParser.generateInstrumentationInfo(i, flags);
2411 }
2412 }
2413
2414 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2415 int flags) {
2416 ArrayList<InstrumentationInfo> finalList =
2417 new ArrayList<InstrumentationInfo>();
2418
2419 synchronized (mPackages) {
2420 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2421 while (i.hasNext()) {
2422 PackageParser.Instrumentation p = i.next();
2423 if (targetPackage == null
2424 || targetPackage.equals(p.info.targetPackage)) {
2425 finalList.add(PackageParser.generateInstrumentationInfo(p,
2426 flags));
2427 }
2428 }
2429 }
2430
2431 return finalList;
2432 }
2433
2434 private void scanDirLI(File dir, int flags, int scanMode) {
2435 Log.d(TAG, "Scanning app dir " + dir);
2436
2437 String[] files = dir.list();
2438
2439 int i;
2440 for (i=0; i<files.length; i++) {
2441 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002442 if (!isPackageFilename(files[i])) {
2443 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002444 continue;
2445 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002446 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002448 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002449 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2450 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002451 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002452 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002453 file.delete();
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 }
2456 }
2457
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002458 private static File getSettingsProblemFile() {
2459 File dataDir = Environment.getDataDirectory();
2460 File systemDir = new File(dataDir, "system");
2461 File fname = new File(systemDir, "uiderrors.txt");
2462 return fname;
2463 }
2464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 private static void reportSettingsProblem(int priority, String msg) {
2466 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002467 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 FileOutputStream out = new FileOutputStream(fname, true);
2469 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002470 SimpleDateFormat formatter = new SimpleDateFormat();
2471 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2472 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 pw.close();
2474 FileUtils.setPermissions(
2475 fname.toString(),
2476 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2477 -1, -1);
2478 } catch (java.io.IOException e) {
2479 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002480 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
2482
2483 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2484 PackageParser.Package pkg, File srcFile, int parseFlags) {
2485 if (GET_CERTIFICATES) {
2486 if (ps == null || !ps.codePath.equals(srcFile)
2487 || ps.getTimeStamp() != srcFile.lastModified()) {
2488 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2489 if (!pp.collectCertificates(pkg, parseFlags)) {
2490 mLastScanError = pp.getParseError();
2491 return false;
2492 }
2493 }
2494 }
2495 return true;
2496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 /*
2499 * Scan a package and return the newly parsed package.
2500 * Returns null in case of errors and the error code is stored in mLastScanError
2501 */
2502 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002503 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002505 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002507 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002510 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 if (pkg == null) {
2512 mLastScanError = pp.getParseError();
2513 return null;
2514 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002515 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 PackageSetting updatedPkg;
2517 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002518 // Look to see if we already know about this package.
2519 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002520 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002521 // This package has been renamed to its original name. Let's
2522 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002523 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002524 }
2525 // If there was no original package, see one for the real package name.
2526 if (ps == null) {
2527 ps = mSettings.peekPackageLP(pkg.packageName);
2528 }
2529 // Check to see if this package could be hiding/updating a system
2530 // package. Must look for it either under the original or real
2531 // package name depending on our state.
2532 updatedPkg = mSettings.mDisabledSysPackages.get(
2533 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002535 // First check if this is a system package that may involve an update
2536 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2537 if (!ps.codePath.equals(scanFile)) {
2538 // The path has changed from what was last scanned... check the
2539 // version of the new path against what we have stored to determine
2540 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002541 if (pkg.mVersionCode < ps.versionCode) {
2542 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002543 // Ignore entry. Skip it.
2544 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2545 + "ignored: updated version " + ps.versionCode
2546 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002547 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2548 return null;
2549 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002550 // The current app on the system partion is better than
2551 // what we have updated to on the data partition; switch
2552 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002553 // At this point, its safely assumed that package installation for
2554 // apps in system partition will go through. If not there won't be a working
2555 // version of the app
2556 synchronized (mPackages) {
2557 // Just remove the loaded entries from package lists.
2558 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002559 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002560 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002561 + "reverting from " + ps.codePathString
2562 + ": new version " + pkg.mVersionCode
2563 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002564 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2565 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002566 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 }
2569 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002570 if (updatedPkg != null) {
2571 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2572 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2573 }
2574 // Verify certificates against what was last scanned
2575 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002576 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002577 return null;
2578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 // The apk is forward locked (not public) if its code and resources
2580 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002581 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002583 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002584 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002585
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002586 String codePath = null;
2587 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002588 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2589 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002590 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002591 } else {
2592 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002593 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002594 }
2595 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002596 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002597 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002598 codePath = pkg.mScanPath;
2599 // Set application objects path explicitly.
2600 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002602 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 }
2604
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002605 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2606 String destCodePath, String destResPath) {
2607 pkg.mPath = pkg.mScanPath = destCodePath;
2608 pkg.applicationInfo.sourceDir = destCodePath;
2609 pkg.applicationInfo.publicSourceDir = destResPath;
2610 }
2611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 private static String fixProcessName(String defProcessName,
2613 String processName, int uid) {
2614 if (processName == null) {
2615 return defProcessName;
2616 }
2617 return processName;
2618 }
2619
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002620 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2622 if (pkg.mSignatures != null) {
2623 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2624 updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002625 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 + " signatures do not match the previously installed version; ignoring!");
2627 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2628 return false;
2629 }
2630
2631 if (pkgSetting.sharedUser != null) {
2632 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2633 pkg.mSignatures, updateSignature)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002634 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 + " has no signatures that match those in shared user "
2636 + pkgSetting.sharedUser.name + "; ignoring!");
2637 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2638 return false;
2639 }
2640 }
2641 } else {
2642 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2643 }
2644 return true;
2645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002646
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002647 public boolean performDexOpt(String packageName) {
2648 if (!mNoDexOpt) {
2649 return false;
2650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002651
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002652 PackageParser.Package p;
2653 synchronized (mPackages) {
2654 p = mPackages.get(packageName);
2655 if (p == null || p.mDidDexOpt) {
2656 return false;
2657 }
2658 }
2659 synchronized (mInstallLock) {
2660 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2661 }
2662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002663
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002664 static final int DEX_OPT_SKIPPED = 0;
2665 static final int DEX_OPT_PERFORMED = 1;
2666 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002667
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002668 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2669 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002670 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002671 String path = pkg.mScanPath;
2672 int ret = 0;
2673 try {
2674 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002675 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002676 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002677 pkg.mDidDexOpt = true;
2678 performed = true;
2679 }
2680 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002681 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002682 ret = -1;
2683 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002684 Slog.w(TAG, "Exception reading apk: " + path, e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002685 ret = -1;
2686 }
2687 if (ret < 0) {
2688 //error from installer
2689 return DEX_OPT_FAILED;
2690 }
2691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002692
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002693 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2694 }
2695
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002696 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2697 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002698 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002699 + " to " + newPkg.packageName
2700 + ": old package not in system partition");
2701 return false;
2702 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002703 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002704 + " to " + newPkg.packageName
2705 + ": old package still exists");
2706 return false;
2707 }
2708 return true;
2709 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002710
2711 private File getDataPathForPackage(PackageParser.Package pkg) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07002712 return new File(mAppDataDir, pkg.packageName);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002713 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002714
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002715 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2716 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002717 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002718 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2719 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002720 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002721 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002722 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2723 return null;
2724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 mScanningPath = scanFile;
2726 if (pkg == null) {
2727 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2728 return null;
2729 }
2730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2732 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2733 }
2734
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002735 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 synchronized (mPackages) {
2737 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002738 Slog.w(TAG, "*************************************************");
2739 Slog.w(TAG, "Core android package being redefined. Skipping.");
2740 Slog.w(TAG, " file=" + mScanningPath);
2741 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2743 return null;
2744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 // Set up information for our fall-back user intent resolution
2747 // activity.
2748 mPlatformPackage = pkg;
2749 pkg.mVersionCode = mSdkVersion;
2750 mAndroidApplication = pkg.applicationInfo;
2751 mResolveActivity.applicationInfo = mAndroidApplication;
2752 mResolveActivity.name = ResolverActivity.class.getName();
2753 mResolveActivity.packageName = mAndroidApplication.packageName;
2754 mResolveActivity.processName = mAndroidApplication.processName;
2755 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2756 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2757 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2758 mResolveActivity.exported = true;
2759 mResolveActivity.enabled = true;
2760 mResolveInfo.activityInfo = mResolveActivity;
2761 mResolveInfo.priority = 0;
2762 mResolveInfo.preferredOrder = 0;
2763 mResolveInfo.match = 0;
2764 mResolveComponentName = new ComponentName(
2765 mAndroidApplication.packageName, mResolveActivity.name);
2766 }
2767 }
2768
2769 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002770 TAG, "Scanning package " + pkg.packageName);
2771 if (mPackages.containsKey(pkg.packageName)
2772 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002773 Slog.w(TAG, "*************************************************");
2774 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002776 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2778 return null;
2779 }
2780
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002781 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002782 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2783 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 SharedUserSetting suid = null;
2786 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002787
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002788 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2789 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002790 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002791 pkg.mRealPackage = null;
2792 pkg.mAdoptPermissions = null;
2793 }
2794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 synchronized (mPackages) {
2796 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002797 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2798 if (mTmpSharedLibraries == null ||
2799 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2800 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2801 }
2802 int num = 0;
2803 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2804 for (int i=0; i<N; i++) {
2805 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002807 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002809 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002810 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2811 return null;
2812 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002813 mTmpSharedLibraries[num] = file;
2814 num++;
2815 }
2816 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2817 for (int i=0; i<N; i++) {
2818 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2819 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002821 + " desires unavailable shared library "
2822 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2823 } else {
2824 mTmpSharedLibraries[num] = file;
2825 num++;
2826 }
2827 }
2828 if (num > 0) {
2829 pkg.usesLibraryFiles = new String[num];
2830 System.arraycopy(mTmpSharedLibraries, 0,
2831 pkg.usesLibraryFiles, 0, num);
2832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002833
Dianne Hackborn49237342009-08-27 20:08:01 -07002834 if (pkg.reqFeatures != null) {
2835 N = pkg.reqFeatures.size();
2836 for (int i=0; i<N; i++) {
2837 FeatureInfo fi = pkg.reqFeatures.get(i);
2838 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2839 // Don't care.
2840 continue;
2841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002842
Dianne Hackborn49237342009-08-27 20:08:01 -07002843 if (fi.name != null) {
2844 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002845 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002846 + " requires unavailable feature "
2847 + fi.name + "; failing!");
2848 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2849 return null;
2850 }
2851 }
2852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 }
2854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 if (pkg.mSharedUserId != null) {
2857 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2858 pkg.applicationInfo.flags, true);
2859 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002860 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 + " for shared user failed");
2862 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2863 return null;
2864 }
2865 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2866 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2867 + suid.userId + "): packages=" + suid.packages);
2868 }
2869 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002870
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002871 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002872 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002873 Log.w(TAG, "WAITING FOR DEBUGGER");
2874 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002875 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2876 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 }
2878 }
2879
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002880 // Check if we are renaming from an original package name.
2881 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002882 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002883 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002884 // This package may need to be renamed to a previously
2885 // installed name. Let's check on that...
2886 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002887 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 // This package had originally been installed as the
2889 // original name, and we have already taken care of
2890 // transitioning to the new one. Just update the new
2891 // one to continue using the old name.
2892 realName = pkg.mRealPackage;
2893 if (!pkg.packageName.equals(renamed)) {
2894 // Callers into this function may have already taken
2895 // care of renaming the package; only do it here if
2896 // it is not already done.
2897 pkg.setPackageName(renamed);
2898 }
2899
Dianne Hackbornc1552392010-03-03 16:19:01 -08002900 } else {
2901 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2902 if ((origPackage=mSettings.peekPackageLP(
2903 pkg.mOriginalPackages.get(i))) != null) {
2904 // We do have the package already installed under its
2905 // original name... should we use it?
2906 if (!verifyPackageUpdate(origPackage, pkg)) {
2907 // New package is not compatible with original.
2908 origPackage = null;
2909 continue;
2910 } else if (origPackage.sharedUser != null) {
2911 // Make sure uid is compatible between packages.
2912 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002913 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002914 + " to " + pkg.packageName + ": old uid "
2915 + origPackage.sharedUser.name
2916 + " differs from " + pkg.mSharedUserId);
2917 origPackage = null;
2918 continue;
2919 }
2920 } else {
2921 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2922 + pkg.packageName + " to old name " + origPackage.name);
2923 }
2924 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002925 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002926 }
2927 }
2928 }
2929
2930 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002931 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002932 + " was transferred to another, but its .apk remains");
2933 }
2934
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002935 // Just create the setting, don't add it yet. For already existing packages
2936 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002937 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 destResourceFile, pkg.applicationInfo.flags, true, false);
2939 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002940 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2942 return null;
2943 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002944
2945 if (pkgSetting.origPackage != null) {
2946 // If we are first transitioning from an original package,
2947 // fix up the new package's name now. We need to do this after
2948 // looking up the package under its new name, so getPackageLP
2949 // can take care of fiddling things correctly.
2950 pkg.setPackageName(origPackage.name);
2951
2952 // File a report about this.
2953 String msg = "New package " + pkgSetting.realName
2954 + " renamed to replace old package " + pkgSetting.name;
2955 reportSettingsProblem(Log.WARN, msg);
2956
2957 // Make a note of it.
2958 mTransferedPackages.add(origPackage.name);
2959
2960 // No longer need to retain this.
2961 pkgSetting.origPackage = null;
2962 }
2963
2964 if (realName != null) {
2965 // Make a note of it.
2966 mTransferedPackages.add(pkg.packageName);
2967 }
2968
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002969 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2971 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 pkg.applicationInfo.uid = pkgSetting.userId;
2974 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002975
2976 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002978 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2980 return null;
2981 }
2982 // The signature has changed, but this package is in the system
2983 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002984 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 // However... if this package is part of a shared user, but it
2986 // doesn't match the signature of the shared user, let's fail.
2987 // What this means is that you can't change the signatures
2988 // associated with an overall shared user, which doesn't seem all
2989 // that unreasonable.
2990 if (pkgSetting.sharedUser != null) {
2991 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2992 pkg.mSignatures, false)) {
2993 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2994 return null;
2995 }
2996 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07002997 // File a report about this.
2998 String msg = "System package " + pkg.packageName
2999 + " signature changed; retaining data.";
3000 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003002
The Android Open Source Project10592532009-03-18 17:39:46 -07003003 // Verify that this new package doesn't have any content providers
3004 // that conflict with existing packages. Only do this if the
3005 // package isn't already installed, since we don't want to break
3006 // things that are installed.
3007 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3008 int N = pkg.providers.size();
3009 int i;
3010 for (i=0; i<N; i++) {
3011 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003012 if (p.info.authority != null) {
3013 String names[] = p.info.authority.split(";");
3014 for (int j = 0; j < names.length; j++) {
3015 if (mProviders.containsKey(names[j])) {
3016 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003017 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003018 " (in package " + pkg.applicationInfo.packageName +
3019 ") is already used by "
3020 + ((other != null && other.getComponentName() != null)
3021 ? other.getComponentName().getPackageName() : "?"));
3022 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3023 return null;
3024 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003025 }
3026 }
3027 }
3028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
3030
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003031 final String pkgName = pkg.packageName;
3032
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003033 if (pkg.mAdoptPermissions != null) {
3034 // This package wants to adopt ownership of permissions from
3035 // another package.
3036 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3037 String origName = pkg.mAdoptPermissions.get(i);
3038 PackageSetting orig = mSettings.peekPackageLP(origName);
3039 if (orig != null) {
3040 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003041 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003042 + origName + " to " + pkg.packageName);
3043 mSettings.transferPermissions(origName, pkg.packageName);
3044 }
3045 }
3046 }
3047 }
3048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 long scanFileTime = scanFile.lastModified();
3050 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3051 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3052 pkg.applicationInfo.processName = fixProcessName(
3053 pkg.applicationInfo.packageName,
3054 pkg.applicationInfo.processName,
3055 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056
3057 File dataPath;
3058 if (mPlatformPackage == pkg) {
3059 // The system package is special.
3060 dataPath = new File (Environment.getDataDirectory(), "system");
3061 pkg.applicationInfo.dataDir = dataPath.getPath();
3062 } else {
3063 // This is a normal package, need to make its data directory.
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003064 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003065
3066 boolean uidError = false;
3067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 if (dataPath.exists()) {
3069 mOutPermissions[1] = 0;
3070 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3071 if (mOutPermissions[1] == pkg.applicationInfo.uid
3072 || !Process.supportsProcesses()) {
3073 pkg.applicationInfo.dataDir = dataPath.getPath();
3074 } else {
3075 boolean recovered = false;
3076 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3077 // If this is a system app, we can at least delete its
3078 // current data so the application will still work.
3079 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003080 int ret = mInstaller.remove(pkgName);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003081 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 // Old data gone!
3083 String msg = "System package " + pkg.packageName
3084 + " has changed from uid: "
3085 + mOutPermissions[1] + " to "
3086 + pkg.applicationInfo.uid + "; old data erased";
3087 reportSettingsProblem(Log.WARN, msg);
3088 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 // And now re-install the app.
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003091 ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 pkg.applicationInfo.uid);
3093 if (ret == -1) {
3094 // Ack should not happen!
3095 msg = "System package " + pkg.packageName
3096 + " could not have data directory re-created after delete.";
3097 reportSettingsProblem(Log.WARN, msg);
3098 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3099 return null;
3100 }
3101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 if (!recovered) {
3104 mHasSystemUidErrors = true;
3105 }
3106 }
3107 if (!recovered) {
3108 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3109 + pkg.applicationInfo.uid + "/fs_"
3110 + mOutPermissions[1];
3111 String msg = "Package " + pkg.packageName
3112 + " has mismatched uid: "
3113 + mOutPermissions[1] + " on disk, "
3114 + pkg.applicationInfo.uid + " in settings";
3115 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003116 mSettings.mReadMessages.append(msg);
3117 mSettings.mReadMessages.append('\n');
3118 uidError = true;
3119 if (!pkgSetting.uidError) {
3120 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 }
3123 }
3124 }
3125 pkg.applicationInfo.dataDir = dataPath.getPath();
3126 } else {
3127 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3128 Log.v(TAG, "Want this data dir: " + dataPath);
3129 //invoke installer to do the actual installation
3130 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07003131 int ret = mInstaller.install(pkgName, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 pkg.applicationInfo.uid);
3133 if(ret < 0) {
3134 // Error from installer
3135 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3136 return null;
3137 }
3138 } else {
3139 dataPath.mkdirs();
3140 if (dataPath.exists()) {
3141 FileUtils.setPermissions(
3142 dataPath.toString(),
3143 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3144 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3145 }
3146 }
3147 if (dataPath.exists()) {
3148 pkg.applicationInfo.dataDir = dataPath.getPath();
3149 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003150 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 pkg.applicationInfo.dataDir = null;
3152 }
3153 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003154
3155 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 }
3157
3158 // Perform shared library installation and dex validation and
3159 // optimization, if this is not a system app.
3160 if (mInstaller != null) {
3161 String path = scanFile.getPath();
3162 if (scanFileNewer) {
3163 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003164 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3165 if (err != PackageManager.INSTALL_SUCCEEDED) {
3166 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 return null;
3168 }
3169 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003170 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003171
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003172 if ((scanMode&SCAN_NO_DEX) == 0) {
3173 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3175 return null;
3176 }
3177 }
3178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 if (mFactoryTest && pkg.requestedPermissions.contains(
3181 android.Manifest.permission.FACTORY_TEST)) {
3182 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3183 }
3184
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003185 // Request the ActivityManager to kill the process(only for existing packages)
3186 // so that we do not end up in a confused state while the user is still using the older
3187 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003188 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003189 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003190 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003191 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003194 // We don't expect installation to fail beyond this point,
3195 if ((scanMode&SCAN_MONITOR) != 0) {
3196 mAppDirs.put(pkg.mPath, pkg);
3197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003199 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003201 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003202 // Make sure we don't accidentally delete its data.
3203 mSettings.mPackagesToBeCleaned.remove(pkgName);
3204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 int N = pkg.providers.size();
3206 StringBuilder r = null;
3207 int i;
3208 for (i=0; i<N; i++) {
3209 PackageParser.Provider p = pkg.providers.get(i);
3210 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3211 p.info.processName, pkg.applicationInfo.uid);
3212 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3213 p.info.name), p);
3214 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003215 if (p.info.authority != null) {
3216 String names[] = p.info.authority.split(";");
3217 p.info.authority = null;
3218 for (int j = 0; j < names.length; j++) {
3219 if (j == 1 && p.syncable) {
3220 // We only want the first authority for a provider to possibly be
3221 // syncable, so if we already added this provider using a different
3222 // authority clear the syncable flag. We copy the provider before
3223 // changing it because the mProviders object contains a reference
3224 // to a provider that we don't want to change.
3225 // Only do this for the second authority since the resulting provider
3226 // object can be the same for all future authorities for this provider.
3227 p = new PackageParser.Provider(p);
3228 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003230 if (!mProviders.containsKey(names[j])) {
3231 mProviders.put(names[j], p);
3232 if (p.info.authority == null) {
3233 p.info.authority = names[j];
3234 } else {
3235 p.info.authority = p.info.authority + ";" + names[j];
3236 }
3237 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3238 Log.d(TAG, "Registered content provider: " + names[j] +
3239 ", className = " + p.info.name +
3240 ", isSyncable = " + p.info.isSyncable);
3241 } else {
3242 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003243 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003244 " (in package " + pkg.applicationInfo.packageName +
3245 "): name already used by "
3246 + ((other != null && other.getComponentName() != null)
3247 ? other.getComponentName().getPackageName() : "?"));
3248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 }
3250 }
3251 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3252 if (r == null) {
3253 r = new StringBuilder(256);
3254 } else {
3255 r.append(' ');
3256 }
3257 r.append(p.info.name);
3258 }
3259 }
3260 if (r != null) {
3261 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3262 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 N = pkg.services.size();
3265 r = null;
3266 for (i=0; i<N; i++) {
3267 PackageParser.Service s = pkg.services.get(i);
3268 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3269 s.info.processName, pkg.applicationInfo.uid);
3270 mServices.addService(s);
3271 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3272 if (r == null) {
3273 r = new StringBuilder(256);
3274 } else {
3275 r.append(' ');
3276 }
3277 r.append(s.info.name);
3278 }
3279 }
3280 if (r != null) {
3281 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 N = pkg.receivers.size();
3285 r = null;
3286 for (i=0; i<N; i++) {
3287 PackageParser.Activity a = pkg.receivers.get(i);
3288 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3289 a.info.processName, pkg.applicationInfo.uid);
3290 mReceivers.addActivity(a, "receiver");
3291 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3292 if (r == null) {
3293 r = new StringBuilder(256);
3294 } else {
3295 r.append(' ');
3296 }
3297 r.append(a.info.name);
3298 }
3299 }
3300 if (r != null) {
3301 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 N = pkg.activities.size();
3305 r = null;
3306 for (i=0; i<N; i++) {
3307 PackageParser.Activity a = pkg.activities.get(i);
3308 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3309 a.info.processName, pkg.applicationInfo.uid);
3310 mActivities.addActivity(a, "activity");
3311 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3312 if (r == null) {
3313 r = new StringBuilder(256);
3314 } else {
3315 r.append(' ');
3316 }
3317 r.append(a.info.name);
3318 }
3319 }
3320 if (r != null) {
3321 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 N = pkg.permissionGroups.size();
3325 r = null;
3326 for (i=0; i<N; i++) {
3327 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3328 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3329 if (cur == null) {
3330 mPermissionGroups.put(pg.info.name, pg);
3331 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3332 if (r == null) {
3333 r = new StringBuilder(256);
3334 } else {
3335 r.append(' ');
3336 }
3337 r.append(pg.info.name);
3338 }
3339 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003340 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 + pg.info.packageName + " ignored: original from "
3342 + cur.info.packageName);
3343 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3344 if (r == null) {
3345 r = new StringBuilder(256);
3346 } else {
3347 r.append(' ');
3348 }
3349 r.append("DUP:");
3350 r.append(pg.info.name);
3351 }
3352 }
3353 }
3354 if (r != null) {
3355 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3356 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 N = pkg.permissions.size();
3359 r = null;
3360 for (i=0; i<N; i++) {
3361 PackageParser.Permission p = pkg.permissions.get(i);
3362 HashMap<String, BasePermission> permissionMap =
3363 p.tree ? mSettings.mPermissionTrees
3364 : mSettings.mPermissions;
3365 p.group = mPermissionGroups.get(p.info.group);
3366 if (p.info.group == null || p.group != null) {
3367 BasePermission bp = permissionMap.get(p.info.name);
3368 if (bp == null) {
3369 bp = new BasePermission(p.info.name, p.info.packageName,
3370 BasePermission.TYPE_NORMAL);
3371 permissionMap.put(p.info.name, bp);
3372 }
3373 if (bp.perm == null) {
3374 if (bp.sourcePackage == null
3375 || bp.sourcePackage.equals(p.info.packageName)) {
3376 BasePermission tree = findPermissionTreeLP(p.info.name);
3377 if (tree == null
3378 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003379 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 bp.perm = p;
3381 bp.uid = pkg.applicationInfo.uid;
3382 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3383 if (r == null) {
3384 r = new StringBuilder(256);
3385 } else {
3386 r.append(' ');
3387 }
3388 r.append(p.info.name);
3389 }
3390 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003391 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 + p.info.packageName + " ignored: base tree "
3393 + tree.name + " is from package "
3394 + tree.sourcePackage);
3395 }
3396 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003397 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 + p.info.packageName + " ignored: original from "
3399 + bp.sourcePackage);
3400 }
3401 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3402 if (r == null) {
3403 r = new StringBuilder(256);
3404 } else {
3405 r.append(' ');
3406 }
3407 r.append("DUP:");
3408 r.append(p.info.name);
3409 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003410 if (bp.perm == p) {
3411 bp.protectionLevel = p.info.protectionLevel;
3412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003414 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 + p.info.packageName + " ignored: no group "
3416 + p.group);
3417 }
3418 }
3419 if (r != null) {
3420 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3421 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 N = pkg.instrumentation.size();
3424 r = null;
3425 for (i=0; i<N; i++) {
3426 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3427 a.info.packageName = pkg.applicationInfo.packageName;
3428 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3429 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3430 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003431 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3433 if (r == null) {
3434 r = new StringBuilder(256);
3435 } else {
3436 r.append(' ');
3437 }
3438 r.append(a.info.name);
3439 }
3440 }
3441 if (r != null) {
3442 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003444
Dianne Hackborn854060af2009-07-09 18:14:31 -07003445 if (pkg.protectedBroadcasts != null) {
3446 N = pkg.protectedBroadcasts.size();
3447 for (i=0; i<N; i++) {
3448 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3449 }
3450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 pkgSetting.setTimeStamp(scanFileTime);
3453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 return pkg;
3456 }
3457
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003458 private void killApplication(String pkgName, int uid) {
3459 // Request the ActivityManager to kill the process(only for existing packages)
3460 // so that we do not end up in a confused state while the user is still using the older
3461 // version of the application while the new one gets installed.
3462 IActivityManager am = ActivityManagerNative.getDefault();
3463 if (am != null) {
3464 try {
3465 am.killApplicationWithUid(pkgName, uid);
3466 } catch (RemoteException e) {
3467 }
3468 }
3469 }
3470
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003471 // The following constants are returned by cachePackageSharedLibsForAbiLI
3472 // to indicate if native shared libraries were found in the package.
3473 // Values are:
3474 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3475 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3476 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3477 // in package (and not installed)
3478 //
3479 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3480 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3481 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003483 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3484 // and automatically copy them to /data/data/<appname>/lib if present.
3485 //
3486 // NOTE: this method may throw an IOException if the library cannot
3487 // be copied to its final destination, e.g. if there isn't enough
3488 // room left on the data partition, or a ZipException if the package
3489 // file is malformed.
3490 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003491 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3492 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003493 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3494 final String apkLib = "lib/";
3495 final int apkLibLen = apkLib.length();
3496 final int cpuAbiLen = cpuAbi.length();
3497 final String libPrefix = "lib";
3498 final int libPrefixLen = libPrefix.length();
3499 final String libSuffix = ".so";
3500 final int libSuffixLen = libSuffix.length();
3501 boolean hasNativeLibraries = false;
3502 boolean installedNativeLibraries = false;
3503
3504 // the minimum length of a valid native shared library of the form
3505 // lib/<something>/lib<name>.so.
3506 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
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 // check that the entry looks like lib/<something>/lib<name>.so
3521 // here, but don't check the ABI just yet.
3522 //
3523 // - must be sufficiently long
3524 // - must end with libSuffix, i.e. ".so"
3525 // - must start with apkLib, i.e. "lib/"
3526 if (entryName.length() < minEntryLen ||
3527 !entryName.endsWith(libSuffix) ||
3528 !entryName.startsWith(apkLib) ) {
3529 continue;
3530 }
3531
3532 // file name must start with libPrefix, i.e. "lib"
3533 int lastSlash = entryName.lastIndexOf('/');
3534
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003535 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003536 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3537 continue;
3538 }
3539
3540 hasNativeLibraries = true;
3541
3542 // check the cpuAbi now, between lib/ and /lib<name>.so
3543 //
3544 if (lastSlash != apkLibLen + cpuAbiLen ||
3545 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3546 continue;
3547
3548 // extract the library file name, ensure it doesn't contain
3549 // weird characters. we're guaranteed here that it doesn't contain
3550 // a directory separator though.
3551 String libFileName = entryName.substring(lastSlash+1);
3552 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3553 continue;
3554 }
3555
3556 installedNativeLibraries = true;
3557
3558 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3559 File.separator + libFileName;
3560 File sharedLibraryFile = new File(sharedLibraryFilePath);
3561 if (! sharedLibraryFile.exists() ||
3562 sharedLibraryFile.length() != entry.getSize() ||
3563 sharedLibraryFile.lastModified() != entry.getTime()) {
3564 if (Config.LOGD) {
3565 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003567 if (mInstaller == null) {
3568 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003569 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003570 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003571 sharedLibraryFile);
3572 }
3573 }
3574 if (!hasNativeLibraries)
3575 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3576
3577 if (!installedNativeLibraries)
3578 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3579
3580 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3581 }
3582
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003583 // Find the gdbserver executable program in a package at
3584 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3585 //
3586 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3587 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3588 //
3589 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3590 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3591 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3592 final String GDBSERVER = "gdbserver";
3593 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3594
3595 ZipFile zipFile = new ZipFile(scanFile);
3596 Enumeration<ZipEntry> entries =
3597 (Enumeration<ZipEntry>) zipFile.entries();
3598
3599 while (entries.hasMoreElements()) {
3600 ZipEntry entry = entries.nextElement();
3601 // skip directories
3602 if (entry.isDirectory()) {
3603 continue;
3604 }
3605 String entryName = entry.getName();
3606
3607 if (!entryName.equals(apkGdbServerPath)) {
3608 continue;
3609 }
3610
3611 String installGdbServerPath = installGdbServerDir.getPath() +
3612 "/" + GDBSERVER;
3613 File installGdbServerFile = new File(installGdbServerPath);
3614 if (! installGdbServerFile.exists() ||
3615 installGdbServerFile.length() != entry.getSize() ||
3616 installGdbServerFile.lastModified() != entry.getTime()) {
3617 if (Config.LOGD) {
3618 Log.d(TAG, "Caching gdbserver " + entry.getName());
3619 }
3620 if (mInstaller == null) {
3621 installGdbServerDir.mkdir();
3622 }
3623 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3624 installGdbServerFile);
3625 }
3626 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3627 }
3628 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3629 }
3630
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003631 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3632 // and copy them to /data/data/<appname>/lib.
3633 //
3634 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3635 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3636 // one if ro.product.cpu.abi2 is defined.
3637 //
3638 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3639 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003640 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003641 try {
3642 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3643
3644 // some architectures are capable of supporting several CPU ABIs
3645 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3646 // this is indicated by the definition of the ro.product.cpu.abi2
3647 // system property.
3648 //
3649 // only scan the package twice in case of ABI mismatch
3650 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003651 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003652 if (cpuAbi2 != null) {
3653 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003655
3656 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003657 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003658 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003660
3661 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3662 cpuAbi = cpuAbi2;
3663 }
3664 }
3665
3666 // for debuggable packages, also extract gdbserver from lib/<abi>
3667 // into /data/data/<appname>/lib too.
3668 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3669 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3670 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3671 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3672 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003675 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003676 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003677 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003679 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003680 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003682 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
3684
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003685 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003687 File binaryDir,
3688 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 InputStream inputStream = zipFile.getInputStream(entry);
3690 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003691 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003693 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 // now need to be left as world readable and owned by the system.
3695 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3696 ! tempFile.setLastModified(entry.getTime()) ||
3697 FileUtils.setPermissions(tempFilePath,
3698 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003699 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003701 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 // Failed to properly write file.
3703 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003704 throw new IOException("Couldn't create cached binary "
3705 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 }
3707 } finally {
3708 inputStream.close();
3709 }
3710 }
3711
3712 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3713 if (chatty && Config.LOGD) Log.d(
3714 TAG, "Removing package " + pkg.applicationInfo.packageName );
3715
3716 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 mPackages.remove(pkg.applicationInfo.packageName);
3720 if (pkg.mPath != null) {
3721 mAppDirs.remove(pkg.mPath);
3722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 PackageSetting ps = (PackageSetting)pkg.mExtras;
3725 if (ps != null && ps.sharedUser != null) {
3726 // XXX don't do this until the data is removed.
3727 if (false) {
3728 ps.sharedUser.packages.remove(ps);
3729 if (ps.sharedUser.packages.size() == 0) {
3730 // Remove.
3731 }
3732 }
3733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 int N = pkg.providers.size();
3736 StringBuilder r = null;
3737 int i;
3738 for (i=0; i<N; i++) {
3739 PackageParser.Provider p = pkg.providers.get(i);
3740 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3741 p.info.name));
3742 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 /* The is another ContentProvider with this authority when
3745 * this app was installed so this authority is null,
3746 * Ignore it as we don't have to unregister the provider.
3747 */
3748 continue;
3749 }
3750 String names[] = p.info.authority.split(";");
3751 for (int j = 0; j < names.length; j++) {
3752 if (mProviders.get(names[j]) == p) {
3753 mProviders.remove(names[j]);
3754 if (chatty && Config.LOGD) Log.d(
3755 TAG, "Unregistered content provider: " + names[j] +
3756 ", className = " + p.info.name +
3757 ", isSyncable = " + p.info.isSyncable);
3758 }
3759 }
3760 if (chatty) {
3761 if (r == null) {
3762 r = new StringBuilder(256);
3763 } else {
3764 r.append(' ');
3765 }
3766 r.append(p.info.name);
3767 }
3768 }
3769 if (r != null) {
3770 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3771 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 N = pkg.services.size();
3774 r = null;
3775 for (i=0; i<N; i++) {
3776 PackageParser.Service s = pkg.services.get(i);
3777 mServices.removeService(s);
3778 if (chatty) {
3779 if (r == null) {
3780 r = new StringBuilder(256);
3781 } else {
3782 r.append(' ');
3783 }
3784 r.append(s.info.name);
3785 }
3786 }
3787 if (r != null) {
3788 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3789 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 N = pkg.receivers.size();
3792 r = null;
3793 for (i=0; i<N; i++) {
3794 PackageParser.Activity a = pkg.receivers.get(i);
3795 mReceivers.removeActivity(a, "receiver");
3796 if (chatty) {
3797 if (r == null) {
3798 r = new StringBuilder(256);
3799 } else {
3800 r.append(' ');
3801 }
3802 r.append(a.info.name);
3803 }
3804 }
3805 if (r != null) {
3806 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 N = pkg.activities.size();
3810 r = null;
3811 for (i=0; i<N; i++) {
3812 PackageParser.Activity a = pkg.activities.get(i);
3813 mActivities.removeActivity(a, "activity");
3814 if (chatty) {
3815 if (r == null) {
3816 r = new StringBuilder(256);
3817 } else {
3818 r.append(' ');
3819 }
3820 r.append(a.info.name);
3821 }
3822 }
3823 if (r != null) {
3824 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 N = pkg.permissions.size();
3828 r = null;
3829 for (i=0; i<N; i++) {
3830 PackageParser.Permission p = pkg.permissions.get(i);
3831 boolean tree = false;
3832 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3833 if (bp == null) {
3834 tree = true;
3835 bp = mSettings.mPermissionTrees.get(p.info.name);
3836 }
3837 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003838 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 if (chatty) {
3840 if (r == null) {
3841 r = new StringBuilder(256);
3842 } else {
3843 r.append(' ');
3844 }
3845 r.append(p.info.name);
3846 }
3847 }
3848 }
3849 if (r != null) {
3850 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 N = pkg.instrumentation.size();
3854 r = null;
3855 for (i=0; i<N; i++) {
3856 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003857 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 if (chatty) {
3859 if (r == null) {
3860 r = new StringBuilder(256);
3861 } else {
3862 r.append(' ');
3863 }
3864 r.append(a.info.name);
3865 }
3866 }
3867 if (r != null) {
3868 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3869 }
3870 }
3871 }
3872
3873 private static final boolean isPackageFilename(String name) {
3874 return name != null && name.endsWith(".apk");
3875 }
3876
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003877 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3878 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3879 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3880 return true;
3881 }
3882 }
3883 return false;
3884 }
3885
3886 private void updatePermissionsLP(String changingPkg,
3887 PackageParser.Package pkgInfo, boolean grantPermissions, boolean replace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 // Make sure there are no dangling permission trees.
3889 Iterator<BasePermission> it = mSettings.mPermissionTrees
3890 .values().iterator();
3891 while (it.hasNext()) {
3892 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003893 if (bp.packageSetting == null) {
3894 // We may not yet have parsed the package, so just see if
3895 // we still know about its settings.
3896 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3897 }
3898 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003899 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 + " from package " + bp.sourcePackage);
3901 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003902 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3903 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3904 Slog.i(TAG, "Removing old permission tree: " + bp.name
3905 + " from package " + bp.sourcePackage);
3906 grantPermissions = true;
3907 it.remove();
3908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 }
3910 }
3911
3912 // Make sure all dynamic permissions have been assigned to a package,
3913 // and make sure there are no dangling permissions.
3914 it = mSettings.mPermissions.values().iterator();
3915 while (it.hasNext()) {
3916 BasePermission bp = it.next();
3917 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3918 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3919 + bp.name + " pkg=" + bp.sourcePackage
3920 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003921 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 BasePermission tree = findPermissionTreeLP(bp.name);
3923 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003924 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 bp.perm = new PackageParser.Permission(tree.perm.owner,
3926 new PermissionInfo(bp.pendingInfo));
3927 bp.perm.info.packageName = tree.perm.info.packageName;
3928 bp.perm.info.name = bp.name;
3929 bp.uid = tree.uid;
3930 }
3931 }
3932 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003933 if (bp.packageSetting == null) {
3934 // We may not yet have parsed the package, so just see if
3935 // we still know about its settings.
3936 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3937 }
3938 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003939 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 + " from package " + bp.sourcePackage);
3941 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003942 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3943 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3944 Slog.i(TAG, "Removing old permission: " + bp.name
3945 + " from package " + bp.sourcePackage);
3946 grantPermissions = true;
3947 it.remove();
3948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
3950 }
3951
3952 // Now update the permissions for all packages, in particular
3953 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003954 if (grantPermissions) {
3955 for (PackageParser.Package pkg : mPackages.values()) {
3956 if (pkg != pkgInfo) {
3957 grantPermissionsLP(pkg, false);
3958 }
3959 }
3960 }
3961
3962 if (pkgInfo != null) {
3963 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 }
3965 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3968 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3969 if (ps == null) {
3970 return;
3971 }
3972 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003973 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 if (replace) {
3976 ps.permissionsFixed = false;
3977 if (gp == ps) {
3978 gp.grantedPermissions.clear();
3979 gp.gids = mGlobalGids;
3980 }
3981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 if (gp.gids == null) {
3984 gp.gids = mGlobalGids;
3985 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 final int N = pkg.requestedPermissions.size();
3988 for (int i=0; i<N; i++) {
3989 String name = pkg.requestedPermissions.get(i);
3990 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 if (false) {
3992 if (gp != ps) {
3993 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003994 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 }
3996 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003997 if (bp != null && bp.packageSetting != null) {
3998 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004000 boolean allowedSig = false;
4001 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4002 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 allowed = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004004 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4005 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4006 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004008 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004010 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4012 // For updated system applications, the signatureOrSystem permission
4013 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004014 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4016 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4017 if(sysPs.grantedPermissions.contains(perm)) {
4018 allowed = true;
4019 } else {
4020 allowed = false;
4021 }
4022 } else {
4023 allowed = true;
4024 }
4025 }
4026 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004027 if (allowed) {
4028 allowedSig = true;
4029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 } else {
4031 allowed = false;
4032 }
4033 if (false) {
4034 if (gp != ps) {
4035 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4036 }
4037 }
4038 if (allowed) {
4039 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4040 && ps.permissionsFixed) {
4041 // If this is an existing, non-system package, then
4042 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004043 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004045 // Except... if this is a permission that was added
4046 // to the platform (note: need to only do this when
4047 // updating the platform).
4048 final int NP = PackageParser.NEW_PERMISSIONS.length;
4049 for (int ip=0; ip<NP; ip++) {
4050 final PackageParser.NewPermissionInfo npi
4051 = PackageParser.NEW_PERMISSIONS[ip];
4052 if (npi.name.equals(perm)
4053 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4054 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004055 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004056 + pkg.packageName);
4057 break;
4058 }
4059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 }
4061 }
4062 if (allowed) {
4063 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004064 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 gp.grantedPermissions.add(perm);
4066 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004067 } else if (!ps.haveGids) {
4068 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 }
4070 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004071 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 + " to package " + pkg.packageName
4073 + " because it was previously installed without");
4074 }
4075 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004076 if (gp.grantedPermissions.remove(perm)) {
4077 changedPermission = true;
4078 gp.gids = removeInts(gp.gids, bp.gids);
4079 Slog.i(TAG, "Un-granting permission " + perm
4080 + " from package " + pkg.packageName
4081 + " (protectionLevel=" + bp.protectionLevel
4082 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4083 + ")");
4084 } else {
4085 Slog.w(TAG, "Not granting permission " + perm
4086 + " to package " + pkg.packageName
4087 + " (protectionLevel=" + bp.protectionLevel
4088 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4089 + ")");
4090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 }
4092 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004093 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 + " in package " + pkg.packageName);
4095 }
4096 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004097
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004098 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004099 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4100 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 // This is the first that we have heard about this package, so the
4102 // permissions we have now selected are fixed until explicitly
4103 // changed.
4104 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004106 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 private final class ActivityIntentResolver
4110 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004111 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004113 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 }
4115
Mihai Preda074edef2009-05-18 17:13:31 +02004116 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004118 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4120 }
4121
Mihai Predaeae850c2009-05-13 10:13:48 +02004122 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4123 ArrayList<PackageParser.Activity> packageActivities) {
4124 if (packageActivities == null) {
4125 return null;
4126 }
4127 mFlags = flags;
4128 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4129 int N = packageActivities.size();
4130 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4131 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004132
4133 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004134 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004135 intentFilters = packageActivities.get(i).intents;
4136 if (intentFilters != null && intentFilters.size() > 0) {
4137 listCut.add(intentFilters);
4138 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004139 }
4140 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4141 }
4142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004144 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 if (SHOW_INFO || Config.LOGV) Log.v(
4146 TAG, " " + type + " " +
4147 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4148 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4149 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004150 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4152 if (SHOW_INFO || Config.LOGV) {
4153 Log.v(TAG, " IntentFilter:");
4154 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4155 }
4156 if (!intent.debugCheck()) {
4157 Log.w(TAG, "==> For Activity " + a.info.name);
4158 }
4159 addFilter(intent);
4160 }
4161 }
4162
4163 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004164 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 if (SHOW_INFO || Config.LOGV) Log.v(
4166 TAG, " " + type + " " +
4167 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4168 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4169 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004170 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4172 if (SHOW_INFO || Config.LOGV) {
4173 Log.v(TAG, " IntentFilter:");
4174 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4175 }
4176 removeFilter(intent);
4177 }
4178 }
4179
4180 @Override
4181 protected boolean allowFilterResult(
4182 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4183 ActivityInfo filterAi = filter.activity.info;
4184 for (int i=dest.size()-1; i>=0; i--) {
4185 ActivityInfo destAi = dest.get(i).activityInfo;
4186 if (destAi.name == filterAi.name
4187 && destAi.packageName == filterAi.packageName) {
4188 return false;
4189 }
4190 }
4191 return true;
4192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004195 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4196 return info.activity.owner.packageName;
4197 }
4198
4199 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4201 int match) {
4202 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4203 return null;
4204 }
4205 final PackageParser.Activity activity = info.activity;
4206 if (mSafeMode && (activity.info.applicationInfo.flags
4207 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4208 return null;
4209 }
4210 final ResolveInfo res = new ResolveInfo();
4211 res.activityInfo = PackageParser.generateActivityInfo(activity,
4212 mFlags);
4213 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4214 res.filter = info;
4215 }
4216 res.priority = info.getPriority();
4217 res.preferredOrder = activity.owner.mPreferredOrder;
4218 //System.out.println("Result: " + res.activityInfo.className +
4219 // " = " + res.priority);
4220 res.match = match;
4221 res.isDefault = info.hasDefault;
4222 res.labelRes = info.labelRes;
4223 res.nonLocalizedLabel = info.nonLocalizedLabel;
4224 res.icon = info.icon;
4225 return res;
4226 }
4227
4228 @Override
4229 protected void sortResults(List<ResolveInfo> results) {
4230 Collections.sort(results, mResolvePrioritySorter);
4231 }
4232
4233 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004234 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004236 out.print(prefix); out.print(
4237 Integer.toHexString(System.identityHashCode(filter.activity)));
4238 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004239 out.print(filter.activity.getComponentShortName());
4240 out.print(" filter ");
4241 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 }
4243
4244// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4245// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4246// final List<ResolveInfo> retList = Lists.newArrayList();
4247// while (i.hasNext()) {
4248// final ResolveInfo resolveInfo = i.next();
4249// if (isEnabledLP(resolveInfo.activityInfo)) {
4250// retList.add(resolveInfo);
4251// }
4252// }
4253// return retList;
4254// }
4255
4256 // Keys are String (activity class name), values are Activity.
4257 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4258 = new HashMap<ComponentName, PackageParser.Activity>();
4259 private int mFlags;
4260 }
4261
4262 private final class ServiceIntentResolver
4263 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004264 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004266 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004267 }
4268
Mihai Preda074edef2009-05-18 17:13:31 +02004269 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004271 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4273 }
4274
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004275 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4276 ArrayList<PackageParser.Service> packageServices) {
4277 if (packageServices == null) {
4278 return null;
4279 }
4280 mFlags = flags;
4281 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4282 int N = packageServices.size();
4283 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4284 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4285
4286 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4287 for (int i = 0; i < N; ++i) {
4288 intentFilters = packageServices.get(i).intents;
4289 if (intentFilters != null && intentFilters.size() > 0) {
4290 listCut.add(intentFilters);
4291 }
4292 }
4293 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4294 }
4295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004297 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 if (SHOW_INFO || Config.LOGV) Log.v(
4299 TAG, " " + (s.info.nonLocalizedLabel != null
4300 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4301 if (SHOW_INFO || Config.LOGV) Log.v(
4302 TAG, " Class=" + s.info.name);
4303 int NI = s.intents.size();
4304 int j;
4305 for (j=0; j<NI; j++) {
4306 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4307 if (SHOW_INFO || Config.LOGV) {
4308 Log.v(TAG, " IntentFilter:");
4309 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4310 }
4311 if (!intent.debugCheck()) {
4312 Log.w(TAG, "==> For Service " + s.info.name);
4313 }
4314 addFilter(intent);
4315 }
4316 }
4317
4318 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004319 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 if (SHOW_INFO || Config.LOGV) Log.v(
4321 TAG, " " + (s.info.nonLocalizedLabel != null
4322 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4323 if (SHOW_INFO || Config.LOGV) Log.v(
4324 TAG, " Class=" + s.info.name);
4325 int NI = s.intents.size();
4326 int j;
4327 for (j=0; j<NI; j++) {
4328 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4329 if (SHOW_INFO || Config.LOGV) {
4330 Log.v(TAG, " IntentFilter:");
4331 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4332 }
4333 removeFilter(intent);
4334 }
4335 }
4336
4337 @Override
4338 protected boolean allowFilterResult(
4339 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4340 ServiceInfo filterSi = filter.service.info;
4341 for (int i=dest.size()-1; i>=0; i--) {
4342 ServiceInfo destAi = dest.get(i).serviceInfo;
4343 if (destAi.name == filterSi.name
4344 && destAi.packageName == filterSi.packageName) {
4345 return false;
4346 }
4347 }
4348 return true;
4349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004352 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4353 return info.service.owner.packageName;
4354 }
4355
4356 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4358 int match) {
4359 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4360 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4361 return null;
4362 }
4363 final PackageParser.Service service = info.service;
4364 if (mSafeMode && (service.info.applicationInfo.flags
4365 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4366 return null;
4367 }
4368 final ResolveInfo res = new ResolveInfo();
4369 res.serviceInfo = PackageParser.generateServiceInfo(service,
4370 mFlags);
4371 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4372 res.filter = filter;
4373 }
4374 res.priority = info.getPriority();
4375 res.preferredOrder = service.owner.mPreferredOrder;
4376 //System.out.println("Result: " + res.activityInfo.className +
4377 // " = " + res.priority);
4378 res.match = match;
4379 res.isDefault = info.hasDefault;
4380 res.labelRes = info.labelRes;
4381 res.nonLocalizedLabel = info.nonLocalizedLabel;
4382 res.icon = info.icon;
4383 return res;
4384 }
4385
4386 @Override
4387 protected void sortResults(List<ResolveInfo> results) {
4388 Collections.sort(results, mResolvePrioritySorter);
4389 }
4390
4391 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004392 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004394 out.print(prefix); out.print(
4395 Integer.toHexString(System.identityHashCode(filter.service)));
4396 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004397 out.print(filter.service.getComponentShortName());
4398 out.print(" filter ");
4399 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 }
4401
4402// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4403// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4404// final List<ResolveInfo> retList = Lists.newArrayList();
4405// while (i.hasNext()) {
4406// final ResolveInfo resolveInfo = (ResolveInfo) i;
4407// if (isEnabledLP(resolveInfo.serviceInfo)) {
4408// retList.add(resolveInfo);
4409// }
4410// }
4411// return retList;
4412// }
4413
4414 // Keys are String (activity class name), values are Activity.
4415 private final HashMap<ComponentName, PackageParser.Service> mServices
4416 = new HashMap<ComponentName, PackageParser.Service>();
4417 private int mFlags;
4418 };
4419
4420 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4421 new Comparator<ResolveInfo>() {
4422 public int compare(ResolveInfo r1, ResolveInfo r2) {
4423 int v1 = r1.priority;
4424 int v2 = r2.priority;
4425 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4426 if (v1 != v2) {
4427 return (v1 > v2) ? -1 : 1;
4428 }
4429 v1 = r1.preferredOrder;
4430 v2 = r2.preferredOrder;
4431 if (v1 != v2) {
4432 return (v1 > v2) ? -1 : 1;
4433 }
4434 if (r1.isDefault != r2.isDefault) {
4435 return r1.isDefault ? -1 : 1;
4436 }
4437 v1 = r1.match;
4438 v2 = r2.match;
4439 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4440 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4441 }
4442 };
4443
4444 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4445 new Comparator<ProviderInfo>() {
4446 public int compare(ProviderInfo p1, ProviderInfo p2) {
4447 final int v1 = p1.initOrder;
4448 final int v2 = p2.initOrder;
4449 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4450 }
4451 };
4452
4453 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4454 IActivityManager am = ActivityManagerNative.getDefault();
4455 if (am != null) {
4456 try {
4457 final Intent intent = new Intent(action,
4458 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4459 if (extras != null) {
4460 intent.putExtras(extras);
4461 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004462 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 am.broadcastIntent(
4464 null, intent,
4465 null, null, 0, null, null, null, false, false);
4466 } catch (RemoteException ex) {
4467 }
4468 }
4469 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004470
4471 public String nextPackageToClean(String lastPackage) {
4472 synchronized (mPackages) {
4473 if (!mMediaMounted) {
4474 // If the external storage is no longer mounted at this point,
4475 // the caller may not have been able to delete all of this
4476 // packages files and can not delete any more. Bail.
4477 return null;
4478 }
4479 if (lastPackage != null) {
4480 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4481 }
4482 return mSettings.mPackagesToBeCleaned.size() > 0
4483 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4484 }
4485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004487 void schedulePackageCleaning(String packageName) {
4488 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4489 }
4490
4491 void startCleaningPackages() {
4492 synchronized (mPackages) {
4493 if (!mMediaMounted) {
4494 return;
4495 }
4496 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4497 return;
4498 }
4499 }
4500 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4501 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4502 IActivityManager am = ActivityManagerNative.getDefault();
4503 if (am != null) {
4504 try {
4505 am.startService(null, intent, null);
4506 } catch (RemoteException e) {
4507 }
4508 }
4509 }
4510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 private final class AppDirObserver extends FileObserver {
4512 public AppDirObserver(String path, int mask, boolean isrom) {
4513 super(path, mask);
4514 mRootDir = path;
4515 mIsRom = isrom;
4516 }
4517
4518 public void onEvent(int event, String path) {
4519 String removedPackage = null;
4520 int removedUid = -1;
4521 String addedPackage = null;
4522 int addedUid = -1;
4523
4524 synchronized (mInstallLock) {
4525 String fullPathStr = null;
4526 File fullPath = null;
4527 if (path != null) {
4528 fullPath = new File(mRootDir, path);
4529 fullPathStr = fullPath.getPath();
4530 }
4531
4532 if (Config.LOGV) Log.v(
4533 TAG, "File " + fullPathStr + " changed: "
4534 + Integer.toHexString(event));
4535
4536 if (!isPackageFilename(path)) {
4537 if (Config.LOGV) Log.v(
4538 TAG, "Ignoring change of non-package file: " + fullPathStr);
4539 return;
4540 }
4541
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004542 // Ignore packages that are being installed or
4543 // have just been installed.
4544 if (ignoreCodePath(fullPathStr)) {
4545 return;
4546 }
4547 PackageParser.Package p = null;
4548 synchronized (mPackages) {
4549 p = mAppDirs.get(fullPathStr);
4550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004552 if (p != null) {
4553 removePackageLI(p, true);
4554 removedPackage = p.applicationInfo.packageName;
4555 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 }
4557 }
4558
4559 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004561 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004562 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4563 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004564 PackageParser.PARSE_CHATTY |
4565 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004566 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 if (p != null) {
4568 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004569 updatePermissionsLP(p.packageName, p,
4570 p.permissions.size() > 0, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004571 }
4572 addedPackage = p.applicationInfo.packageName;
4573 addedUid = p.applicationInfo.uid;
4574 }
4575 }
4576 }
4577
4578 synchronized (mPackages) {
4579 mSettings.writeLP();
4580 }
4581 }
4582
4583 if (removedPackage != null) {
4584 Bundle extras = new Bundle(1);
4585 extras.putInt(Intent.EXTRA_UID, removedUid);
4586 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4587 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4588 }
4589 if (addedPackage != null) {
4590 Bundle extras = new Bundle(1);
4591 extras.putInt(Intent.EXTRA_UID, addedUid);
4592 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4593 }
4594 }
4595
4596 private final String mRootDir;
4597 private final boolean mIsRom;
4598 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 /* Called when a downloaded package installation has been confirmed by the user */
4601 public void installPackage(
4602 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004603 installPackage(packageURI, observer, flags, null);
4604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004605
Jacek Surazski65e13172009-04-28 15:26:38 +02004606 /* Called when a downloaded package installation has been confirmed by the user */
4607 public void installPackage(
4608 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4609 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 mContext.enforceCallingOrSelfPermission(
4611 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004612
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004613 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004614 msg.obj = new InstallParams(packageURI, observer, flags,
4615 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004616 mHandler.sendMessage(msg);
4617 }
4618
Christopher Tate1bb69062010-02-19 17:02:12 -08004619 public void finishPackageInstall(int token) {
4620 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4621 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4622 mHandler.sendMessage(msg);
4623 }
4624
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004625 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 // Queue up an async operation since the package installation may take a little while.
4627 mHandler.post(new Runnable() {
4628 public void run() {
4629 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004630 // Result object to be returned
4631 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004632 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004633 res.uid = -1;
4634 res.pkg = null;
4635 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004636 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004637 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004638 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004639 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004640 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004641 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004642 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004643
4644 // A restore should be performed at this point if (a) the install
4645 // succeeded, (b) the operation is not an update, and (c) the new
4646 // package has a backupAgent defined.
4647 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004648 boolean doRestore = (!update
4649 && res.pkg != null
4650 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004651
4652 // Set up the post-install work request bookkeeping. This will be used
4653 // and cleaned up by the post-install event handling regardless of whether
4654 // there's a restore pass performed. Token values are >= 1.
4655 int token;
4656 if (mNextInstallToken < 0) mNextInstallToken = 1;
4657 token = mNextInstallToken++;
4658
4659 PostInstallData data = new PostInstallData(args, res);
4660 mRunningInstalls.put(token, data);
4661 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4662
4663 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4664 // Pass responsibility to the Backup Manager. It will perform a
4665 // restore if appropriate, then pass responsibility back to the
4666 // Package Manager to run the post-install observer callbacks
4667 // and broadcasts.
4668 IBackupManager bm = IBackupManager.Stub.asInterface(
4669 ServiceManager.getService(Context.BACKUP_SERVICE));
4670 if (bm != null) {
4671 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4672 + " to BM for possible restore");
4673 try {
4674 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4675 } catch (RemoteException e) {
4676 // can't happen; the backup manager is local
4677 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004678 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004679 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004680 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004681 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004682 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004683 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004686
4687 if (!doRestore) {
4688 // No restore possible, or the Backup Manager was mysteriously not
4689 // available -- just fire the post-install work request directly.
4690 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4691 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4692 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 });
4696 }
4697
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004698 abstract class HandlerParams {
4699 final static int MAX_RETRIES = 4;
4700 int retry = 0;
4701 final void startCopy() {
4702 try {
4703 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4704 retry++;
4705 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004706 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004707 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4708 handleServiceError();
4709 return;
4710 } else {
4711 handleStartCopy();
4712 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4713 mHandler.sendEmptyMessage(MCS_UNBIND);
4714 }
4715 } catch (RemoteException e) {
4716 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4717 mHandler.sendEmptyMessage(MCS_RECONNECT);
4718 }
4719 handleReturnCode();
4720 }
4721
4722 final void serviceError() {
4723 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4724 handleServiceError();
4725 handleReturnCode();
4726 }
4727 abstract void handleStartCopy() throws RemoteException;
4728 abstract void handleServiceError();
4729 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004730 }
4731
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004733 final IPackageInstallObserver observer;
4734 int flags;
4735 final Uri packageURI;
4736 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004737 private InstallArgs mArgs;
4738 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004739 InstallParams(Uri packageURI,
4740 IPackageInstallObserver observer, int flags,
4741 String installerPackageName) {
4742 this.packageURI = packageURI;
4743 this.flags = flags;
4744 this.observer = observer;
4745 this.installerPackageName = installerPackageName;
4746 }
4747
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004748 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4749 String packageName = pkgLite.packageName;
4750 int installLocation = pkgLite.installLocation;
4751 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4752 synchronized (mPackages) {
4753 PackageParser.Package pkg = mPackages.get(packageName);
4754 if (pkg != null) {
4755 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4756 // Check for updated system application.
4757 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4758 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004759 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004760 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4761 }
4762 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4763 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004764 if (onSd) {
4765 // Install flag overrides everything.
4766 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4767 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004768 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004769 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4770 // Application explicitly specified internal.
4771 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4772 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4773 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004774 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004775 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004776 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4777 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4778 }
4779 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004780 }
4781 }
4782 } else {
4783 // Invalid install. Return error code
4784 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4785 }
4786 }
4787 }
4788 // All the special cases have been taken care of.
4789 // Return result based on recommended install location.
4790 if (onSd) {
4791 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4792 }
4793 return pkgLite.recommendedInstallLocation;
4794 }
4795
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004796 /*
4797 * Invoke remote method to get package information and install
4798 * location values. Override install location based on default
4799 * policy if needed and then create install arguments based
4800 * on the install location.
4801 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004802 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004803 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004804 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4805 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004806 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4807 if (onInt && onSd) {
4808 // Check if both bits are set.
4809 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4810 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4811 } else if (fwdLocked && onSd) {
4812 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004813 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004814 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004815 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004816 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004817 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004818 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004819 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4820 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4821 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4822 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4823 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4825 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4826 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004827 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4828 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004829 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004830 // Override with defaults if needed.
4831 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004832 if (!onSd && !onInt) {
4833 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004834 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4835 // Set the flag to install on external media.
4836 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004837 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004838 } else {
4839 // Make sure the flag for installing on external
4840 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004841 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 flags &= ~PackageManager.INSTALL_EXTERNAL;
4843 }
4844 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 }
4846 }
4847 // Create the file args now.
4848 mArgs = createInstallArgs(this);
4849 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4850 // Create copy only if we are not in an erroneous state.
4851 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004852 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004853 }
4854 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004855 }
4856
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004857 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 void handleReturnCode() {
4859 processPendingInstall(mArgs, mRet);
4860 }
4861
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004862 @Override
4863 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004864 mArgs = createInstallArgs(this);
4865 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004866 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004867 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004868
4869 /*
4870 * Utility class used in movePackage api.
4871 * srcArgs and targetArgs are not set for invalid flags and make
4872 * sure to do null checks when invoking methods on them.
4873 * We probably want to return ErrorPrams for both failed installs
4874 * and moves.
4875 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004876 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 final IPackageMoveObserver observer;
4878 final int flags;
4879 final String packageName;
4880 final InstallArgs srcArgs;
4881 final InstallArgs targetArgs;
4882 int mRet;
4883 MoveParams(InstallArgs srcArgs,
4884 IPackageMoveObserver observer,
4885 int flags, String packageName) {
4886 this.srcArgs = srcArgs;
4887 this.observer = observer;
4888 this.flags = flags;
4889 this.packageName = packageName;
4890 if (srcArgs != null) {
4891 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4892 targetArgs = createInstallArgs(packageUri, flags, packageName);
4893 } else {
4894 targetArgs = null;
4895 }
4896 }
4897
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004898 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004899 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4900 // Check for storage space on target medium
4901 if (!targetArgs.checkFreeStorage(mContainerService)) {
4902 Log.w(TAG, "Insufficient storage to install");
4903 return;
4904 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004905 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004906 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004907 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004908 if (DEBUG_SD_INSTALL) {
4909 StringBuilder builder = new StringBuilder();
4910 if (srcArgs != null) {
4911 builder.append("src: ");
4912 builder.append(srcArgs.getCodePath());
4913 }
4914 if (targetArgs != null) {
4915 builder.append(" target : ");
4916 builder.append(targetArgs.getCodePath());
4917 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004918 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004919 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004920 }
4921
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004922 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004923 void handleReturnCode() {
4924 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004925 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4926 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4927 currentStatus = PackageManager.MOVE_SUCCEEDED;
4928 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4929 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4930 }
4931 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004932 }
4933
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004934 @Override
4935 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004936 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004937 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004938 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004939
4940 private InstallArgs createInstallArgs(InstallParams params) {
4941 if (installOnSd(params.flags)) {
4942 return new SdInstallArgs(params);
4943 } else {
4944 return new FileInstallArgs(params);
4945 }
4946 }
4947
4948 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4949 if (installOnSd(flags)) {
4950 return new SdInstallArgs(fullCodePath, fullResourcePath);
4951 } else {
4952 return new FileInstallArgs(fullCodePath, fullResourcePath);
4953 }
4954 }
4955
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004956 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4957 if (installOnSd(flags)) {
4958 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4959 return new SdInstallArgs(packageURI, cid);
4960 } else {
4961 return new FileInstallArgs(packageURI, pkgName);
4962 }
4963 }
4964
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004965 static abstract class InstallArgs {
4966 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004967 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968 final int flags;
4969 final Uri packageURI;
4970 final String installerPackageName;
4971
4972 InstallArgs(Uri packageURI,
4973 IPackageInstallObserver observer, int flags,
4974 String installerPackageName) {
4975 this.packageURI = packageURI;
4976 this.flags = flags;
4977 this.observer = observer;
4978 this.installerPackageName = installerPackageName;
4979 }
4980
4981 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004982 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004983 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004985 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004986 abstract String getCodePath();
4987 abstract String getResourcePath();
4988 // Need installer lock especially for dex file removal.
4989 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004990 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004991 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004992 }
4993
4994 class FileInstallArgs extends InstallArgs {
4995 File installDir;
4996 String codeFileName;
4997 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004998 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005000 FileInstallArgs(InstallParams params) {
5001 super(params.packageURI, params.observer,
5002 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005003 }
5004
5005 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5006 super(null, null, 0, null);
5007 File codeFile = new File(fullCodePath);
5008 installDir = codeFile.getParentFile();
5009 codeFileName = fullCodePath;
5010 resourceFileName = fullResourcePath;
5011 }
5012
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005013 FileInstallArgs(Uri packageURI, String pkgName) {
5014 super(packageURI, null, 0, null);
5015 boolean fwdLocked = isFwdLocked(flags);
5016 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5017 String apkName = getNextCodePath(null, pkgName, ".apk");
5018 codeFileName = new File(installDir, apkName + ".apk").getPath();
5019 resourceFileName = getResourcePathFromCodePath();
5020 }
5021
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005022 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5023 return imcs.checkFreeStorage(false, packageURI);
5024 }
5025
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005026 String getCodePath() {
5027 return codeFileName;
5028 }
5029
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 void createCopyFile() {
5031 boolean fwdLocked = isFwdLocked(flags);
5032 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5033 codeFileName = createTempPackageFile(installDir).getPath();
5034 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005035 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005036 }
5037
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005038 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005039 if (temp) {
5040 // Generate temp file name
5041 createCopyFile();
5042 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 // Get a ParcelFileDescriptor to write to the output file
5044 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005045 if (!created) {
5046 try {
5047 codeFile.createNewFile();
5048 // Set permissions
5049 if (!setPermissions()) {
5050 // Failed setting permissions.
5051 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5052 }
5053 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005054 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005055 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5056 }
5057 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005058 ParcelFileDescriptor out = null;
5059 try {
5060 out = ParcelFileDescriptor.open(codeFile,
5061 ParcelFileDescriptor.MODE_READ_WRITE);
5062 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005063 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005064 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5065 }
5066 // Copy the resource now
5067 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5068 try {
5069 if (imcs.copyResource(packageURI, out)) {
5070 ret = PackageManager.INSTALL_SUCCEEDED;
5071 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005072 } finally {
5073 try { if (out != null) out.close(); } catch (IOException e) {}
5074 }
5075 return ret;
5076 }
5077
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005078 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 if (status != PackageManager.INSTALL_SUCCEEDED) {
5080 cleanUp();
5081 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005082 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 }
5084
5085 boolean doRename(int status, final String pkgName, String oldCodePath) {
5086 if (status != PackageManager.INSTALL_SUCCEEDED) {
5087 cleanUp();
5088 return false;
5089 } else {
5090 // Rename based on packageName
5091 File codeFile = new File(getCodePath());
5092 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5093 File desFile = new File(installDir, apkName + ".apk");
5094 if (!codeFile.renameTo(desFile)) {
5095 return false;
5096 }
5097 // Reset paths since the file has been renamed.
5098 codeFileName = desFile.getPath();
5099 resourceFileName = getResourcePathFromCodePath();
5100 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005101 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 // Failed setting permissions.
5103 return false;
5104 }
5105 return true;
5106 }
5107 }
5108
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005109 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005110 if (status != PackageManager.INSTALL_SUCCEEDED) {
5111 cleanUp();
5112 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005113 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 }
5115
5116 String getResourcePath() {
5117 return resourceFileName;
5118 }
5119
5120 String getResourcePathFromCodePath() {
5121 String codePath = getCodePath();
5122 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5123 String apkNameOnly = getApkName(codePath);
5124 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5125 } else {
5126 return codePath;
5127 }
5128 }
5129
5130 private boolean cleanUp() {
5131 boolean ret = true;
5132 String sourceDir = getCodePath();
5133 String publicSourceDir = getResourcePath();
5134 if (sourceDir != null) {
5135 File sourceFile = new File(sourceDir);
5136 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005137 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005138 ret = false;
5139 }
5140 // Delete application's code and resources
5141 sourceFile.delete();
5142 }
5143 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5144 final File publicSourceFile = new File(publicSourceDir);
5145 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005146 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 }
5148 if (publicSourceFile.exists()) {
5149 publicSourceFile.delete();
5150 }
5151 }
5152 return ret;
5153 }
5154
5155 void cleanUpResourcesLI() {
5156 String sourceDir = getCodePath();
5157 if (cleanUp() && mInstaller != null) {
5158 int retCode = mInstaller.rmdex(sourceDir);
5159 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005160 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005161 + " at location "
5162 + sourceDir + ", retcode=" + retCode);
5163 // we don't consider this to be a failure of the core package deletion
5164 }
5165 }
5166 }
5167
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005168 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 // TODO Do this in a more elegant way later on. for now just a hack
5170 if (!isFwdLocked(flags)) {
5171 final int filePermissions =
5172 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5173 |FileUtils.S_IROTH;
5174 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5175 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005176 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005177 getCodePath()
5178 + ". The return code was: " + retCode);
5179 // TODO Define new internal error
5180 return false;
5181 }
5182 return true;
5183 }
5184 return true;
5185 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005186
5187 boolean doPostDeleteLI(boolean delete) {
5188 cleanUpResourcesLI();
5189 return true;
5190 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005191 }
5192
5193 class SdInstallArgs extends InstallArgs {
5194 String cid;
5195 String cachePath;
5196 static final String RES_FILE_NAME = "pkg.apk";
5197
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005198 SdInstallArgs(InstallParams params) {
5199 super(params.packageURI, params.observer,
5200 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 }
5202
5203 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005204 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 // Extract cid from fullCodePath
5206 int eidx = fullCodePath.lastIndexOf("/");
5207 String subStr1 = fullCodePath.substring(0, eidx);
5208 int sidx = subStr1.lastIndexOf("/");
5209 cid = subStr1.substring(sidx+1, eidx);
5210 cachePath = subStr1;
5211 }
5212
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005213 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005214 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5215 this.cid = cid;
5216 }
5217
5218 SdInstallArgs(Uri packageURI, String cid) {
5219 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005220 this.cid = cid;
5221 }
5222
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005223 void createCopyFile() {
5224 cid = getTempContainerId();
5225 }
5226
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005227 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5228 return imcs.checkFreeStorage(true, packageURI);
5229 }
5230
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005231 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005232 if (temp) {
5233 createCopyFile();
5234 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005235 cachePath = imcs.copyResourceToContainer(
5236 packageURI, cid,
5237 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005238 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5239 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 }
5241
5242 @Override
5243 String getCodePath() {
5244 return cachePath + "/" + RES_FILE_NAME;
5245 }
5246
5247 @Override
5248 String getResourcePath() {
5249 return cachePath + "/" + RES_FILE_NAME;
5250 }
5251
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005252 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005253 if (status != PackageManager.INSTALL_SUCCEEDED) {
5254 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005255 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005256 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005257 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005258 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005259 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005260 if (cachePath == null) {
5261 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5262 }
5263 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005264 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005265 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005266 }
5267
5268 boolean doRename(int status, final String pkgName,
5269 String oldCodePath) {
5270 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005271 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005272 if (PackageHelper.isContainerMounted(cid)) {
5273 // Unmount the container
5274 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005275 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005276 return false;
5277 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005278 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005279 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005280 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5281 " which might be stale. Will try to clean up.");
5282 // Clean up the stale container and proceed to recreate.
5283 if (!PackageHelper.destroySdDir(newCacheId)) {
5284 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5285 return false;
5286 }
5287 // Successfully cleaned up stale container. Try to rename again.
5288 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5289 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5290 + " inspite of cleaning it up.");
5291 return false;
5292 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005293 }
5294 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005295 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005296 newCachePath = PackageHelper.mountSdDir(newCacheId,
5297 getEncryptKey(), Process.SYSTEM_UID);
5298 } else {
5299 newCachePath = PackageHelper.getSdDir(newCacheId);
5300 }
5301 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005302 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005303 return false;
5304 }
5305 Log.i(TAG, "Succesfully renamed " + cid +
5306 " at path: " + cachePath + " to " + newCacheId +
5307 " at new path: " + newCachePath);
5308 cid = newCacheId;
5309 cachePath = newCachePath;
5310 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
5312
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005313 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005314 if (status != PackageManager.INSTALL_SUCCEEDED) {
5315 cleanUp();
5316 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005317 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005318 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005319 PackageHelper.mountSdDir(cid,
5320 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005321 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005323 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005324 }
5325
5326 private void cleanUp() {
5327 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005328 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005329 }
5330
5331 void cleanUpResourcesLI() {
5332 String sourceFile = getCodePath();
5333 // Remove dex file
5334 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005335 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005336 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005337 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 + " at location "
5339 + sourceFile.toString() + ", retcode=" + retCode);
5340 // we don't consider this to be a failure of the core package deletion
5341 }
5342 }
5343 cleanUp();
5344 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005345
5346 boolean matchContainer(String app) {
5347 if (cid.startsWith(app)) {
5348 return true;
5349 }
5350 return false;
5351 }
5352
5353 String getPackageName() {
5354 int idx = cid.lastIndexOf("-");
5355 if (idx == -1) {
5356 return cid;
5357 }
5358 return cid.substring(0, idx);
5359 }
5360
5361 boolean doPostDeleteLI(boolean delete) {
5362 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005363 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005364 if (mounted) {
5365 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005366 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005367 }
5368 if (ret && delete) {
5369 cleanUpResourcesLI();
5370 }
5371 return ret;
5372 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005373 };
5374
5375 // Utility method used to create code paths based on package name and available index.
5376 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5377 String idxStr = "";
5378 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005379 // Fall back to default value of idx=1 if prefix is not
5380 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005381 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005382 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005383 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005384 if (subStr.endsWith(suffix)) {
5385 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005387 // If oldCodePath already contains prefix find out the
5388 // ending index to either increment or decrement.
5389 int sidx = subStr.lastIndexOf(prefix);
5390 if (sidx != -1) {
5391 subStr = subStr.substring(sidx + prefix.length());
5392 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005393 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5394 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005395 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005396 try {
5397 idx = Integer.parseInt(subStr);
5398 if (idx <= 1) {
5399 idx++;
5400 } else {
5401 idx--;
5402 }
5403 } catch(NumberFormatException e) {
5404 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 }
5406 }
5407 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005408 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005409 return prefix + idxStr;
5410 }
5411
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005412 // Utility method used to ignore ADD/REMOVE events
5413 // by directory observer.
5414 private static boolean ignoreCodePath(String fullPathStr) {
5415 String apkName = getApkName(fullPathStr);
5416 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5417 if (idx != -1 && ((idx+1) < apkName.length())) {
5418 // Make sure the package ends with a numeral
5419 String version = apkName.substring(idx+1);
5420 try {
5421 Integer.parseInt(version);
5422 return true;
5423 } catch (NumberFormatException e) {}
5424 }
5425 return false;
5426 }
5427
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005428 // Utility method that returns the relative package path with respect
5429 // to the installation directory. Like say for /data/data/com.test-1.apk
5430 // string com.test-1 is returned.
5431 static String getApkName(String codePath) {
5432 if (codePath == null) {
5433 return null;
5434 }
5435 int sidx = codePath.lastIndexOf("/");
5436 int eidx = codePath.lastIndexOf(".");
5437 if (eidx == -1) {
5438 eidx = codePath.length();
5439 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005440 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005441 return null;
5442 }
5443 return codePath.substring(sidx+1, eidx);
5444 }
5445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 class PackageInstalledInfo {
5447 String name;
5448 int uid;
5449 PackageParser.Package pkg;
5450 int returnCode;
5451 PackageRemovedInfo removedInfo;
5452 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 /*
5455 * Install a non-existing package.
5456 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005457 private void installNewPackageLI(PackageParser.Package pkg,
5458 int parseFlags,
5459 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005460 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005462 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005463
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005464 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 res.name = pkgName;
5466 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005467 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005469 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 + " without first uninstalling.");
5471 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5472 return;
5473 }
5474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005478 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5480 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5481 }
5482 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005483 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005484 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 res);
5486 // delete the partially installed application. the data directory will have to be
5487 // restored if it was already existing
5488 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5489 // remove package from internal structures. Note that we want deletePackageX to
5490 // delete the package data and cache directories that it created in
5491 // scanPackageLocked, unless those directories existed before we even tried to
5492 // install.
5493 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005494 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5496 res.removedInfo);
5497 }
5498 }
5499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005500
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005501 private void replacePackageLI(PackageParser.Package pkg,
5502 int parseFlags,
5503 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005504 String installerPackageName, PackageInstalledInfo res) {
5505
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005506 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 // First find the old package info and check signatures
5509 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005510 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005511 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005512 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5514 return;
5515 }
5516 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005517 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005518 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005519 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005521 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 }
5523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 private void replaceNonSystemPackageLI(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 String pkgName = deletedPackage.packageName;
5531 boolean deletedPkg = true;
5532 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005533
Jacek Surazski65e13172009-04-28 15:26:38 +02005534 String oldInstallerPackageName = null;
5535 synchronized (mPackages) {
5536 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005538
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005539 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005541 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 res.removedInfo)) {
5543 // If the existing package was'nt successfully deleted
5544 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5545 deletedPkg = false;
5546 } else {
5547 // Successfully deleted the old package. Now proceed with re-installation
5548 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005549 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005551 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5553 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005554 }
5555 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005556 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005557 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 res);
5559 updatedSettings = true;
5560 }
5561 }
5562
5563 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5564 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005565 // were keeping around in case we needed them (see below) can now be deleted.
5566 // This info will be set on the res.removedInfo to clean up later on as post
5567 // install action.
5568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 //update signature on the new package setting
5570 //this should always succeed, since we checked the
5571 //signature earlier.
5572 synchronized(mPackages) {
5573 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5574 parseFlags, true);
5575 }
5576 } else {
5577 // remove package from internal structures. Note that we want deletePackageX to
5578 // delete the package data and cache directories that it created in
5579 // scanPackageLocked, unless those directories existed before we even tried to
5580 // install.
5581 if(updatedSettings) {
5582 deletePackageLI(
5583 pkgName, true,
5584 PackageManager.DONT_DELETE_DATA,
5585 res.removedInfo);
5586 }
5587 // Since we failed to install the new package we need to restore the old
5588 // package that we deleted.
5589 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005590 File restoreFile = new File(deletedPackage.mPath);
5591 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005592 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005593 return;
5594 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005595 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5596 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005597 // Parse old package
5598 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5599 scanPackageLI(restoreFile, parseFlags, scanMode);
5600 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005601 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
5602 true, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005603 mSettings.writeLP();
5604 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005605 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005606 Slog.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 }
5609 }
5610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005613 PackageParser.Package pkg,
5614 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005615 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 PackageParser.Package newPackage = null;
5617 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 PackageParser.PARSE_IS_SYSTEM;
5620 String packageName = deletedPackage.packageName;
5621 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5622 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005623 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 return;
5625 }
5626 PackageParser.Package oldPkg;
5627 PackageSetting oldPkgSetting;
5628 synchronized (mPackages) {
5629 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005630 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5632 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005633 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 return;
5635 }
5636 }
5637 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5638 res.removedInfo.removedPackage = packageName;
5639 // Remove existing system package
5640 removePackageLI(oldPkg, true);
5641 synchronized (mPackages) {
5642 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5643 }
5644
5645 // Successfully disabled the old package. Now proceed with re-installation
5646 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5647 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005648 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005650 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5652 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5653 }
5654 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005655 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 updatedSettings = true;
5657 }
5658
5659 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5660 //update signature on the new package setting
5661 //this should always succeed, since we checked the
5662 //signature earlier.
5663 synchronized(mPackages) {
5664 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5665 parseFlags, true);
5666 }
5667 } else {
5668 // Re installation failed. Restore old information
5669 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005670 if (newPackage != null) {
5671 removePackageLI(newPackage, true);
5672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005674 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005676 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 // Restore the old system information in Settings
5678 synchronized(mPackages) {
5679 if(updatedSettings) {
5680 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005681 mSettings.setInstallerPackageName(packageName,
5682 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 }
5684 mSettings.writeLP();
5685 }
5686 }
5687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005688
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005689 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005690 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005691 int retCode;
5692 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5693 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5694 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005695 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005696 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5697 }
5698 }
5699 return PackageManager.INSTALL_SUCCEEDED;
5700 }
5701
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005702 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005703 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005704 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 synchronized (mPackages) {
5706 //write settings. the installStatus will be incomplete at this stage.
5707 //note that the new package setting would have already been
5708 //added to mPackages. It hasn't been persisted yet.
5709 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5710 mSettings.writeLP();
5711 }
5712
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005713 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005714 != PackageManager.INSTALL_SUCCEEDED) {
5715 // Discontinue if moving dex files failed.
5716 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005718 if((res.returnCode = setPermissionsLI(newPackage))
5719 != PackageManager.INSTALL_SUCCEEDED) {
5720 if (mInstaller != null) {
5721 mInstaller.rmdex(newPackage.mScanPath);
5722 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005723 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005725 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005728 updatePermissionsLP(newPackage.packageName, newPackage,
5729 newPackage.permissions.size() > 0, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 res.name = pkgName;
5731 res.uid = newPackage.applicationInfo.uid;
5732 res.pkg = newPackage;
5733 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005734 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5736 //to update install status
5737 mSettings.writeLP();
5738 }
5739 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005740
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005741 private void installPackageLI(InstallArgs args,
5742 boolean newInstall, PackageInstalledInfo res) {
5743 int pFlags = args.flags;
5744 String installerPackageName = args.installerPackageName;
5745 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005746 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005747 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005748 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005749 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5750 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005751 // Result object to be returned
5752 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5753
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005754 // Retrieve PackageSettings and parse package
5755 int parseFlags = PackageParser.PARSE_CHATTY |
5756 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5757 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5758 parseFlags |= mDefParseFlags;
5759 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5760 pp.setSeparateProcesses(mSeparateProcesses);
5761 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5762 null, mMetrics, parseFlags);
5763 if (pkg == null) {
5764 res.returnCode = pp.getParseError();
5765 return;
5766 }
5767 String pkgName = res.name = pkg.packageName;
5768 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5769 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5770 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5771 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005773 }
5774 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5775 res.returnCode = pp.getParseError();
5776 return;
5777 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005778 // Get rid of all references to package scan path via parser.
5779 pp = null;
5780 String oldCodePath = null;
5781 boolean systemApp = false;
5782 synchronized (mPackages) {
5783 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005784 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5785 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005786 if (pkg.mOriginalPackages != null
5787 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005788 && mPackages.containsKey(oldName)) {
5789 // This package is derived from an original package,
5790 // and this device has been updating from that original
5791 // name. We must continue using the original name, so
5792 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005793 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005794 pkgName = pkg.packageName;
5795 replace = true;
5796 } else if (mPackages.containsKey(pkgName)) {
5797 // This package, under its official name, already exists
5798 // on the device; we should replace it.
5799 replace = true;
5800 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005801 }
5802 PackageSetting ps = mSettings.mPackages.get(pkgName);
5803 if (ps != null) {
5804 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5805 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5806 systemApp = (ps.pkg.applicationInfo.flags &
5807 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005808 }
5809 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005811
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005812 if (systemApp && onSd) {
5813 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005814 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005815 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5816 return;
5817 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005818
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005819 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5820 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5821 return;
5822 }
5823 // Set application objects path explicitly after the rename
5824 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005825 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005826 replacePackageLI(pkg, parseFlags, scanMode,
5827 installerPackageName, res);
5828 } else {
5829 installNewPackageLI(pkg, parseFlags, scanMode,
5830 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
5832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005833
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005834 private int setPermissionsLI(PackageParser.Package newPackage) {
5835 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005836 int retCode = 0;
5837 // TODO Gross hack but fix later. Ideally move this to be a post installation
5838 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005839 if ((newPackage.applicationInfo.flags
5840 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5841 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 try {
5843 extractPublicFiles(newPackage, destResourceFile);
5844 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005845 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 -08005846 " forward-locked app.");
5847 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5848 } finally {
5849 //TODO clean up the extracted public files
5850 }
5851 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005852 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 newPackage.applicationInfo.uid);
5854 } else {
5855 final int filePermissions =
5856 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005857 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005858 newPackage.applicationInfo.uid);
5859 }
5860 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861 // The permissions on the resource file was set when it was copied for
5862 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005866 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005867 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005869 // TODO Define new internal error
5870 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 }
5872 return PackageManager.INSTALL_SUCCEEDED;
5873 }
5874
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005875 private boolean isForwardLocked(PackageParser.Package pkg) {
5876 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
5878
5879 private void extractPublicFiles(PackageParser.Package newPackage,
5880 File publicZipFile) throws IOException {
5881 final ZipOutputStream publicZipOutStream =
5882 new ZipOutputStream(new FileOutputStream(publicZipFile));
5883 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5884
5885 // Copy manifest, resources.arsc and res directory to public zip
5886
5887 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5888 while (privateZipEntries.hasMoreElements()) {
5889 final ZipEntry zipEntry = privateZipEntries.nextElement();
5890 final String zipEntryName = zipEntry.getName();
5891 if ("AndroidManifest.xml".equals(zipEntryName)
5892 || "resources.arsc".equals(zipEntryName)
5893 || zipEntryName.startsWith("res/")) {
5894 try {
5895 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5896 } catch (IOException e) {
5897 try {
5898 publicZipOutStream.close();
5899 throw e;
5900 } finally {
5901 publicZipFile.delete();
5902 }
5903 }
5904 }
5905 }
5906
5907 publicZipOutStream.close();
5908 FileUtils.setPermissions(
5909 publicZipFile.getAbsolutePath(),
5910 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5911 -1, -1);
5912 }
5913
5914 private static void copyZipEntry(ZipEntry zipEntry,
5915 ZipFile inZipFile,
5916 ZipOutputStream outZipStream) throws IOException {
5917 byte[] buffer = new byte[4096];
5918 int num;
5919
5920 ZipEntry newEntry;
5921 if (zipEntry.getMethod() == ZipEntry.STORED) {
5922 // Preserve the STORED method of the input entry.
5923 newEntry = new ZipEntry(zipEntry);
5924 } else {
5925 // Create a new entry so that the compressed len is recomputed.
5926 newEntry = new ZipEntry(zipEntry.getName());
5927 }
5928 outZipStream.putNextEntry(newEntry);
5929
5930 InputStream data = inZipFile.getInputStream(zipEntry);
5931 while ((num = data.read(buffer)) > 0) {
5932 outZipStream.write(buffer, 0, num);
5933 }
5934 outZipStream.flush();
5935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 private void deleteTempPackageFiles() {
5938 FilenameFilter filter = new FilenameFilter() {
5939 public boolean accept(File dir, String name) {
5940 return name.startsWith("vmdl") && name.endsWith(".tmp");
5941 }
5942 };
5943 String tmpFilesList[] = mAppInstallDir.list(filter);
5944 if(tmpFilesList == null) {
5945 return;
5946 }
5947 for(int i = 0; i < tmpFilesList.length; i++) {
5948 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5949 tmpFile.delete();
5950 }
5951 }
5952
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005953 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 File tmpPackageFile;
5955 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005956 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005958 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 return null;
5960 }
5961 try {
5962 FileUtils.setPermissions(
5963 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5964 -1, -1);
5965 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005966 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 return null;
5968 }
5969 return tmpPackageFile;
5970 }
5971
5972 public void deletePackage(final String packageName,
5973 final IPackageDeleteObserver observer,
5974 final int flags) {
5975 mContext.enforceCallingOrSelfPermission(
5976 android.Manifest.permission.DELETE_PACKAGES, null);
5977 // Queue up an async operation since the package deletion may take a little while.
5978 mHandler.post(new Runnable() {
5979 public void run() {
5980 mHandler.removeCallbacks(this);
5981 final boolean succeded = deletePackageX(packageName, true, true, flags);
5982 if (observer != null) {
5983 try {
5984 observer.packageDeleted(succeded);
5985 } catch (RemoteException e) {
5986 Log.i(TAG, "Observer no longer exists.");
5987 } //end catch
5988 } //end if
5989 } //end run
5990 });
5991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 /**
5994 * This method is an internal method that could be get invoked either
5995 * to delete an installed package or to clean up a failed installation.
5996 * After deleting an installed package, a broadcast is sent to notify any
5997 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005998 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 * installation wouldn't have sent the initial broadcast either
6000 * The key steps in deleting a package are
6001 * deleting the package information in internal structures like mPackages,
6002 * deleting the packages base directories through installd
6003 * updating mSettings to reflect current status
6004 * persisting settings for later use
6005 * sending a broadcast if necessary
6006 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6008 boolean deleteCodeAndResources, int flags) {
6009 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006010 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006012 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6013 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6014 try {
6015 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006016 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006017 return false;
6018 }
6019 } catch (RemoteException e) {
6020 }
6021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 synchronized (mInstallLock) {
6023 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
6024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006027 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
6028 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
6029
6030 // If the removed package was a system update, the old system packaged
6031 // was re-enabled; we need to broadcast this information
6032 if (systemUpdate) {
6033 Bundle extras = new Bundle(1);
6034 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6035 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6036
6037 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
6038 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
6039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08006041 // Force a gc here.
6042 Runtime.getRuntime().gc();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006043 // Delete the resources here after sending the broadcast to let
6044 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08006045 if (info.args != null) {
6046 synchronized (mInstallLock) {
6047 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006048 }
6049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 return res;
6051 }
6052
6053 static class PackageRemovedInfo {
6054 String removedPackage;
6055 int uid = -1;
6056 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006057 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006058 // Clean up resources deleted packages.
6059 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 void sendBroadcast(boolean fullRemove, boolean replacing) {
6062 Bundle extras = new Bundle(1);
6063 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6064 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6065 if (replacing) {
6066 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6067 }
6068 if (removedPackage != null) {
6069 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
6070 }
6071 if (removedUid >= 0) {
6072 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
6073 }
6074 }
6075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 /*
6078 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6079 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006080 * 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 -08006081 * delete a partially installed application.
6082 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006083 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 int flags) {
6085 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006086 if (outInfo != null) {
6087 outInfo.removedPackage = packageName;
6088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 removePackageLI(p, true);
6090 // Retrieve object to delete permissions for shared user later on
6091 PackageSetting deletedPs;
6092 synchronized (mPackages) {
6093 deletedPs = mSettings.mPackages.get(packageName);
6094 }
6095 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6096 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006097 int retCode = mInstaller.remove(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006099 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 + packageName + ", retcode=" + retCode);
6101 // we don't consider this to be a failure of the core package deletion
6102 }
6103 } else {
6104 //for emulator
6105 PackageParser.Package pkg = mPackages.get(packageName);
6106 File dataDir = new File(pkg.applicationInfo.dataDir);
6107 dataDir.delete();
6108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 }
6110 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006111 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006112 schedulePackageCleaning(packageName);
6113
6114 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6115 if (outInfo != null) {
6116 outInfo.removedUid = mSettings.removePackageLP(packageName);
6117 }
6118 if (deletedPs != null) {
6119 updatePermissionsLP(deletedPs.name, null, false, false);
6120 if (deletedPs.sharedUser != null) {
6121 // remove permissions associated with package
6122 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6123 }
6124 }
6125 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006126 // remove from preferred activities.
6127 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6128 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6129 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6130 removed.add(pa);
6131 }
6132 }
6133 for (PreferredActivity pa : removed) {
6134 mSettings.mPreferredActivities.removeFilter(pa);
6135 }
6136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006138 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 }
6140 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 /*
6143 * Tries to delete system package.
6144 */
6145 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006146 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 ApplicationInfo applicationInfo = p.applicationInfo;
6148 //applicable for non-partially installed applications only
6149 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006150 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 return false;
6152 }
6153 PackageSetting ps = null;
6154 // Confirm if the system package has been updated
6155 // An updated system app can be deleted. This will also have to restore
6156 // the system pkg from system partition
6157 synchronized (mPackages) {
6158 ps = mSettings.getDisabledSystemPkg(p.packageName);
6159 }
6160 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006161 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 return false;
6163 } else {
6164 Log.i(TAG, "Deleting system pkg from data partition");
6165 }
6166 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006167 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006168 boolean deleteCodeAndResources = false;
6169 if (ps.versionCode < p.mVersionCode) {
6170 // Delete code and resources for downgrades
6171 deleteCodeAndResources = true;
6172 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6173 flags &= ~PackageManager.DONT_DELETE_DATA;
6174 }
6175 } else {
6176 // Preserve data by setting flag
6177 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6178 flags |= PackageManager.DONT_DELETE_DATA;
6179 }
6180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6182 if (!ret) {
6183 return false;
6184 }
6185 synchronized (mPackages) {
6186 // Reinstate the old system package
6187 mSettings.enableSystemPackageLP(p.packageName);
6188 }
6189 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006190 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006192 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006195 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 return false;
6197 }
6198 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006199 updatePermissionsLP(newPkg.packageName, newPkg, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 mSettings.writeLP();
6201 }
6202 return true;
6203 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6206 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6207 ApplicationInfo applicationInfo = p.applicationInfo;
6208 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006209 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 return false;
6211 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006212 if (outInfo != null) {
6213 outInfo.uid = applicationInfo.uid;
6214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215
6216 // Delete package data from internal structures and also remove data if flag is set
6217 removePackageDataLI(p, outInfo, flags);
6218
6219 // Delete application code and resources
6220 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006221 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006222 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006223 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006224 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6225 PackageManager.INSTALL_FORWARD_LOCK : 0;
6226 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006227 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 }
6229 return true;
6230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 /*
6233 * This method handles package deletion in general
6234 */
6235 private boolean deletePackageLI(String packageName,
6236 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6237 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006238 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 return false;
6240 }
6241 PackageParser.Package p;
6242 boolean dataOnly = false;
6243 synchronized (mPackages) {
6244 p = mPackages.get(packageName);
6245 if (p == null) {
6246 //this retrieves partially installed apps
6247 dataOnly = true;
6248 PackageSetting ps = mSettings.mPackages.get(packageName);
6249 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006250 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 return false;
6252 }
6253 p = ps.pkg;
6254 }
6255 }
6256 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006257 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 return false;
6259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 if (dataOnly) {
6262 // Delete application data first
6263 removePackageDataLI(p, outInfo, flags);
6264 return true;
6265 }
6266 // At this point the package should have ApplicationInfo associated with it
6267 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006268 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 return false;
6270 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006271 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6273 Log.i(TAG, "Removing system package:"+p.packageName);
6274 // When an updated system application is deleted we delete the existing resources as well and
6275 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006276 ret = deleteSystemPackageLI(p, flags, outInfo);
6277 } else {
6278 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006279 // Kill application pre-emptively especially for apps on sd.
6280 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006281 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006283 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 public void clearApplicationUserData(final String packageName,
6287 final IPackageDataObserver observer) {
6288 mContext.enforceCallingOrSelfPermission(
6289 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6290 // Queue up an async operation since the package deletion may take a little while.
6291 mHandler.post(new Runnable() {
6292 public void run() {
6293 mHandler.removeCallbacks(this);
6294 final boolean succeeded;
6295 synchronized (mInstallLock) {
6296 succeeded = clearApplicationUserDataLI(packageName);
6297 }
6298 if (succeeded) {
6299 // invoke DeviceStorageMonitor's update method to clear any notifications
6300 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6301 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6302 if (dsm != null) {
6303 dsm.updateMemory();
6304 }
6305 }
6306 if(observer != null) {
6307 try {
6308 observer.onRemoveCompleted(packageName, succeeded);
6309 } catch (RemoteException e) {
6310 Log.i(TAG, "Observer no longer exists.");
6311 }
6312 } //end if observer
6313 } //end run
6314 });
6315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 private boolean clearApplicationUserDataLI(String packageName) {
6318 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006319 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 return false;
6321 }
6322 PackageParser.Package p;
6323 boolean dataOnly = false;
6324 synchronized (mPackages) {
6325 p = mPackages.get(packageName);
6326 if(p == null) {
6327 dataOnly = true;
6328 PackageSetting ps = mSettings.mPackages.get(packageName);
6329 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006330 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return false;
6332 }
6333 p = ps.pkg;
6334 }
6335 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 if(!dataOnly) {
6338 //need to check this only for fully installed applications
6339 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006340 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 return false;
6342 }
6343 final ApplicationInfo applicationInfo = p.applicationInfo;
6344 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006345 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 return false;
6347 }
6348 }
6349 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006350 int retCode = mInstaller.clearUserData(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006352 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 + packageName);
6354 return false;
6355 }
6356 }
6357 return true;
6358 }
6359
6360 public void deleteApplicationCacheFiles(final String packageName,
6361 final IPackageDataObserver observer) {
6362 mContext.enforceCallingOrSelfPermission(
6363 android.Manifest.permission.DELETE_CACHE_FILES, null);
6364 // Queue up an async operation since the package deletion may take a little while.
6365 mHandler.post(new Runnable() {
6366 public void run() {
6367 mHandler.removeCallbacks(this);
6368 final boolean succeded;
6369 synchronized (mInstallLock) {
6370 succeded = deleteApplicationCacheFilesLI(packageName);
6371 }
6372 if(observer != null) {
6373 try {
6374 observer.onRemoveCompleted(packageName, succeded);
6375 } catch (RemoteException e) {
6376 Log.i(TAG, "Observer no longer exists.");
6377 }
6378 } //end if observer
6379 } //end run
6380 });
6381 }
6382
6383 private boolean deleteApplicationCacheFilesLI(String packageName) {
6384 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006385 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 return false;
6387 }
6388 PackageParser.Package p;
6389 synchronized (mPackages) {
6390 p = mPackages.get(packageName);
6391 }
6392 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 return false;
6395 }
6396 final ApplicationInfo applicationInfo = p.applicationInfo;
6397 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006398 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 return false;
6400 }
6401 if (mInstaller != null) {
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006402 int retCode = mInstaller.deleteCacheFiles(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006404 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 + packageName);
6406 return false;
6407 }
6408 }
6409 return true;
6410 }
6411
6412 public void getPackageSizeInfo(final String packageName,
6413 final IPackageStatsObserver observer) {
6414 mContext.enforceCallingOrSelfPermission(
6415 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6416 // Queue up an async operation since the package deletion may take a little while.
6417 mHandler.post(new Runnable() {
6418 public void run() {
6419 mHandler.removeCallbacks(this);
6420 PackageStats lStats = new PackageStats(packageName);
6421 final boolean succeded;
6422 synchronized (mInstallLock) {
6423 succeded = getPackageSizeInfoLI(packageName, lStats);
6424 }
6425 if(observer != null) {
6426 try {
6427 observer.onGetStatsCompleted(lStats, succeded);
6428 } catch (RemoteException e) {
6429 Log.i(TAG, "Observer no longer exists.");
6430 }
6431 } //end if observer
6432 } //end run
6433 });
6434 }
6435
6436 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6437 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006438 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 return false;
6440 }
6441 PackageParser.Package p;
6442 boolean dataOnly = false;
6443 synchronized (mPackages) {
6444 p = mPackages.get(packageName);
6445 if(p == null) {
6446 dataOnly = true;
6447 PackageSetting ps = mSettings.mPackages.get(packageName);
6448 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006449 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 return false;
6451 }
6452 p = ps.pkg;
6453 }
6454 }
6455 String publicSrcDir = null;
6456 if(!dataOnly) {
6457 final ApplicationInfo applicationInfo = p.applicationInfo;
6458 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006459 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 return false;
6461 }
6462 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6463 }
6464 if (mInstaller != null) {
6465 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayor1f4df902010-03-26 18:44:14 -07006466 publicSrcDir, pStats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 if (res < 0) {
6468 return false;
6469 } else {
6470 return true;
6471 }
6472 }
6473 return true;
6474 }
6475
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 public void addPackageToPreferred(String packageName) {
6478 mContext.enforceCallingOrSelfPermission(
6479 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006480 Slog.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 }
6482
6483 public void removePackageFromPreferred(String packageName) {
6484 mContext.enforceCallingOrSelfPermission(
6485 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006486 Slog.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
6489 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006490 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 }
6492
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006493 int getUidTargetSdkVersionLockedLP(int uid) {
6494 Object obj = mSettings.getUserIdLP(uid);
6495 if (obj instanceof SharedUserSetting) {
6496 SharedUserSetting sus = (SharedUserSetting)obj;
6497 final int N = sus.packages.size();
6498 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6499 Iterator<PackageSetting> it = sus.packages.iterator();
6500 int i=0;
6501 while (it.hasNext()) {
6502 PackageSetting ps = it.next();
6503 if (ps.pkg != null) {
6504 int v = ps.pkg.applicationInfo.targetSdkVersion;
6505 if (v < vers) vers = v;
6506 }
6507 }
6508 return vers;
6509 } else if (obj instanceof PackageSetting) {
6510 PackageSetting ps = (PackageSetting)obj;
6511 if (ps.pkg != null) {
6512 return ps.pkg.applicationInfo.targetSdkVersion;
6513 }
6514 }
6515 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6516 }
6517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006518 public void addPreferredActivity(IntentFilter filter, int match,
6519 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006521 if (mContext.checkCallingOrSelfPermission(
6522 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6523 != PackageManager.PERMISSION_GRANTED) {
6524 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6525 < Build.VERSION_CODES.FROYO) {
6526 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6527 + Binder.getCallingUid());
6528 return;
6529 }
6530 mContext.enforceCallingOrSelfPermission(
6531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6532 }
6533
6534 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6536 mSettings.mPreferredActivities.addFilter(
6537 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006538 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540 }
6541
Satish Sampath8dbe6122009-06-02 23:35:54 +01006542 public void replacePreferredActivity(IntentFilter filter, int match,
6543 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006544 if (filter.countActions() != 1) {
6545 throw new IllegalArgumentException(
6546 "replacePreferredActivity expects filter to have only 1 action.");
6547 }
6548 if (filter.countCategories() != 1) {
6549 throw new IllegalArgumentException(
6550 "replacePreferredActivity expects filter to have only 1 category.");
6551 }
6552 if (filter.countDataAuthorities() != 0
6553 || filter.countDataPaths() != 0
6554 || filter.countDataSchemes() != 0
6555 || filter.countDataTypes() != 0) {
6556 throw new IllegalArgumentException(
6557 "replacePreferredActivity expects filter to have no data authorities, " +
6558 "paths, schemes or types.");
6559 }
6560 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006561 if (mContext.checkCallingOrSelfPermission(
6562 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6563 != PackageManager.PERMISSION_GRANTED) {
6564 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6565 < Build.VERSION_CODES.FROYO) {
6566 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6567 + Binder.getCallingUid());
6568 return;
6569 }
6570 mContext.enforceCallingOrSelfPermission(
6571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6572 }
6573
Satish Sampath8dbe6122009-06-02 23:35:54 +01006574 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6575 String action = filter.getAction(0);
6576 String category = filter.getCategory(0);
6577 while (it.hasNext()) {
6578 PreferredActivity pa = it.next();
6579 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6580 it.remove();
6581 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6582 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6583 }
6584 }
6585 addPreferredActivity(filter, match, set, activity);
6586 }
6587 }
6588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006591 int uid = Binder.getCallingUid();
6592 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006593 if (pkg == null || pkg.applicationInfo.uid != uid) {
6594 if (mContext.checkCallingOrSelfPermission(
6595 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6596 != PackageManager.PERMISSION_GRANTED) {
6597 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6598 < Build.VERSION_CODES.FROYO) {
6599 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6600 + Binder.getCallingUid());
6601 return;
6602 }
6603 mContext.enforceCallingOrSelfPermission(
6604 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6605 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006606 }
6607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006609 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
6611 }
6612 }
6613
6614 boolean clearPackagePreferredActivitiesLP(String packageName) {
6615 boolean changed = false;
6616 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6617 while (it.hasNext()) {
6618 PreferredActivity pa = it.next();
6619 if (pa.mActivity.getPackageName().equals(packageName)) {
6620 it.remove();
6621 changed = true;
6622 }
6623 }
6624 return changed;
6625 }
6626
6627 public int getPreferredActivities(List<IntentFilter> outFilters,
6628 List<ComponentName> outActivities, String packageName) {
6629
6630 int num = 0;
6631 synchronized (mPackages) {
6632 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6633 while (it.hasNext()) {
6634 PreferredActivity pa = it.next();
6635 if (packageName == null
6636 || pa.mActivity.getPackageName().equals(packageName)) {
6637 if (outFilters != null) {
6638 outFilters.add(new IntentFilter(pa));
6639 }
6640 if (outActivities != null) {
6641 outActivities.add(pa.mActivity);
6642 }
6643 }
6644 }
6645 }
6646
6647 return num;
6648 }
6649
6650 public void setApplicationEnabledSetting(String appPackageName,
6651 int newState, int flags) {
6652 setEnabledSetting(appPackageName, null, newState, flags);
6653 }
6654
6655 public void setComponentEnabledSetting(ComponentName componentName,
6656 int newState, int flags) {
6657 setEnabledSetting(componentName.getPackageName(),
6658 componentName.getClassName(), newState, flags);
6659 }
6660
6661 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006662 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6664 || newState == COMPONENT_ENABLED_STATE_ENABLED
6665 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6666 throw new IllegalArgumentException("Invalid new component state: "
6667 + newState);
6668 }
6669 PackageSetting pkgSetting;
6670 final int uid = Binder.getCallingUid();
6671 final int permission = mContext.checkCallingPermission(
6672 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6673 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006674 boolean sendNow = false;
6675 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006676 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006678 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006680 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006682 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006684 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 }
6686 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006687 "Unknown component: " + packageName
6688 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 }
6690 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6691 throw new SecurityException(
6692 "Permission Denial: attempt to change component state from pid="
6693 + Binder.getCallingPid()
6694 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6695 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006696 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006698 if (pkgSetting.enabled == newState) {
6699 // Nothing to do
6700 return;
6701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 pkgSetting.enabled = newState;
6703 } else {
6704 // We're dealing with a component level state change
6705 switch (newState) {
6706 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006707 if (!pkgSetting.enableComponentLP(className)) {
6708 return;
6709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 break;
6711 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006712 if (!pkgSetting.disableComponentLP(className)) {
6713 return;
6714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 break;
6716 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006717 if (!pkgSetting.restoreComponentLP(className)) {
6718 return;
6719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 break;
6721 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006722 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006723 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
6725 }
6726 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006727 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006728 components = mPendingBroadcasts.get(packageName);
6729 boolean newPackage = components == null;
6730 if (newPackage) {
6731 components = new ArrayList<String>();
6732 }
6733 if (!components.contains(componentName)) {
6734 components.add(componentName);
6735 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006736 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6737 sendNow = true;
6738 // Purge entry from pending broadcast list if another one exists already
6739 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006740 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006742 if (newPackage) {
6743 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006744 }
6745 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6746 // Schedule a message
6747 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6748 }
6749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 long callingId = Binder.clearCallingIdentity();
6753 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 if (sendNow) {
6755 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006756 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 } finally {
6759 Binder.restoreCallingIdentity(callingId);
6760 }
6761 }
6762
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006763 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006764 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6765 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6766 + " components=" + componentNames);
6767 Bundle extras = new Bundle(4);
6768 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6769 String nameList[] = new String[componentNames.size()];
6770 componentNames.toArray(nameList);
6771 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6773 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006774 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 }
6776
Jacek Surazski65e13172009-04-28 15:26:38 +02006777 public String getInstallerPackageName(String packageName) {
6778 synchronized (mPackages) {
6779 PackageSetting pkg = mSettings.mPackages.get(packageName);
6780 if (pkg == null) {
6781 throw new IllegalArgumentException("Unknown package: " + packageName);
6782 }
6783 return pkg.installerPackageName;
6784 }
6785 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 public int getApplicationEnabledSetting(String appPackageName) {
6788 synchronized (mPackages) {
6789 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6790 if (pkg == null) {
6791 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6792 }
6793 return pkg.enabled;
6794 }
6795 }
6796
6797 public int getComponentEnabledSetting(ComponentName componentName) {
6798 synchronized (mPackages) {
6799 final String packageNameStr = componentName.getPackageName();
6800 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6801 if (pkg == null) {
6802 throw new IllegalArgumentException("Unknown component: " + componentName);
6803 }
6804 final String classNameStr = componentName.getClassName();
6805 return pkg.currentEnabledStateLP(classNameStr);
6806 }
6807 }
6808
6809 public void enterSafeMode() {
6810 if (!mSystemReady) {
6811 mSafeMode = true;
6812 }
6813 }
6814
6815 public void systemReady() {
6816 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006817
6818 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006819 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006820 mContext.getContentResolver(),
6821 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006822 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006823 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006824 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 }
6827
6828 public boolean isSafeMode() {
6829 return mSafeMode;
6830 }
6831
6832 public boolean hasSystemUidErrors() {
6833 return mHasSystemUidErrors;
6834 }
6835
6836 static String arrayToString(int[] array) {
6837 StringBuffer buf = new StringBuffer(128);
6838 buf.append('[');
6839 if (array != null) {
6840 for (int i=0; i<array.length; i++) {
6841 if (i > 0) buf.append(", ");
6842 buf.append(array[i]);
6843 }
6844 }
6845 buf.append(']');
6846 return buf.toString();
6847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 @Override
6850 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6851 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6852 != PackageManager.PERMISSION_GRANTED) {
6853 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6854 + Binder.getCallingPid()
6855 + ", uid=" + Binder.getCallingUid()
6856 + " without permission "
6857 + android.Manifest.permission.DUMP);
6858 return;
6859 }
6860
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006861 String packageName = null;
6862
6863 int opti = 0;
6864 while (opti < args.length) {
6865 String opt = args[opti];
6866 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6867 break;
6868 }
6869 opti++;
6870 if ("-a".equals(opt)) {
6871 // Right now we only know how to print all.
6872 } else if ("-h".equals(opt)) {
6873 pw.println("Package manager dump options:");
6874 pw.println(" [-h] [cmd] ...");
6875 pw.println(" cmd may be one of:");
6876 pw.println(" [package.name]: info about given package");
6877 return;
6878 } else {
6879 pw.println("Unknown argument: " + opt + "; use -h for help");
6880 }
6881 }
6882
6883 // Is the caller requesting to dump a particular piece of data?
6884 if (opti < args.length) {
6885 String cmd = args[opti];
6886 opti++;
6887 // Is this a package name?
6888 if ("android".equals(cmd) || cmd.contains(".")) {
6889 packageName = cmd;
6890 }
6891 }
6892
6893 boolean printedTitle = false;
6894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006895 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006896 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6897 printedTitle = true;
6898 }
6899 if (mReceivers.dump(pw, printedTitle
6900 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6901 " ", packageName)) {
6902 printedTitle = true;
6903 }
6904 if (mServices.dump(pw, printedTitle
6905 ? "\nService Resolver Table:" : "Service Resolver Table:",
6906 " ", packageName)) {
6907 printedTitle = true;
6908 }
6909 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6910 ? "\nPreferred Activities:" : "Preferred Activities:",
6911 " ", packageName)) {
6912 printedTitle = true;
6913 }
6914 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 {
6916 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006917 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6918 continue;
6919 }
6920 if (!printedSomething) {
6921 if (printedTitle) pw.println(" ");
6922 pw.println("Permissions:");
6923 printedSomething = true;
6924 printedTitle = true;
6925 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006926 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6927 pw.print(Integer.toHexString(System.identityHashCode(p)));
6928 pw.println("):");
6929 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6930 pw.print(" uid="); pw.print(p.uid);
6931 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006932 pw.print(" type="); pw.print(p.type);
6933 pw.print(" prot="); pw.println(p.protectionLevel);
6934 if (p.packageSetting != null) {
6935 pw.print(" packageSetting="); pw.println(p.packageSetting);
6936 }
6937 if (p.perm != null) {
6938 pw.print(" perm="); pw.println(p.perm);
6939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 }
6941 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 printedSomething = false;
6943 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 {
6945 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006946 if (packageName != null && !packageName.equals(ps.realName)
6947 && !packageName.equals(ps.name)) {
6948 continue;
6949 }
6950 if (!printedSomething) {
6951 if (printedTitle) pw.println(" ");
6952 pw.println("Packages:");
6953 printedSomething = true;
6954 printedTitle = true;
6955 }
6956 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006957 pw.print(" Package [");
6958 pw.print(ps.realName != null ? ps.realName : ps.name);
6959 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006960 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6961 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006962 if (ps.realName != null) {
6963 pw.print(" compat name="); pw.println(ps.name);
6964 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006965 pw.print(" userId="); pw.print(ps.userId);
6966 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6967 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6968 pw.print(" pkg="); pw.println(ps.pkg);
6969 pw.print(" codePath="); pw.println(ps.codePathString);
6970 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006972 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006973 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006974 pw.print(" supportsScreens=[");
6975 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006976 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006977 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006978 if (!first) pw.print(", ");
6979 first = false;
6980 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006982 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006983 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006984 if (!first) pw.print(", ");
6985 first = false;
6986 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006987 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006988 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006989 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006990 if (!first) pw.print(", ");
6991 first = false;
6992 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006993 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006994 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006995 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006996 if (!first) pw.print(", ");
6997 first = false;
6998 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007000 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007001 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7002 if (!first) pw.print(", ");
7003 first = false;
7004 pw.print("anyDensity");
7005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007006 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007007 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007008 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7009 pw.print(" signatures="); pw.println(ps.signatures);
7010 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007011 pw.print(" haveGids="); pw.println(ps.haveGids);
7012 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007013 pw.print(" installStatus="); pw.print(ps.installStatus);
7014 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 if (ps.disabledComponents.size() > 0) {
7016 pw.println(" disabledComponents:");
7017 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007018 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 }
7020 }
7021 if (ps.enabledComponents.size() > 0) {
7022 pw.println(" enabledComponents:");
7023 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007024 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 }
7026 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007027 if (ps.grantedPermissions.size() > 0) {
7028 pw.println(" grantedPermissions:");
7029 for (String s : ps.grantedPermissions) {
7030 pw.print(" "); pw.println(s);
7031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 }
7034 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007035 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007036 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007037 for (HashMap.Entry<String, String> e
7038 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007039 if (packageName != null && !packageName.equals(e.getKey())
7040 && !packageName.equals(e.getValue())) {
7041 continue;
7042 }
7043 if (!printedSomething) {
7044 if (printedTitle) pw.println(" ");
7045 pw.println("Renamed packages:");
7046 printedSomething = true;
7047 printedTitle = true;
7048 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007049 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7050 pw.println(e.getValue());
7051 }
7052 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007053 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007054 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007055 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007056 if (packageName != null && !packageName.equals(ps.realName)
7057 && !packageName.equals(ps.name)) {
7058 continue;
7059 }
7060 if (!printedSomething) {
7061 if (printedTitle) pw.println(" ");
7062 pw.println("Hidden system packages:");
7063 printedSomething = true;
7064 printedTitle = true;
7065 }
7066 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007067 pw.print(ps.realName != null ? ps.realName : ps.name);
7068 pw.print("] (");
7069 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7070 pw.println("):");
7071 if (ps.realName != null) {
7072 pw.print(" compat name="); pw.println(ps.name);
7073 }
7074 pw.print(" userId="); pw.println(ps.userId);
7075 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7076 pw.print(" codePath="); pw.println(ps.codePathString);
7077 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7078 }
7079 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007080 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 {
7082 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007083 if (packageName != null && su != packageSharedUser) {
7084 continue;
7085 }
7086 if (!printedSomething) {
7087 if (printedTitle) pw.println(" ");
7088 pw.println("Shared users:");
7089 printedSomething = true;
7090 printedTitle = true;
7091 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007092 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7093 pw.print(Integer.toHexString(System.identityHashCode(su)));
7094 pw.println("):");
7095 pw.print(" userId="); pw.print(su.userId);
7096 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 pw.println(" grantedPermissions:");
7098 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007099 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 }
7102 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007103
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007104 if (packageName == null) {
7105 if (printedTitle) pw.println(" ");
7106 printedTitle = true;
7107 pw.println("Settings parse messages:");
7108 pw.println(mSettings.mReadMessages.toString());
7109
7110 pw.println(" ");
7111 pw.println("Package warning messages:");
7112 File fname = getSettingsProblemFile();
7113 FileInputStream in;
7114 try {
7115 in = new FileInputStream(fname);
7116 int avail = in.available();
7117 byte[] data = new byte[avail];
7118 in.read(data);
7119 pw.println(new String(data));
7120 } catch (FileNotFoundException e) {
7121 } catch (IOException e) {
7122 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007125
7126 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007127 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007128 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007129 if (packageName != null && !packageName.equals(p.info.packageName)) {
7130 continue;
7131 }
7132 if (!printedSomething) {
7133 if (printedTitle) pw.println(" ");
7134 pw.println("Registered ContentProviders:");
7135 printedSomething = true;
7136 printedTitle = true;
7137 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007138 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007139 pw.println(p.toString());
7140 }
7141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 }
7143
7144 static final class BasePermission {
7145 final static int TYPE_NORMAL = 0;
7146 final static int TYPE_BUILTIN = 1;
7147 final static int TYPE_DYNAMIC = 2;
7148
7149 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007150 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007151 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007153 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 PackageParser.Permission perm;
7155 PermissionInfo pendingInfo;
7156 int uid;
7157 int[] gids;
7158
7159 BasePermission(String _name, String _sourcePackage, int _type) {
7160 name = _name;
7161 sourcePackage = _sourcePackage;
7162 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007163 // Default to most conservative protection level.
7164 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7165 }
7166
7167 public String toString() {
7168 return "BasePermission{"
7169 + Integer.toHexString(System.identityHashCode(this))
7170 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 }
7172 }
7173
7174 static class PackageSignatures {
7175 private Signature[] mSignatures;
7176
7177 PackageSignatures(Signature[] sigs) {
7178 assignSignatures(sigs);
7179 }
7180
7181 PackageSignatures() {
7182 }
7183
7184 void writeXml(XmlSerializer serializer, String tagName,
7185 ArrayList<Signature> pastSignatures) throws IOException {
7186 if (mSignatures == null) {
7187 return;
7188 }
7189 serializer.startTag(null, tagName);
7190 serializer.attribute(null, "count",
7191 Integer.toString(mSignatures.length));
7192 for (int i=0; i<mSignatures.length; i++) {
7193 serializer.startTag(null, "cert");
7194 final Signature sig = mSignatures[i];
7195 final int sigHash = sig.hashCode();
7196 final int numPast = pastSignatures.size();
7197 int j;
7198 for (j=0; j<numPast; j++) {
7199 Signature pastSig = pastSignatures.get(j);
7200 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7201 serializer.attribute(null, "index", Integer.toString(j));
7202 break;
7203 }
7204 }
7205 if (j >= numPast) {
7206 pastSignatures.add(sig);
7207 serializer.attribute(null, "index", Integer.toString(numPast));
7208 serializer.attribute(null, "key", sig.toCharsString());
7209 }
7210 serializer.endTag(null, "cert");
7211 }
7212 serializer.endTag(null, tagName);
7213 }
7214
7215 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7216 throws IOException, XmlPullParserException {
7217 String countStr = parser.getAttributeValue(null, "count");
7218 if (countStr == null) {
7219 reportSettingsProblem(Log.WARN,
7220 "Error in package manager settings: <signatures> has"
7221 + " no count at " + parser.getPositionDescription());
7222 XmlUtils.skipCurrentTag(parser);
7223 }
7224 final int count = Integer.parseInt(countStr);
7225 mSignatures = new Signature[count];
7226 int pos = 0;
7227
7228 int outerDepth = parser.getDepth();
7229 int type;
7230 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7231 && (type != XmlPullParser.END_TAG
7232 || parser.getDepth() > outerDepth)) {
7233 if (type == XmlPullParser.END_TAG
7234 || type == XmlPullParser.TEXT) {
7235 continue;
7236 }
7237
7238 String tagName = parser.getName();
7239 if (tagName.equals("cert")) {
7240 if (pos < count) {
7241 String index = parser.getAttributeValue(null, "index");
7242 if (index != null) {
7243 try {
7244 int idx = Integer.parseInt(index);
7245 String key = parser.getAttributeValue(null, "key");
7246 if (key == null) {
7247 if (idx >= 0 && idx < pastSignatures.size()) {
7248 Signature sig = pastSignatures.get(idx);
7249 if (sig != null) {
7250 mSignatures[pos] = pastSignatures.get(idx);
7251 pos++;
7252 } else {
7253 reportSettingsProblem(Log.WARN,
7254 "Error in package manager settings: <cert> "
7255 + "index " + index + " is not defined at "
7256 + parser.getPositionDescription());
7257 }
7258 } else {
7259 reportSettingsProblem(Log.WARN,
7260 "Error in package manager settings: <cert> "
7261 + "index " + index + " is out of bounds at "
7262 + parser.getPositionDescription());
7263 }
7264 } else {
7265 while (pastSignatures.size() <= idx) {
7266 pastSignatures.add(null);
7267 }
7268 Signature sig = new Signature(key);
7269 pastSignatures.set(idx, sig);
7270 mSignatures[pos] = sig;
7271 pos++;
7272 }
7273 } catch (NumberFormatException e) {
7274 reportSettingsProblem(Log.WARN,
7275 "Error in package manager settings: <cert> "
7276 + "index " + index + " is not a number at "
7277 + parser.getPositionDescription());
7278 }
7279 } else {
7280 reportSettingsProblem(Log.WARN,
7281 "Error in package manager settings: <cert> has"
7282 + " no index at " + parser.getPositionDescription());
7283 }
7284 } else {
7285 reportSettingsProblem(Log.WARN,
7286 "Error in package manager settings: too "
7287 + "many <cert> tags, expected " + count
7288 + " at " + parser.getPositionDescription());
7289 }
7290 } else {
7291 reportSettingsProblem(Log.WARN,
7292 "Unknown element under <cert>: "
7293 + parser.getName());
7294 }
7295 XmlUtils.skipCurrentTag(parser);
7296 }
7297
7298 if (pos < count) {
7299 // Should never happen -- there is an error in the written
7300 // settings -- but if it does we don't want to generate
7301 // a bad array.
7302 Signature[] newSigs = new Signature[pos];
7303 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7304 mSignatures = newSigs;
7305 }
7306 }
7307
7308 /**
7309 * If any of the given 'sigs' is contained in the existing signatures,
7310 * then completely replace the current signatures with the ones in
7311 * 'sigs'. This is used for updating an existing package to a newly
7312 * installed version.
7313 */
7314 boolean updateSignatures(Signature[] sigs, boolean update) {
7315 if (mSignatures == null) {
7316 if (update) {
7317 assignSignatures(sigs);
7318 }
7319 return true;
7320 }
7321 if (sigs == null) {
7322 return false;
7323 }
7324
7325 for (int i=0; i<sigs.length; i++) {
7326 Signature sig = sigs[i];
7327 for (int j=0; j<mSignatures.length; j++) {
7328 if (mSignatures[j].equals(sig)) {
7329 if (update) {
7330 assignSignatures(sigs);
7331 }
7332 return true;
7333 }
7334 }
7335 }
7336 return false;
7337 }
7338
7339 /**
7340 * If any of the given 'sigs' is contained in the existing signatures,
7341 * then add in any new signatures found in 'sigs'. This is used for
7342 * including a new package into an existing shared user id.
7343 */
7344 boolean mergeSignatures(Signature[] sigs, boolean update) {
7345 if (mSignatures == null) {
7346 if (update) {
7347 assignSignatures(sigs);
7348 }
7349 return true;
7350 }
7351 if (sigs == null) {
7352 return false;
7353 }
7354
7355 Signature[] added = null;
7356 int addedCount = 0;
7357 boolean haveMatch = false;
7358 for (int i=0; i<sigs.length; i++) {
7359 Signature sig = sigs[i];
7360 boolean found = false;
7361 for (int j=0; j<mSignatures.length; j++) {
7362 if (mSignatures[j].equals(sig)) {
7363 found = true;
7364 haveMatch = true;
7365 break;
7366 }
7367 }
7368
7369 if (!found) {
7370 if (added == null) {
7371 added = new Signature[sigs.length];
7372 }
7373 added[i] = sig;
7374 addedCount++;
7375 }
7376 }
7377
7378 if (!haveMatch) {
7379 // Nothing matched -- reject the new signatures.
7380 return false;
7381 }
7382 if (added == null) {
7383 // Completely matched -- nothing else to do.
7384 return true;
7385 }
7386
7387 // Add additional signatures in.
7388 if (update) {
7389 Signature[] total = new Signature[addedCount+mSignatures.length];
7390 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
7391 int j = mSignatures.length;
7392 for (int i=0; i<added.length; i++) {
7393 if (added[i] != null) {
7394 total[j] = added[i];
7395 j++;
7396 }
7397 }
7398 mSignatures = total;
7399 }
7400 return true;
7401 }
7402
7403 private void assignSignatures(Signature[] sigs) {
7404 if (sigs == null) {
7405 mSignatures = null;
7406 return;
7407 }
7408 mSignatures = new Signature[sigs.length];
7409 for (int i=0; i<sigs.length; i++) {
7410 mSignatures[i] = sigs[i];
7411 }
7412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 @Override
7415 public String toString() {
7416 StringBuffer buf = new StringBuffer(128);
7417 buf.append("PackageSignatures{");
7418 buf.append(Integer.toHexString(System.identityHashCode(this)));
7419 buf.append(" [");
7420 if (mSignatures != null) {
7421 for (int i=0; i<mSignatures.length; i++) {
7422 if (i > 0) buf.append(", ");
7423 buf.append(Integer.toHexString(
7424 System.identityHashCode(mSignatures[i])));
7425 }
7426 }
7427 buf.append("]}");
7428 return buf.toString();
7429 }
7430 }
7431
7432 static class PreferredActivity extends IntentFilter {
7433 final int mMatch;
7434 final String[] mSetPackages;
7435 final String[] mSetClasses;
7436 final String[] mSetComponents;
7437 final ComponentName mActivity;
7438 final String mShortActivity;
7439 String mParseError;
7440
7441 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7442 ComponentName activity) {
7443 super(filter);
7444 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7445 mActivity = activity;
7446 mShortActivity = activity.flattenToShortString();
7447 mParseError = null;
7448 if (set != null) {
7449 final int N = set.length;
7450 String[] myPackages = new String[N];
7451 String[] myClasses = new String[N];
7452 String[] myComponents = new String[N];
7453 for (int i=0; i<N; i++) {
7454 ComponentName cn = set[i];
7455 if (cn == null) {
7456 mSetPackages = null;
7457 mSetClasses = null;
7458 mSetComponents = null;
7459 return;
7460 }
7461 myPackages[i] = cn.getPackageName().intern();
7462 myClasses[i] = cn.getClassName().intern();
7463 myComponents[i] = cn.flattenToShortString().intern();
7464 }
7465 mSetPackages = myPackages;
7466 mSetClasses = myClasses;
7467 mSetComponents = myComponents;
7468 } else {
7469 mSetPackages = null;
7470 mSetClasses = null;
7471 mSetComponents = null;
7472 }
7473 }
7474
7475 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7476 IOException {
7477 mShortActivity = parser.getAttributeValue(null, "name");
7478 mActivity = ComponentName.unflattenFromString(mShortActivity);
7479 if (mActivity == null) {
7480 mParseError = "Bad activity name " + mShortActivity;
7481 }
7482 String matchStr = parser.getAttributeValue(null, "match");
7483 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7484 String setCountStr = parser.getAttributeValue(null, "set");
7485 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7486
7487 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7488 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7489 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7490
7491 int setPos = 0;
7492
7493 int outerDepth = parser.getDepth();
7494 int type;
7495 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7496 && (type != XmlPullParser.END_TAG
7497 || parser.getDepth() > outerDepth)) {
7498 if (type == XmlPullParser.END_TAG
7499 || type == XmlPullParser.TEXT) {
7500 continue;
7501 }
7502
7503 String tagName = parser.getName();
7504 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7505 // + parser.getDepth() + " tag=" + tagName);
7506 if (tagName.equals("set")) {
7507 String name = parser.getAttributeValue(null, "name");
7508 if (name == null) {
7509 if (mParseError == null) {
7510 mParseError = "No name in set tag in preferred activity "
7511 + mShortActivity;
7512 }
7513 } else if (setPos >= setCount) {
7514 if (mParseError == null) {
7515 mParseError = "Too many set tags in preferred activity "
7516 + mShortActivity;
7517 }
7518 } else {
7519 ComponentName cn = ComponentName.unflattenFromString(name);
7520 if (cn == null) {
7521 if (mParseError == null) {
7522 mParseError = "Bad set name " + name + " in preferred activity "
7523 + mShortActivity;
7524 }
7525 } else {
7526 myPackages[setPos] = cn.getPackageName();
7527 myClasses[setPos] = cn.getClassName();
7528 myComponents[setPos] = name;
7529 setPos++;
7530 }
7531 }
7532 XmlUtils.skipCurrentTag(parser);
7533 } else if (tagName.equals("filter")) {
7534 //Log.i(TAG, "Starting to parse filter...");
7535 readFromXml(parser);
7536 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7537 // + parser.getDepth() + " tag=" + parser.getName());
7538 } else {
7539 reportSettingsProblem(Log.WARN,
7540 "Unknown element under <preferred-activities>: "
7541 + parser.getName());
7542 XmlUtils.skipCurrentTag(parser);
7543 }
7544 }
7545
7546 if (setPos != setCount) {
7547 if (mParseError == null) {
7548 mParseError = "Not enough set tags (expected " + setCount
7549 + " but found " + setPos + ") in " + mShortActivity;
7550 }
7551 }
7552
7553 mSetPackages = myPackages;
7554 mSetClasses = myClasses;
7555 mSetComponents = myComponents;
7556 }
7557
7558 public void writeToXml(XmlSerializer serializer) throws IOException {
7559 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7560 serializer.attribute(null, "name", mShortActivity);
7561 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7562 serializer.attribute(null, "set", Integer.toString(NS));
7563 for (int s=0; s<NS; s++) {
7564 serializer.startTag(null, "set");
7565 serializer.attribute(null, "name", mSetComponents[s]);
7566 serializer.endTag(null, "set");
7567 }
7568 serializer.startTag(null, "filter");
7569 super.writeToXml(serializer);
7570 serializer.endTag(null, "filter");
7571 }
7572
7573 boolean sameSet(List<ResolveInfo> query, int priority) {
7574 if (mSetPackages == null) return false;
7575 final int NQ = query.size();
7576 final int NS = mSetPackages.length;
7577 int numMatch = 0;
7578 for (int i=0; i<NQ; i++) {
7579 ResolveInfo ri = query.get(i);
7580 if (ri.priority != priority) continue;
7581 ActivityInfo ai = ri.activityInfo;
7582 boolean good = false;
7583 for (int j=0; j<NS; j++) {
7584 if (mSetPackages[j].equals(ai.packageName)
7585 && mSetClasses[j].equals(ai.name)) {
7586 numMatch++;
7587 good = true;
7588 break;
7589 }
7590 }
7591 if (!good) return false;
7592 }
7593 return numMatch == NS;
7594 }
7595 }
7596
7597 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007598 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 HashSet<String> grantedPermissions = new HashSet<String>();
7601 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007604 setFlags(pkgFlags);
7605 }
7606
7607 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007608 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007609 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
Oscar Montemayor1f4df902010-03-26 18:44:14 -07007610 (pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 }
7612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 /**
7615 * Settings base class for pending and resolved classes.
7616 */
7617 static class PackageSettingBase extends GrantedPermissions {
7618 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007619 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007620 File codePath;
7621 String codePathString;
7622 File resourcePath;
7623 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 private long timeStamp;
7625 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007626 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007628 boolean uidError;
7629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 PackageSignatures signatures = new PackageSignatures();
7631
7632 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007633 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 /* Explicitly disabled components */
7636 HashSet<String> disabledComponents = new HashSet<String>(0);
7637 /* Explicitly enabled components */
7638 HashSet<String> enabledComponents = new HashSet<String>(0);
7639 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7640 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007641
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007642 PackageSettingBase origPackage;
7643
Jacek Surazski65e13172009-04-28 15:26:38 +02007644 /* package name of the app that installed this package */
7645 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007647 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007648 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 super(pkgFlags);
7650 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007651 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007652 init(codePath, resourcePath, pVersionCode);
7653 }
7654
7655 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 this.codePath = codePath;
7657 this.codePathString = codePath.toString();
7658 this.resourcePath = resourcePath;
7659 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007660 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007662
Jacek Surazski65e13172009-04-28 15:26:38 +02007663 public void setInstallerPackageName(String packageName) {
7664 installerPackageName = packageName;
7665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007666
Jacek Surazski65e13172009-04-28 15:26:38 +02007667 String getInstallerPackageName() {
7668 return installerPackageName;
7669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 public void setInstallStatus(int newStatus) {
7672 installStatus = newStatus;
7673 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 public int getInstallStatus() {
7676 return installStatus;
7677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 public void setTimeStamp(long newStamp) {
7680 if (newStamp != timeStamp) {
7681 timeStamp = newStamp;
7682 timeStampString = Long.toString(newStamp);
7683 }
7684 }
7685
7686 public void setTimeStamp(long newStamp, String newStampStr) {
7687 timeStamp = newStamp;
7688 timeStampString = newStampStr;
7689 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 public long getTimeStamp() {
7692 return timeStamp;
7693 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 public String getTimeStampStr() {
7696 return timeStampString;
7697 }
7698
7699 public void copyFrom(PackageSettingBase base) {
7700 grantedPermissions = base.grantedPermissions;
7701 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 timeStamp = base.timeStamp;
7704 timeStampString = base.timeStampString;
7705 signatures = base.signatures;
7706 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007707 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 disabledComponents = base.disabledComponents;
7709 enabledComponents = base.enabledComponents;
7710 enabled = base.enabled;
7711 installStatus = base.installStatus;
7712 }
7713
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007714 boolean enableComponentLP(String componentClassName) {
7715 boolean changed = disabledComponents.remove(componentClassName);
7716 changed |= enabledComponents.add(componentClassName);
7717 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 }
7719
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007720 boolean disableComponentLP(String componentClassName) {
7721 boolean changed = enabledComponents.remove(componentClassName);
7722 changed |= disabledComponents.add(componentClassName);
7723 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 }
7725
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007726 boolean restoreComponentLP(String componentClassName) {
7727 boolean changed = enabledComponents.remove(componentClassName);
7728 changed |= disabledComponents.remove(componentClassName);
7729 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 }
7731
7732 int currentEnabledStateLP(String componentName) {
7733 if (enabledComponents.contains(componentName)) {
7734 return COMPONENT_ENABLED_STATE_ENABLED;
7735 } else if (disabledComponents.contains(componentName)) {
7736 return COMPONENT_ENABLED_STATE_DISABLED;
7737 } else {
7738 return COMPONENT_ENABLED_STATE_DEFAULT;
7739 }
7740 }
7741 }
7742
7743 /**
7744 * Settings data for a particular package we know about.
7745 */
7746 static final class PackageSetting extends PackageSettingBase {
7747 int userId;
7748 PackageParser.Package pkg;
7749 SharedUserSetting sharedUser;
7750
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007751 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007752 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007753 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 @Override
7757 public String toString() {
7758 return "PackageSetting{"
7759 + Integer.toHexString(System.identityHashCode(this))
7760 + " " + name + "/" + userId + "}";
7761 }
7762 }
7763
7764 /**
7765 * Settings data for a particular shared user ID we know about.
7766 */
7767 static final class SharedUserSetting extends GrantedPermissions {
7768 final String name;
7769 int userId;
7770 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7771 final PackageSignatures signatures = new PackageSignatures();
7772
7773 SharedUserSetting(String _name, int _pkgFlags) {
7774 super(_pkgFlags);
7775 name = _name;
7776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 @Override
7779 public String toString() {
7780 return "SharedUserSetting{"
7781 + Integer.toHexString(System.identityHashCode(this))
7782 + " " + name + "/" + userId + "}";
7783 }
7784 }
7785
7786 /**
7787 * Holds information about dynamic settings.
7788 */
7789 private static final class Settings {
7790 private final File mSettingsFilename;
7791 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007792 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 private final HashMap<String, PackageSetting> mPackages =
7794 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 // List of replaced system applications
7796 final HashMap<String, PackageSetting> mDisabledSysPackages =
7797 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 // The user's preferred activities associated with particular intent
7800 // filters.
7801 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7802 new IntentResolver<PreferredActivity, PreferredActivity>() {
7803 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007804 protected String packageForFilter(PreferredActivity filter) {
7805 return filter.mActivity.getPackageName();
7806 }
7807 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007808 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007810 out.print(prefix); out.print(
7811 Integer.toHexString(System.identityHashCode(filter)));
7812 out.print(' ');
7813 out.print(filter.mActivity.flattenToShortString());
7814 out.print(" match=0x");
7815 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007817 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007819 out.print(prefix); out.print(" ");
7820 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 }
7822 }
7823 }
7824 };
7825 private final HashMap<String, SharedUserSetting> mSharedUsers =
7826 new HashMap<String, SharedUserSetting>();
7827 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7828 private final SparseArray<Object> mOtherUserIds =
7829 new SparseArray<Object>();
7830
7831 // For reading/writing settings file.
7832 private final ArrayList<Signature> mPastSignatures =
7833 new ArrayList<Signature>();
7834
7835 // Mapping from permission names to info about them.
7836 final HashMap<String, BasePermission> mPermissions =
7837 new HashMap<String, BasePermission>();
7838
7839 // Mapping from permission tree names to info about them.
7840 final HashMap<String, BasePermission> mPermissionTrees =
7841 new HashMap<String, BasePermission>();
7842
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007843 // Packages that have been uninstalled and still need their external
7844 // storage data deleted.
7845 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7846
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007847 // Packages that have been renamed since they were first installed.
7848 // Keys are the new names of the packages, values are the original
7849 // names. The packages appear everwhere else under their original
7850 // names.
7851 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 private final StringBuilder mReadMessages = new StringBuilder();
7854
7855 private static final class PendingPackage extends PackageSettingBase {
7856 final int sharedId;
7857
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007858 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007859 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007860 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 this.sharedId = sharedId;
7862 }
7863 }
7864 private final ArrayList<PendingPackage> mPendingPackages
7865 = new ArrayList<PendingPackage>();
7866
7867 Settings() {
7868 File dataDir = Environment.getDataDirectory();
7869 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007870 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 systemDir.mkdirs();
7872 FileUtils.setPermissions(systemDir.toString(),
7873 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7874 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7875 -1, -1);
7876 mSettingsFilename = new File(systemDir, "packages.xml");
7877 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007878 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 }
7880
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007881 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007882 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 int pkgFlags, boolean create, boolean add) {
7884 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007885 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007886 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 return p;
7888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007889
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007890 PackageSetting peekPackageLP(String name) {
7891 return mPackages.get(name);
7892 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 PackageSetting p = mPackages.get(name);
7894 if (p != null && p.codePath.getPath().equals(codePath)) {
7895 return p;
7896 }
7897 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007898 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 void setInstallStatus(String pkgName, int status) {
7902 PackageSetting p = mPackages.get(pkgName);
7903 if(p != null) {
7904 if(p.getInstallStatus() != status) {
7905 p.setInstallStatus(status);
7906 }
7907 }
7908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007909
Jacek Surazski65e13172009-04-28 15:26:38 +02007910 void setInstallerPackageName(String pkgName,
7911 String installerPkgName) {
7912 PackageSetting p = mPackages.get(pkgName);
7913 if(p != null) {
7914 p.setInstallerPackageName(installerPkgName);
7915 }
7916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007917
Jacek Surazski65e13172009-04-28 15:26:38 +02007918 String getInstallerPackageName(String pkgName) {
7919 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007920 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007921 }
7922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 int getInstallStatus(String pkgName) {
7924 PackageSetting p = mPackages.get(pkgName);
7925 if(p != null) {
7926 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 return -1;
7929 }
7930
7931 SharedUserSetting getSharedUserLP(String name,
7932 int pkgFlags, boolean create) {
7933 SharedUserSetting s = mSharedUsers.get(name);
7934 if (s == null) {
7935 if (!create) {
7936 return null;
7937 }
7938 s = new SharedUserSetting(name, pkgFlags);
7939 if (MULTIPLE_APPLICATION_UIDS) {
7940 s.userId = newUserIdLP(s);
7941 } else {
7942 s.userId = FIRST_APPLICATION_UID;
7943 }
7944 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7945 // < 0 means we couldn't assign a userid; fall out and return
7946 // s, which is currently null
7947 if (s.userId >= 0) {
7948 mSharedUsers.put(name, s);
7949 }
7950 }
7951
7952 return s;
7953 }
7954
7955 int disableSystemPackageLP(String name) {
7956 PackageSetting p = mPackages.get(name);
7957 if(p == null) {
7958 Log.w(TAG, "Package:"+name+" is not an installed package");
7959 return -1;
7960 }
7961 PackageSetting dp = mDisabledSysPackages.get(name);
7962 // always make sure the system package code and resource paths dont change
7963 if(dp == null) {
7964 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7965 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7966 }
7967 mDisabledSysPackages.put(name, p);
7968 }
7969 return removePackageLP(name);
7970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 PackageSetting enableSystemPackageLP(String name) {
7973 PackageSetting p = mDisabledSysPackages.get(name);
7974 if(p == null) {
7975 Log.w(TAG, "Package:"+name+" is not disabled");
7976 return null;
7977 }
7978 // Reset flag in ApplicationInfo object
7979 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7980 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7981 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007982 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007983 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 mDisabledSysPackages.remove(name);
7985 return ret;
7986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007987
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007988 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007989 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 PackageSetting p = mPackages.get(name);
7991 if (p != null) {
7992 if (p.userId == uid) {
7993 return p;
7994 }
7995 reportSettingsProblem(Log.ERROR,
7996 "Adding duplicate package, keeping first: " + name);
7997 return null;
7998 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007999 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 p.userId = uid;
8001 if (addUserIdLP(uid, p, name)) {
8002 mPackages.put(name, p);
8003 return p;
8004 }
8005 return null;
8006 }
8007
8008 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8009 SharedUserSetting s = mSharedUsers.get(name);
8010 if (s != null) {
8011 if (s.userId == uid) {
8012 return s;
8013 }
8014 reportSettingsProblem(Log.ERROR,
8015 "Adding duplicate shared user, keeping first: " + name);
8016 return null;
8017 }
8018 s = new SharedUserSetting(name, pkgFlags);
8019 s.userId = uid;
8020 if (addUserIdLP(uid, s, name)) {
8021 mSharedUsers.put(name, s);
8022 return s;
8023 }
8024 return null;
8025 }
8026
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008027 // Transfer ownership of permissions from one package to another.
8028 private void transferPermissions(String origPkg, String newPkg) {
8029 // Transfer ownership of permissions to the new package.
8030 for (int i=0; i<2; i++) {
8031 HashMap<String, BasePermission> permissions =
8032 i == 0 ? mPermissionTrees : mPermissions;
8033 for (BasePermission bp : permissions.values()) {
8034 if (origPkg.equals(bp.sourcePackage)) {
8035 if (DEBUG_UPGRADE) Log.v(TAG,
8036 "Moving permission " + bp.name
8037 + " from pkg " + bp.sourcePackage
8038 + " to " + newPkg);
8039 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008040 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008041 bp.perm = null;
8042 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008043 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008044 }
8045 bp.uid = 0;
8046 bp.gids = null;
8047 }
8048 }
8049 }
8050 }
8051
8052 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008053 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008054 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 PackageSetting p = mPackages.get(name);
8056 if (p != null) {
8057 if (!p.codePath.equals(codePath)) {
8058 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008059 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008060 // This is an updated system app with versions in both system
8061 // and data partition. Just let the most recent version
8062 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008063 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008064 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008065 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008066 // Just a change in the code path is not an issue, but
8067 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008068 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008069 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008071 }
8072 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 reportSettingsProblem(Log.WARN,
8074 "Package " + name + " shared user changed from "
8075 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8076 + " to "
8077 + (sharedUser != null ? sharedUser.name : "<nothing>")
8078 + "; replacing with new");
8079 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008080 } else {
8081 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8082 // If what we are scanning is a system package, then
8083 // make it so, regardless of whether it was previously
8084 // installed only in the data partition.
8085 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 }
8088 }
8089 if (p == null) {
8090 // Create a new PackageSettings entry. this can end up here because
8091 // of code path mismatch or user id mismatch of an updated system partition
8092 if (!create) {
8093 return null;
8094 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008095 if (origPackage != null) {
8096 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008097 p = new PackageSetting(origPackage.name, name, codePath,
8098 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008099 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8100 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008101 // Note that we will retain the new package's signature so
8102 // that we can keep its data.
8103 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008104 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008105 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008106 p.sharedUser = origPackage.sharedUser;
8107 p.userId = origPackage.userId;
8108 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008109 mRenamedPackages.put(name, origPackage.name);
8110 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008111 // Update new package state.
8112 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008114 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008115 p.setTimeStamp(codePath.lastModified());
8116 p.sharedUser = sharedUser;
8117 if (sharedUser != null) {
8118 p.userId = sharedUser.userId;
8119 } else if (MULTIPLE_APPLICATION_UIDS) {
8120 // Clone the setting here for disabled system packages
8121 PackageSetting dis = mDisabledSysPackages.get(name);
8122 if (dis != null) {
8123 // For disabled packages a new setting is created
8124 // from the existing user id. This still has to be
8125 // added to list of user id's
8126 // Copy signatures from previous setting
8127 if (dis.signatures.mSignatures != null) {
8128 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8129 }
8130 p.userId = dis.userId;
8131 // Clone permissions
8132 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008133 // Clone component info
8134 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8135 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8136 // Add new setting to list of user ids
8137 addUserIdLP(p.userId, p, name);
8138 } else {
8139 // Assign new user id
8140 p.userId = newUserIdLP(p);
8141 }
8142 } else {
8143 p.userId = FIRST_APPLICATION_UID;
8144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 }
8146 if (p.userId < 0) {
8147 reportSettingsProblem(Log.WARN,
8148 "Package " + name + " could not be assigned a valid uid");
8149 return null;
8150 }
8151 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008152 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008153 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008154 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 }
8156 }
8157 return p;
8158 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008159
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008160 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008161 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008162 String codePath = pkg.applicationInfo.sourceDir;
8163 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008164 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008165 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008166 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008167 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008168 p.codePath = new File(codePath);
8169 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008170 }
8171 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008172 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008173 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008174 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008175 p.resourcePath = new File(resourcePath);
8176 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008177 }
8178 // Update version code if needed
8179 if (pkg.mVersionCode != p.versionCode) {
8180 p.versionCode = pkg.mVersionCode;
8181 }
8182 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8183 }
8184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 // Utility method that adds a PackageSetting to mPackages and
8186 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008187 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008188 SharedUserSetting sharedUser) {
8189 mPackages.put(name, p);
8190 if (sharedUser != null) {
8191 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8192 reportSettingsProblem(Log.ERROR,
8193 "Package " + p.name + " was user "
8194 + p.sharedUser + " but is now " + sharedUser
8195 + "; I am not changing its files so it will probably fail!");
8196 p.sharedUser.packages.remove(p);
8197 } else if (p.userId != sharedUser.userId) {
8198 reportSettingsProblem(Log.ERROR,
8199 "Package " + p.name + " was user id " + p.userId
8200 + " but is now user " + sharedUser
8201 + " with id " + sharedUser.userId
8202 + "; I am not changing its files so it will probably fail!");
8203 }
8204
8205 sharedUser.packages.add(p);
8206 p.sharedUser = sharedUser;
8207 p.userId = sharedUser.userId;
8208 }
8209 }
8210
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008211 /*
8212 * Update the shared user setting when a package using
8213 * specifying the shared user id is removed. The gids
8214 * associated with each permission of the deleted package
8215 * are removed from the shared user's gid list only if its
8216 * not in use by other permissions of packages in the
8217 * shared user setting.
8218 */
8219 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008221 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 return;
8223 }
8224 // No sharedUserId
8225 if (deletedPs.sharedUser == null) {
8226 return;
8227 }
8228 SharedUserSetting sus = deletedPs.sharedUser;
8229 // Update permissions
8230 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8231 boolean used = false;
8232 if (!sus.grantedPermissions.contains (eachPerm)) {
8233 continue;
8234 }
8235 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008236 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008237 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008238 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008239 used = true;
8240 break;
8241 }
8242 }
8243 if (!used) {
8244 // can safely delete this permission from list
8245 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 }
8247 }
8248 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008249 int newGids[] = globalGids;
8250 for (String eachPerm : sus.grantedPermissions) {
8251 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008252 if (bp != null) {
8253 newGids = appendInts(newGids, bp.gids);
8254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 }
8256 sus.gids = newGids;
8257 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 private int removePackageLP(String name) {
8260 PackageSetting p = mPackages.get(name);
8261 if (p != null) {
8262 mPackages.remove(name);
8263 if (p.sharedUser != null) {
8264 p.sharedUser.packages.remove(p);
8265 if (p.sharedUser.packages.size() == 0) {
8266 mSharedUsers.remove(p.sharedUser.name);
8267 removeUserIdLP(p.sharedUser.userId);
8268 return p.sharedUser.userId;
8269 }
8270 } else {
8271 removeUserIdLP(p.userId);
8272 return p.userId;
8273 }
8274 }
8275 return -1;
8276 }
8277
8278 private boolean addUserIdLP(int uid, Object obj, Object name) {
8279 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8280 return false;
8281 }
8282
8283 if (uid >= FIRST_APPLICATION_UID) {
8284 int N = mUserIds.size();
8285 final int index = uid - FIRST_APPLICATION_UID;
8286 while (index >= N) {
8287 mUserIds.add(null);
8288 N++;
8289 }
8290 if (mUserIds.get(index) != null) {
8291 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008292 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 + " name=" + name);
8294 return false;
8295 }
8296 mUserIds.set(index, obj);
8297 } else {
8298 if (mOtherUserIds.get(uid) != null) {
8299 reportSettingsProblem(Log.ERROR,
8300 "Adding duplicate shared id: " + uid
8301 + " name=" + name);
8302 return false;
8303 }
8304 mOtherUserIds.put(uid, obj);
8305 }
8306 return true;
8307 }
8308
8309 public Object getUserIdLP(int uid) {
8310 if (uid >= FIRST_APPLICATION_UID) {
8311 int N = mUserIds.size();
8312 final int index = uid - FIRST_APPLICATION_UID;
8313 return index < N ? mUserIds.get(index) : null;
8314 } else {
8315 return mOtherUserIds.get(uid);
8316 }
8317 }
8318
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008319 private Set<String> findPackagesWithFlag(int flag) {
8320 Set<String> ret = new HashSet<String>();
8321 for (PackageSetting ps : mPackages.values()) {
8322 // Has to match atleast all the flag bits set on flag
8323 if ((ps.pkgFlags & flag) == flag) {
8324 ret.add(ps.name);
8325 }
8326 }
8327 return ret;
8328 }
8329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 private void removeUserIdLP(int uid) {
8331 if (uid >= FIRST_APPLICATION_UID) {
8332 int N = mUserIds.size();
8333 final int index = uid - FIRST_APPLICATION_UID;
8334 if (index < N) mUserIds.set(index, null);
8335 } else {
8336 mOtherUserIds.remove(uid);
8337 }
8338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 void writeLP() {
8341 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8342
8343 // Keep the old settings around until we know the new ones have
8344 // been successfully written.
8345 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008346 // Presence of backup settings file indicates that we failed
8347 // to persist settings earlier. So preserve the older
8348 // backup for future reference since the current settings
8349 // might have been corrupted.
8350 if (!mBackupSettingsFilename.exists()) {
8351 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008352 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008353 return;
8354 }
8355 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008356 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008357 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 }
8360
8361 mPastSignatures.clear();
8362
8363 try {
8364 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8365
8366 //XmlSerializer serializer = XmlUtils.serializerInstance();
8367 XmlSerializer serializer = new FastXmlSerializer();
8368 serializer.setOutput(str, "utf-8");
8369 serializer.startDocument(null, true);
8370 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8371
8372 serializer.startTag(null, "packages");
8373
8374 serializer.startTag(null, "permission-trees");
8375 for (BasePermission bp : mPermissionTrees.values()) {
8376 writePermission(serializer, bp);
8377 }
8378 serializer.endTag(null, "permission-trees");
8379
8380 serializer.startTag(null, "permissions");
8381 for (BasePermission bp : mPermissions.values()) {
8382 writePermission(serializer, bp);
8383 }
8384 serializer.endTag(null, "permissions");
8385
8386 for (PackageSetting pkg : mPackages.values()) {
8387 writePackage(serializer, pkg);
8388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8391 writeDisabledSysPackage(serializer, pkg);
8392 }
8393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008394 serializer.startTag(null, "preferred-activities");
8395 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8396 serializer.startTag(null, "item");
8397 pa.writeToXml(serializer);
8398 serializer.endTag(null, "item");
8399 }
8400 serializer.endTag(null, "preferred-activities");
8401
8402 for (SharedUserSetting usr : mSharedUsers.values()) {
8403 serializer.startTag(null, "shared-user");
8404 serializer.attribute(null, "name", usr.name);
8405 serializer.attribute(null, "userId",
8406 Integer.toString(usr.userId));
8407 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8408 serializer.startTag(null, "perms");
8409 for (String name : usr.grantedPermissions) {
8410 serializer.startTag(null, "item");
8411 serializer.attribute(null, "name", name);
8412 serializer.endTag(null, "item");
8413 }
8414 serializer.endTag(null, "perms");
8415 serializer.endTag(null, "shared-user");
8416 }
8417
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008418 if (mPackagesToBeCleaned.size() > 0) {
8419 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8420 serializer.startTag(null, "cleaning-package");
8421 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8422 serializer.endTag(null, "cleaning-package");
8423 }
8424 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008425
8426 if (mRenamedPackages.size() > 0) {
8427 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8428 serializer.startTag(null, "renamed-package");
8429 serializer.attribute(null, "new", e.getKey());
8430 serializer.attribute(null, "old", e.getValue());
8431 serializer.endTag(null, "renamed-package");
8432 }
8433 }
8434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008435 serializer.endTag(null, "packages");
8436
8437 serializer.endDocument();
8438
8439 str.flush();
8440 str.close();
8441
8442 // New settings successfully written, old ones are no longer
8443 // needed.
8444 mBackupSettingsFilename.delete();
8445 FileUtils.setPermissions(mSettingsFilename.toString(),
8446 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8447 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8448 |FileUtils.S_IROTH,
8449 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008450
8451 // Write package list file now, use a JournaledFile.
8452 //
8453 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8454 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8455
8456 str = new FileOutputStream(journal.chooseForWrite());
8457 try {
8458 StringBuilder sb = new StringBuilder();
8459 for (PackageSetting pkg : mPackages.values()) {
8460 ApplicationInfo ai = pkg.pkg.applicationInfo;
8461 String dataPath = ai.dataDir;
8462 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8463
8464 // Avoid any application that has a space in its path
8465 // or that is handled by the system.
8466 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8467 continue;
8468
8469 // we store on each line the following information for now:
8470 //
8471 // pkgName - package name
8472 // userId - application-specific user id
8473 // debugFlag - 0 or 1 if the package is debuggable.
8474 // dataPath - path to package's data path
8475 //
8476 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8477 //
8478 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8479 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8480 // system/core/run-as/run-as.c
8481 //
8482 sb.setLength(0);
8483 sb.append(ai.packageName);
8484 sb.append(" ");
8485 sb.append((int)ai.uid);
8486 sb.append(isDebug ? " 1 " : " 0 ");
8487 sb.append(dataPath);
8488 sb.append("\n");
8489 str.write(sb.toString().getBytes());
8490 }
8491 str.flush();
8492 str.close();
8493 journal.commit();
8494 }
8495 catch (Exception e) {
8496 journal.rollback();
8497 }
8498
8499 FileUtils.setPermissions(mPackageListFilename.toString(),
8500 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8501 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8502 |FileUtils.S_IROTH,
8503 -1, -1);
8504
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008505 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506
8507 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008508 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 -08008509 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008510 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 -08008511 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008512 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008513 if (mSettingsFilename.exists()) {
8514 if (!mSettingsFilename.delete()) {
8515 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8516 }
8517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 //Debug.stopMethodTracing();
8519 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008520
8521 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008522 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 serializer.startTag(null, "updated-package");
8524 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008525 if (pkg.realName != null) {
8526 serializer.attribute(null, "realName", pkg.realName);
8527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 serializer.attribute(null, "codePath", pkg.codePathString);
8529 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008530 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8532 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8533 }
8534 if (pkg.sharedUser == null) {
8535 serializer.attribute(null, "userId",
8536 Integer.toString(pkg.userId));
8537 } else {
8538 serializer.attribute(null, "sharedUserId",
8539 Integer.toString(pkg.userId));
8540 }
8541 serializer.startTag(null, "perms");
8542 if (pkg.sharedUser == null) {
8543 // If this is a shared user, the permissions will
8544 // be written there. We still need to write an
8545 // empty permissions list so permissionsFixed will
8546 // be set.
8547 for (final String name : pkg.grantedPermissions) {
8548 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008549 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 // We only need to write signature or system permissions but this wont
8551 // match the semantics of grantedPermissions. So write all permissions.
8552 serializer.startTag(null, "item");
8553 serializer.attribute(null, "name", name);
8554 serializer.endTag(null, "item");
8555 }
8556 }
8557 }
8558 serializer.endTag(null, "perms");
8559 serializer.endTag(null, "updated-package");
8560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008561
8562 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008563 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 serializer.startTag(null, "package");
8565 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008566 if (pkg.realName != null) {
8567 serializer.attribute(null, "realName", pkg.realName);
8568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569 serializer.attribute(null, "codePath", pkg.codePathString);
8570 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8571 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8572 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008573 serializer.attribute(null, "flags",
8574 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008576 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 if (pkg.sharedUser == null) {
8578 serializer.attribute(null, "userId",
8579 Integer.toString(pkg.userId));
8580 } else {
8581 serializer.attribute(null, "sharedUserId",
8582 Integer.toString(pkg.userId));
8583 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008584 if (pkg.uidError) {
8585 serializer.attribute(null, "uidError", "true");
8586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8588 serializer.attribute(null, "enabled",
8589 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8590 ? "true" : "false");
8591 }
8592 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8593 serializer.attribute(null, "installStatus", "false");
8594 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008595 if (pkg.installerPackageName != null) {
8596 serializer.attribute(null, "installer", pkg.installerPackageName);
8597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008598 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8599 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8600 serializer.startTag(null, "perms");
8601 if (pkg.sharedUser == null) {
8602 // If this is a shared user, the permissions will
8603 // be written there. We still need to write an
8604 // empty permissions list so permissionsFixed will
8605 // be set.
8606 for (final String name : pkg.grantedPermissions) {
8607 serializer.startTag(null, "item");
8608 serializer.attribute(null, "name", name);
8609 serializer.endTag(null, "item");
8610 }
8611 }
8612 serializer.endTag(null, "perms");
8613 }
8614 if (pkg.disabledComponents.size() > 0) {
8615 serializer.startTag(null, "disabled-components");
8616 for (final String name : pkg.disabledComponents) {
8617 serializer.startTag(null, "item");
8618 serializer.attribute(null, "name", name);
8619 serializer.endTag(null, "item");
8620 }
8621 serializer.endTag(null, "disabled-components");
8622 }
8623 if (pkg.enabledComponents.size() > 0) {
8624 serializer.startTag(null, "enabled-components");
8625 for (final String name : pkg.enabledComponents) {
8626 serializer.startTag(null, "item");
8627 serializer.attribute(null, "name", name);
8628 serializer.endTag(null, "item");
8629 }
8630 serializer.endTag(null, "enabled-components");
8631 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633 serializer.endTag(null, "package");
8634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 void writePermission(XmlSerializer serializer, BasePermission bp)
8637 throws XmlPullParserException, java.io.IOException {
8638 if (bp.type != BasePermission.TYPE_BUILTIN
8639 && bp.sourcePackage != null) {
8640 serializer.startTag(null, "item");
8641 serializer.attribute(null, "name", bp.name);
8642 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008643 if (bp.protectionLevel !=
8644 PermissionInfo.PROTECTION_NORMAL) {
8645 serializer.attribute(null, "protection",
8646 Integer.toString(bp.protectionLevel));
8647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008648 if (DEBUG_SETTINGS) Log.v(TAG,
8649 "Writing perm: name=" + bp.name + " type=" + bp.type);
8650 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8651 PermissionInfo pi = bp.perm != null ? bp.perm.info
8652 : bp.pendingInfo;
8653 if (pi != null) {
8654 serializer.attribute(null, "type", "dynamic");
8655 if (pi.icon != 0) {
8656 serializer.attribute(null, "icon",
8657 Integer.toString(pi.icon));
8658 }
8659 if (pi.nonLocalizedLabel != null) {
8660 serializer.attribute(null, "label",
8661 pi.nonLocalizedLabel.toString());
8662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 }
8664 }
8665 serializer.endTag(null, "item");
8666 }
8667 }
8668
8669 String getReadMessagesLP() {
8670 return mReadMessages.toString();
8671 }
8672
Oscar Montemayora8529f62009-11-18 10:14:20 -08008673 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008674 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8675 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008676 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 while(its.hasNext()) {
8678 String key = its.next();
8679 PackageSetting ps = mPackages.get(key);
8680 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008681 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008682 }
8683 }
8684 return ret;
8685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 boolean readLP() {
8688 FileInputStream str = null;
8689 if (mBackupSettingsFilename.exists()) {
8690 try {
8691 str = new FileInputStream(mBackupSettingsFilename);
8692 mReadMessages.append("Reading from backup settings file\n");
8693 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008694 if (mSettingsFilename.exists()) {
8695 // If both the backup and settings file exist, we
8696 // ignore the settings since it might have been
8697 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008698 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008699 mSettingsFilename.delete();
8700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 } catch (java.io.IOException e) {
8702 // We'll try for the normal settings file.
8703 }
8704 }
8705
8706 mPastSignatures.clear();
8707
8708 try {
8709 if (str == null) {
8710 if (!mSettingsFilename.exists()) {
8711 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008712 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 return false;
8714 }
8715 str = new FileInputStream(mSettingsFilename);
8716 }
8717 XmlPullParser parser = Xml.newPullParser();
8718 parser.setInput(str, null);
8719
8720 int type;
8721 while ((type=parser.next()) != XmlPullParser.START_TAG
8722 && type != XmlPullParser.END_DOCUMENT) {
8723 ;
8724 }
8725
8726 if (type != XmlPullParser.START_TAG) {
8727 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008728 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 return false;
8730 }
8731
8732 int outerDepth = parser.getDepth();
8733 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8734 && (type != XmlPullParser.END_TAG
8735 || parser.getDepth() > outerDepth)) {
8736 if (type == XmlPullParser.END_TAG
8737 || type == XmlPullParser.TEXT) {
8738 continue;
8739 }
8740
8741 String tagName = parser.getName();
8742 if (tagName.equals("package")) {
8743 readPackageLP(parser);
8744 } else if (tagName.equals("permissions")) {
8745 readPermissionsLP(mPermissions, parser);
8746 } else if (tagName.equals("permission-trees")) {
8747 readPermissionsLP(mPermissionTrees, parser);
8748 } else if (tagName.equals("shared-user")) {
8749 readSharedUserLP(parser);
8750 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008751 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 } else if (tagName.equals("preferred-activities")) {
8753 readPreferredActivitiesLP(parser);
8754 } else if(tagName.equals("updated-package")) {
8755 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008756 } else if (tagName.equals("cleaning-package")) {
8757 String name = parser.getAttributeValue(null, "name");
8758 if (name != null) {
8759 mPackagesToBeCleaned.add(name);
8760 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008761 } else if (tagName.equals("renamed-package")) {
8762 String nname = parser.getAttributeValue(null, "new");
8763 String oname = parser.getAttributeValue(null, "old");
8764 if (nname != null && oname != null) {
8765 mRenamedPackages.put(nname, oname);
8766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008767 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008768 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 + parser.getName());
8770 XmlUtils.skipCurrentTag(parser);
8771 }
8772 }
8773
8774 str.close();
8775
8776 } catch(XmlPullParserException e) {
8777 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008778 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779
8780 } catch(java.io.IOException e) {
8781 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008782 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783
8784 }
8785
8786 int N = mPendingPackages.size();
8787 for (int i=0; i<N; i++) {
8788 final PendingPackage pp = mPendingPackages.get(i);
8789 Object idObj = getUserIdLP(pp.sharedId);
8790 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008791 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008793 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008794 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008795 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 + pp.name);
8797 continue;
8798 }
8799 p.copyFrom(pp);
8800 } else if (idObj != null) {
8801 String msg = "Bad package setting: package " + pp.name
8802 + " has shared uid " + pp.sharedId
8803 + " that is not a shared uid\n";
8804 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008805 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 } else {
8807 String msg = "Bad package setting: package " + pp.name
8808 + " has shared uid " + pp.sharedId
8809 + " that is not defined\n";
8810 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008811 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008812 }
8813 }
8814 mPendingPackages.clear();
8815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 mReadMessages.append("Read completed successfully: "
8817 + mPackages.size() + " packages, "
8818 + mSharedUsers.size() + " shared uids\n");
8819
8820 return true;
8821 }
8822
8823 private int readInt(XmlPullParser parser, String ns, String name,
8824 int defValue) {
8825 String v = parser.getAttributeValue(ns, name);
8826 try {
8827 if (v == null) {
8828 return defValue;
8829 }
8830 return Integer.parseInt(v);
8831 } catch (NumberFormatException e) {
8832 reportSettingsProblem(Log.WARN,
8833 "Error in package manager settings: attribute " +
8834 name + " has bad integer value " + v + " at "
8835 + parser.getPositionDescription());
8836 }
8837 return defValue;
8838 }
8839
8840 private void readPermissionsLP(HashMap<String, BasePermission> out,
8841 XmlPullParser parser)
8842 throws IOException, XmlPullParserException {
8843 int outerDepth = parser.getDepth();
8844 int type;
8845 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8846 && (type != XmlPullParser.END_TAG
8847 || parser.getDepth() > outerDepth)) {
8848 if (type == XmlPullParser.END_TAG
8849 || type == XmlPullParser.TEXT) {
8850 continue;
8851 }
8852
8853 String tagName = parser.getName();
8854 if (tagName.equals("item")) {
8855 String name = parser.getAttributeValue(null, "name");
8856 String sourcePackage = parser.getAttributeValue(null, "package");
8857 String ptype = parser.getAttributeValue(null, "type");
8858 if (name != null && sourcePackage != null) {
8859 boolean dynamic = "dynamic".equals(ptype);
8860 BasePermission bp = new BasePermission(name, sourcePackage,
8861 dynamic
8862 ? BasePermission.TYPE_DYNAMIC
8863 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008864 bp.protectionLevel = readInt(parser, null, "protection",
8865 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 if (dynamic) {
8867 PermissionInfo pi = new PermissionInfo();
8868 pi.packageName = sourcePackage.intern();
8869 pi.name = name.intern();
8870 pi.icon = readInt(parser, null, "icon", 0);
8871 pi.nonLocalizedLabel = parser.getAttributeValue(
8872 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008873 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874 bp.pendingInfo = pi;
8875 }
8876 out.put(bp.name, bp);
8877 } else {
8878 reportSettingsProblem(Log.WARN,
8879 "Error in package manager settings: permissions has"
8880 + " no name at " + parser.getPositionDescription());
8881 }
8882 } else {
8883 reportSettingsProblem(Log.WARN,
8884 "Unknown element reading permissions: "
8885 + parser.getName() + " at "
8886 + parser.getPositionDescription());
8887 }
8888 XmlUtils.skipCurrentTag(parser);
8889 }
8890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008893 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008895 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008896 String codePathStr = parser.getAttributeValue(null, "codePath");
8897 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008898 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 resourcePathStr = codePathStr;
8900 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008901 String version = parser.getAttributeValue(null, "version");
8902 int versionCode = 0;
8903 if (version != null) {
8904 try {
8905 versionCode = Integer.parseInt(version);
8906 } catch (NumberFormatException e) {
8907 }
8908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 int pkgFlags = 0;
8911 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008912 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008913 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008914 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 String timeStampStr = parser.getAttributeValue(null, "ts");
8916 if (timeStampStr != null) {
8917 try {
8918 long timeStamp = Long.parseLong(timeStampStr);
8919 ps.setTimeStamp(timeStamp, timeStampStr);
8920 } catch (NumberFormatException e) {
8921 }
8922 }
8923 String idStr = parser.getAttributeValue(null, "userId");
8924 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8925 if(ps.userId <= 0) {
8926 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8927 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8928 }
8929 int outerDepth = parser.getDepth();
8930 int type;
8931 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8932 && (type != XmlPullParser.END_TAG
8933 || parser.getDepth() > outerDepth)) {
8934 if (type == XmlPullParser.END_TAG
8935 || type == XmlPullParser.TEXT) {
8936 continue;
8937 }
8938
8939 String tagName = parser.getName();
8940 if (tagName.equals("perms")) {
8941 readGrantedPermissionsLP(parser,
8942 ps.grantedPermissions);
8943 } else {
8944 reportSettingsProblem(Log.WARN,
8945 "Unknown element under <updated-package>: "
8946 + parser.getName());
8947 XmlUtils.skipCurrentTag(parser);
8948 }
8949 }
8950 mDisabledSysPackages.put(name, ps);
8951 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 private void readPackageLP(XmlPullParser parser)
8954 throws XmlPullParserException, IOException {
8955 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008956 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 String idStr = null;
8958 String sharedIdStr = null;
8959 String codePathStr = null;
8960 String resourcePathStr = null;
8961 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008962 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008963 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 int pkgFlags = 0;
8965 String timeStampStr;
8966 long timeStamp = 0;
8967 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008968 String version = null;
8969 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 try {
8971 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008972 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008974 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8976 codePathStr = parser.getAttributeValue(null, "codePath");
8977 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008978 version = parser.getAttributeValue(null, "version");
8979 if (version != null) {
8980 try {
8981 versionCode = Integer.parseInt(version);
8982 } catch (NumberFormatException e) {
8983 }
8984 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008985 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008986
8987 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008989 try {
8990 pkgFlags = Integer.parseInt(systemStr);
8991 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008992 }
8993 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008994 // For backward compatibility
8995 systemStr = parser.getAttributeValue(null, "system");
8996 if (systemStr != null) {
8997 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8998 } else {
8999 // Old settings that don't specify system... just treat
9000 // them as system, good enough.
9001 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 }
9004 timeStampStr = parser.getAttributeValue(null, "ts");
9005 if (timeStampStr != null) {
9006 try {
9007 timeStamp = Long.parseLong(timeStampStr);
9008 } catch (NumberFormatException e) {
9009 }
9010 }
9011 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9012 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9013 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9014 if (resourcePathStr == null) {
9015 resourcePathStr = codePathStr;
9016 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009017 if (realName != null) {
9018 realName = realName.intern();
9019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 if (name == null) {
9021 reportSettingsProblem(Log.WARN,
9022 "Error in package manager settings: <package> has no name at "
9023 + parser.getPositionDescription());
9024 } else if (codePathStr == null) {
9025 reportSettingsProblem(Log.WARN,
9026 "Error in package manager settings: <package> has no codePath at "
9027 + parser.getPositionDescription());
9028 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009029 packageSetting = addPackageLP(name.intern(), realName,
9030 new File(codePathStr), new File(resourcePathStr),
9031 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9033 + ": userId=" + userId + " pkg=" + packageSetting);
9034 if (packageSetting == null) {
9035 reportSettingsProblem(Log.ERROR,
9036 "Failure adding uid " + userId
9037 + " while parsing settings at "
9038 + parser.getPositionDescription());
9039 } else {
9040 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9041 }
9042 } else if (sharedIdStr != null) {
9043 userId = sharedIdStr != null
9044 ? Integer.parseInt(sharedIdStr) : 0;
9045 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009046 packageSetting = new PendingPackage(name.intern(), realName,
9047 new File(codePathStr), new File(resourcePathStr),
9048 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9050 mPendingPackages.add((PendingPackage) packageSetting);
9051 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9052 + ": sharedUserId=" + userId + " pkg="
9053 + packageSetting);
9054 } else {
9055 reportSettingsProblem(Log.WARN,
9056 "Error in package manager settings: package "
9057 + name + " has bad sharedId " + sharedIdStr
9058 + " at " + parser.getPositionDescription());
9059 }
9060 } else {
9061 reportSettingsProblem(Log.WARN,
9062 "Error in package manager settings: package "
9063 + name + " has bad userId " + idStr + " at "
9064 + parser.getPositionDescription());
9065 }
9066 } catch (NumberFormatException e) {
9067 reportSettingsProblem(Log.WARN,
9068 "Error in package manager settings: package "
9069 + name + " has bad userId " + idStr + " at "
9070 + parser.getPositionDescription());
9071 }
9072 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009073 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009074 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 final String enabledStr = parser.getAttributeValue(null, "enabled");
9076 if (enabledStr != null) {
9077 if (enabledStr.equalsIgnoreCase("true")) {
9078 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9079 } else if (enabledStr.equalsIgnoreCase("false")) {
9080 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9081 } else if (enabledStr.equalsIgnoreCase("default")) {
9082 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9083 } else {
9084 reportSettingsProblem(Log.WARN,
9085 "Error in package manager settings: package "
9086 + name + " has bad enabled value: " + idStr
9087 + " at " + parser.getPositionDescription());
9088 }
9089 } else {
9090 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9091 }
9092 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9093 if (installStatusStr != null) {
9094 if (installStatusStr.equalsIgnoreCase("false")) {
9095 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9096 } else {
9097 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9098 }
9099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 int outerDepth = parser.getDepth();
9102 int type;
9103 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9104 && (type != XmlPullParser.END_TAG
9105 || parser.getDepth() > outerDepth)) {
9106 if (type == XmlPullParser.END_TAG
9107 || type == XmlPullParser.TEXT) {
9108 continue;
9109 }
9110
9111 String tagName = parser.getName();
9112 if (tagName.equals("disabled-components")) {
9113 readDisabledComponentsLP(packageSetting, parser);
9114 } else if (tagName.equals("enabled-components")) {
9115 readEnabledComponentsLP(packageSetting, parser);
9116 } else if (tagName.equals("sigs")) {
9117 packageSetting.signatures.readXml(parser, mPastSignatures);
9118 } else if (tagName.equals("perms")) {
9119 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009120 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 packageSetting.permissionsFixed = true;
9122 } else {
9123 reportSettingsProblem(Log.WARN,
9124 "Unknown element under <package>: "
9125 + parser.getName());
9126 XmlUtils.skipCurrentTag(parser);
9127 }
9128 }
9129 } else {
9130 XmlUtils.skipCurrentTag(parser);
9131 }
9132 }
9133
9134 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9135 XmlPullParser parser)
9136 throws IOException, XmlPullParserException {
9137 int outerDepth = parser.getDepth();
9138 int type;
9139 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9140 && (type != XmlPullParser.END_TAG
9141 || parser.getDepth() > outerDepth)) {
9142 if (type == XmlPullParser.END_TAG
9143 || type == XmlPullParser.TEXT) {
9144 continue;
9145 }
9146
9147 String tagName = parser.getName();
9148 if (tagName.equals("item")) {
9149 String name = parser.getAttributeValue(null, "name");
9150 if (name != null) {
9151 packageSetting.disabledComponents.add(name.intern());
9152 } else {
9153 reportSettingsProblem(Log.WARN,
9154 "Error in package manager settings: <disabled-components> has"
9155 + " no name at " + parser.getPositionDescription());
9156 }
9157 } else {
9158 reportSettingsProblem(Log.WARN,
9159 "Unknown element under <disabled-components>: "
9160 + parser.getName());
9161 }
9162 XmlUtils.skipCurrentTag(parser);
9163 }
9164 }
9165
9166 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9167 XmlPullParser parser)
9168 throws IOException, XmlPullParserException {
9169 int outerDepth = parser.getDepth();
9170 int type;
9171 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9172 && (type != XmlPullParser.END_TAG
9173 || parser.getDepth() > outerDepth)) {
9174 if (type == XmlPullParser.END_TAG
9175 || type == XmlPullParser.TEXT) {
9176 continue;
9177 }
9178
9179 String tagName = parser.getName();
9180 if (tagName.equals("item")) {
9181 String name = parser.getAttributeValue(null, "name");
9182 if (name != null) {
9183 packageSetting.enabledComponents.add(name.intern());
9184 } else {
9185 reportSettingsProblem(Log.WARN,
9186 "Error in package manager settings: <enabled-components> has"
9187 + " no name at " + parser.getPositionDescription());
9188 }
9189 } else {
9190 reportSettingsProblem(Log.WARN,
9191 "Unknown element under <enabled-components>: "
9192 + parser.getName());
9193 }
9194 XmlUtils.skipCurrentTag(parser);
9195 }
9196 }
9197
9198 private void readSharedUserLP(XmlPullParser parser)
9199 throws XmlPullParserException, IOException {
9200 String name = null;
9201 String idStr = null;
9202 int pkgFlags = 0;
9203 SharedUserSetting su = null;
9204 try {
9205 name = parser.getAttributeValue(null, "name");
9206 idStr = parser.getAttributeValue(null, "userId");
9207 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9208 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9209 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9210 }
9211 if (name == null) {
9212 reportSettingsProblem(Log.WARN,
9213 "Error in package manager settings: <shared-user> has no name at "
9214 + parser.getPositionDescription());
9215 } else if (userId == 0) {
9216 reportSettingsProblem(Log.WARN,
9217 "Error in package manager settings: shared-user "
9218 + name + " has bad userId " + idStr + " at "
9219 + parser.getPositionDescription());
9220 } else {
9221 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9222 reportSettingsProblem(Log.ERROR,
9223 "Occurred while parsing settings at "
9224 + parser.getPositionDescription());
9225 }
9226 }
9227 } catch (NumberFormatException e) {
9228 reportSettingsProblem(Log.WARN,
9229 "Error in package manager settings: package "
9230 + name + " has bad userId " + idStr + " at "
9231 + parser.getPositionDescription());
9232 };
9233
9234 if (su != null) {
9235 int outerDepth = parser.getDepth();
9236 int type;
9237 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9238 && (type != XmlPullParser.END_TAG
9239 || parser.getDepth() > outerDepth)) {
9240 if (type == XmlPullParser.END_TAG
9241 || type == XmlPullParser.TEXT) {
9242 continue;
9243 }
9244
9245 String tagName = parser.getName();
9246 if (tagName.equals("sigs")) {
9247 su.signatures.readXml(parser, mPastSignatures);
9248 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009249 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009250 } else {
9251 reportSettingsProblem(Log.WARN,
9252 "Unknown element under <shared-user>: "
9253 + parser.getName());
9254 XmlUtils.skipCurrentTag(parser);
9255 }
9256 }
9257
9258 } else {
9259 XmlUtils.skipCurrentTag(parser);
9260 }
9261 }
9262
9263 private void readGrantedPermissionsLP(XmlPullParser parser,
9264 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9265 int outerDepth = parser.getDepth();
9266 int type;
9267 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9268 && (type != XmlPullParser.END_TAG
9269 || parser.getDepth() > outerDepth)) {
9270 if (type == XmlPullParser.END_TAG
9271 || type == XmlPullParser.TEXT) {
9272 continue;
9273 }
9274
9275 String tagName = parser.getName();
9276 if (tagName.equals("item")) {
9277 String name = parser.getAttributeValue(null, "name");
9278 if (name != null) {
9279 outPerms.add(name.intern());
9280 } else {
9281 reportSettingsProblem(Log.WARN,
9282 "Error in package manager settings: <perms> has"
9283 + " no name at " + parser.getPositionDescription());
9284 }
9285 } else {
9286 reportSettingsProblem(Log.WARN,
9287 "Unknown element under <perms>: "
9288 + parser.getName());
9289 }
9290 XmlUtils.skipCurrentTag(parser);
9291 }
9292 }
9293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009294 private void readPreferredActivitiesLP(XmlPullParser parser)
9295 throws XmlPullParserException, IOException {
9296 int outerDepth = parser.getDepth();
9297 int type;
9298 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9299 && (type != XmlPullParser.END_TAG
9300 || parser.getDepth() > outerDepth)) {
9301 if (type == XmlPullParser.END_TAG
9302 || type == XmlPullParser.TEXT) {
9303 continue;
9304 }
9305
9306 String tagName = parser.getName();
9307 if (tagName.equals("item")) {
9308 PreferredActivity pa = new PreferredActivity(parser);
9309 if (pa.mParseError == null) {
9310 mPreferredActivities.addFilter(pa);
9311 } else {
9312 reportSettingsProblem(Log.WARN,
9313 "Error in package manager settings: <preferred-activity> "
9314 + pa.mParseError + " at "
9315 + parser.getPositionDescription());
9316 }
9317 } else {
9318 reportSettingsProblem(Log.WARN,
9319 "Unknown element under <preferred-activities>: "
9320 + parser.getName());
9321 XmlUtils.skipCurrentTag(parser);
9322 }
9323 }
9324 }
9325
9326 // Returns -1 if we could not find an available UserId to assign
9327 private int newUserIdLP(Object obj) {
9328 // Let's be stupidly inefficient for now...
9329 final int N = mUserIds.size();
9330 for (int i=0; i<N; i++) {
9331 if (mUserIds.get(i) == null) {
9332 mUserIds.set(i, obj);
9333 return FIRST_APPLICATION_UID + i;
9334 }
9335 }
9336
9337 // None left?
9338 if (N >= MAX_APPLICATION_UIDS) {
9339 return -1;
9340 }
9341
9342 mUserIds.add(obj);
9343 return FIRST_APPLICATION_UID + N;
9344 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009346 public PackageSetting getDisabledSystemPkg(String name) {
9347 synchronized(mPackages) {
9348 PackageSetting ps = mDisabledSysPackages.get(name);
9349 return ps;
9350 }
9351 }
9352
9353 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
9354 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9355 if (Config.LOGV) {
9356 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9357 + " componentName = " + componentInfo.name);
9358 Log.v(TAG, "enabledComponents: "
9359 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9360 Log.v(TAG, "disabledComponents: "
9361 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9362 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009363 if (packageSettings == null) {
9364 if (false) {
9365 Log.w(TAG, "WAITING FOR DEBUGGER");
9366 Debug.waitForDebugger();
9367 Log.i(TAG, "We will crash!");
9368 }
9369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009370 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
9371 || ((componentInfo.enabled
9372 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
9373 || (componentInfo.applicationInfo.enabled
9374 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
9375 && !packageSettings.disabledComponents.contains(componentInfo.name))
9376 || packageSettings.enabledComponents.contains(componentInfo.name));
9377 }
9378 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009379
9380 // ------- apps on sdcard specific code -------
9381 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009382 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009383 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009384 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009385 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009386
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009387 private String getEncryptKey() {
9388 try {
9389 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9390 if (sdEncKey == null) {
9391 sdEncKey = SystemKeyStore.getInstance().
9392 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9393 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009394 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009395 return null;
9396 }
9397 }
9398 return sdEncKey;
9399 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009400 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009401 return null;
9402 }
9403 }
9404
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009405 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009406 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009407 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009408 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009409 if (list != null) {
9410 int idx = 0;
9411 int idList[] = new int[MAX_CONTAINERS];
9412 boolean neverFound = true;
9413 for (String name : list) {
9414 // Ignore null entries
9415 if (name == null) {
9416 continue;
9417 }
9418 int sidx = name.indexOf(prefix);
9419 if (sidx == -1) {
9420 // Not a temp file. just ignore
9421 continue;
9422 }
9423 String subStr = name.substring(sidx + prefix.length());
9424 idList[idx] = -1;
9425 if (subStr != null) {
9426 try {
9427 int cid = Integer.parseInt(subStr);
9428 idList[idx++] = cid;
9429 neverFound = false;
9430 } catch (NumberFormatException e) {
9431 }
9432 }
9433 }
9434 if (!neverFound) {
9435 // Sort idList
9436 Arrays.sort(idList);
9437 for (int j = 1; j <= idList.length; j++) {
9438 if (idList[j-1] != j) {
9439 tmpIdx = j;
9440 break;
9441 }
9442 }
9443 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009444 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009445 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009446 }
9447
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009448 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009449 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009450 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009451 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9452 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9453 throw new SecurityException("Media status can only be updated by the system");
9454 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009455 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009456 Log.i(TAG, "Updating external media status from " +
9457 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9458 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009459 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9460 mediaStatus+", mMediaMounted=" + mMediaMounted);
9461 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009462 if (reportStatus) {
9463 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9464 }
9465 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009466 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009467 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009468 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009469 // Queue up an async operation since the package installation may take a little while.
9470 mHandler.post(new Runnable() {
9471 public void run() {
9472 mHandler.removeCallbacks(this);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009473 try {
9474 updateExternalMediaStatusInner(mediaStatus);
9475 } finally {
9476 if (reportStatus) {
9477 mHandler.sendEmptyMessage(UPDATED_MEDIA_STATUS);
9478 }
9479 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009480 }
9481 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009482 }
9483
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009484 private void updateExternalMediaStatusInner(boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009485 // If we are up here that means there are packages to be
9486 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009487 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009488 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009489 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009490 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009491 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009492
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009493 int uidList[] = new int[list.length];
9494 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009495 HashSet<String> removeCids = new HashSet<String>();
9496 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009497 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009498 for (String cid : list) {
9499 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009500 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9501 boolean failed = true;
9502 try {
9503 String pkgName = args.getPackageName();
9504 if (pkgName == null) {
9505 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009506 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009507 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9508 PackageSetting ps = mSettings.mPackages.get(pkgName);
9509 if (ps != null && ps.codePathString != null &&
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009510 (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9512 " corresponds to pkg : " + pkgName +
9513 " at code path: " + ps.codePathString);
9514 // We do have a valid package installed on sdcard
9515 processCids.put(args, ps.codePathString);
9516 failed = false;
9517 int uid = ps.userId;
9518 if (uid != -1) {
9519 uidList[num++] = uid;
9520 }
9521 }
9522 } finally {
9523 if (failed) {
9524 // Stale container on sdcard. Just delete
9525 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9526 removeCids.add(cid);
9527 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009528 }
9529 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009530 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009531 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009532 int uidArr[] = null;
9533 if (num > 0) {
9534 // Sort uid list
9535 Arrays.sort(uidList, 0, num);
9536 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009537 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009538 uidArr[0] = uidList[0];
9539 int di = 0;
9540 for (int i = 1; i < num; i++) {
9541 if (uidList[i-1] != uidList[i]) {
9542 uidArr[di++] = uidList[i];
9543 }
9544 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 // Process packages with valid entries.
9547 if (mediaStatus) {
9548 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009549 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009550 startCleaningPackages();
9551 } else {
9552 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009553 unloadMediaPackages(processCids, uidArr);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009555 }
9556
9557 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9558 ArrayList<String> pkgList, int uidArr[]) {
9559 int size = pkgList.size();
9560 if (size > 0) {
9561 // Send broadcasts here
9562 Bundle extras = new Bundle();
9563 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9564 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009565 if (uidArr != null) {
9566 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9567 }
9568 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9569 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009570 sendPackageBroadcast(action, null, extras);
9571 }
9572 }
9573
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009574 /*
9575 * Look at potentially valid container ids from processCids
9576 * If package information doesn't match the one on record
9577 * or package scanning fails, the cid is added to list of
9578 * removeCids and cleaned up. Since cleaning up containers
9579 * involves destroying them, we do not want any parse
9580 * references to such stale containers. So force gc's
9581 * to avoid unnecessary crashes.
9582 */
9583 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009584 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009585 ArrayList<String> pkgList = new ArrayList<String>();
9586 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009588 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009589 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009590 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9591 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009592 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009593 try {
9594 // Make sure there are no container errors first.
9595 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9596 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009597 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 " when installing from sdcard");
9599 continue;
9600 }
9601 // Check code path here.
9602 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009603 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009604 " does not match one in settings " + codePath);
9605 continue;
9606 }
9607 // Parse package
9608 int parseFlags = PackageParser.PARSE_CHATTY |
9609 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9610 PackageParser pp = new PackageParser(codePath);
9611 pp.setSeparateProcesses(mSeparateProcesses);
9612 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9613 codePath, mMetrics, parseFlags);
9614 pp = null;
9615 doGc = true;
9616 // Check for parse errors
9617 if (pkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009618 Slog.e(TAG, "Parse error when installing install pkg : "
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009619 + args.cid + " from " + args.cachePath);
9620 continue;
9621 }
9622 setApplicationInfoPaths(pkg, codePath, codePath);
9623 synchronized (mInstallLock) {
9624 // Scan the package
9625 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9626 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009627 retCode = PackageManager.INSTALL_SUCCEEDED;
9628 pkgList.add(pkg.packageName);
9629 // Post process args
9630 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9631 }
9632 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009633 Slog.i(TAG, "Failed to install pkg: " +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009634 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009635 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009636 }
9637
9638 } finally {
9639 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9640 // Don't destroy container here. Wait till gc clears things up.
9641 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009642 }
9643 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009644 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009645 synchronized (mPackages) {
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009646 // Make sure group IDs have been assigned, and any permission
9647 // changes in other apps are accounted for
9648 updatePermissionsLP(null, null, true, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009649 // Persist settings
9650 mSettings.writeLP();
9651 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009652 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009653 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9655 }
9656 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009657 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009658 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009659 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009660 if (removeCids != null) {
9661 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009662 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009663 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009664 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009665 }
9666
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009667 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009668 int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009669 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009670 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009671 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009672 Set<SdInstallArgs> keys = processCids.keySet();
9673 for (SdInstallArgs args : keys) {
9674 String cid = args.cid;
9675 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009676 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009677 // Delete package internally
9678 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9679 synchronized (mInstallLock) {
9680 boolean res = deletePackageLI(pkgName, false,
9681 PackageManager.DONT_DELETE_DATA, outInfo);
9682 if (res) {
9683 pkgList.add(pkgName);
9684 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009685 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009686 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009687 }
9688 }
9689 }
9690 // Send broadcasts
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009691 if (pkgList.size() > 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009692 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009693 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009694 // Force gc
9695 Runtime.getRuntime().gc();
9696 // Just unmount all valid containers.
9697 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009698 synchronized (mInstallLock) {
9699 args.doPostDeleteLI(false);
9700 }
9701 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009702 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009703
9704 public void movePackage(final String packageName,
9705 final IPackageMoveObserver observer, final int flags) {
9706 if (packageName == null) {
9707 return;
9708 }
9709 mContext.enforceCallingOrSelfPermission(
9710 android.Manifest.permission.MOVE_PACKAGE, null);
9711 int returnCode = PackageManager.MOVE_SUCCEEDED;
9712 int currFlags = 0;
9713 int newFlags = 0;
9714 synchronized (mPackages) {
9715 PackageParser.Package pkg = mPackages.get(packageName);
9716 if (pkg == null) {
9717 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9718 }
9719 // Disable moving fwd locked apps and system packages
9720 if (pkg.applicationInfo != null &&
9721 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009722 Slog.w(TAG, "Cannot move system application");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009723 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9724 } else if (pkg.applicationInfo != null &&
9725 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009726 Slog.w(TAG, "Cannot move forward locked app.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009727 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9728 } else {
9729 // Find install location first
9730 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9731 (flags & PackageManager.MOVE_INTERNAL) != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009732 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009733 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9734 } else {
9735 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9736 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08009737 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009738 PackageManager.INSTALL_EXTERNAL : 0;
9739 if (newFlags == currFlags) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009740 Slog.w(TAG, "No move required. Trying to move to same location");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009741 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9742 }
9743 }
9744 }
9745 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9746 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9747 } else {
9748 Message msg = mHandler.obtainMessage(INIT_COPY);
9749 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9750 pkg.applicationInfo.publicSourceDir);
9751 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9752 packageName);
9753 msg.obj = mp;
9754 mHandler.sendMessage(msg);
9755 }
9756 }
9757 }
9758
9759 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9760 // Queue up an async operation since the package deletion may take a little while.
9761 mHandler.post(new Runnable() {
9762 public void run() {
9763 mHandler.removeCallbacks(this);
9764 int returnCode = currentStatus;
9765 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9766 if (moveSucceeded) {
9767 int uid = -1;
9768 synchronized (mPackages) {
9769 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9770 }
9771 ArrayList<String> pkgList = new ArrayList<String>();
9772 pkgList.add(mp.packageName);
9773 int uidArr[] = new int[] { uid };
9774 // Send resources unavailable broadcast
9775 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9776
9777 // Update package code and resource paths
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009778 synchronized (mInstallLock) {
9779 synchronized (mPackages) {
9780 PackageParser.Package pkg = mPackages.get(mp.packageName);
9781 if (pkg != null) {
9782 String oldCodePath = pkg.mPath;
9783 String newCodePath = mp.targetArgs.getCodePath();
9784 String newResPath = mp.targetArgs.getResourcePath();
9785 pkg.mPath = newCodePath;
9786 // Move dex files around
9787 if (moveDexFilesLI(pkg)
9788 != PackageManager.INSTALL_SUCCEEDED) {
9789 // Moving of dex files failed. Set
9790 // error code and abort move.
9791 pkg.mPath = pkg.mScanPath;
9792 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9793 moveSucceeded = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009794 } else {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009795 pkg.mScanPath = newCodePath;
9796 pkg.applicationInfo.sourceDir = newCodePath;
9797 pkg.applicationInfo.publicSourceDir = newResPath;
9798 PackageSetting ps = (PackageSetting) pkg.mExtras;
9799 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9800 ps.codePathString = ps.codePath.getPath();
9801 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9802 ps.resourcePathString = ps.resourcePath.getPath();
9803 // Set the application info flag correctly.
9804 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9805 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9806 } else {
9807 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9808 }
9809 ps.setFlags(pkg.applicationInfo.flags);
9810 mAppDirs.remove(oldCodePath);
9811 mAppDirs.put(newCodePath, pkg);
9812 // Persist settings
9813 mSettings.writeLP();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009814 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009815 }
9816 }
9817 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009818 // Send resources available broadcast
9819 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009820 }
9821 if (!moveSucceeded){
9822 // Clean up failed installation
9823 if (mp.targetArgs != null) {
9824 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009825 returnCode);
9826 }
9827 } else {
9828 // Force a gc to clear things up.
9829 Runtime.getRuntime().gc();
9830 // Delete older code
9831 synchronized (mInstallLock) {
9832 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009833 }
9834 }
9835 IPackageMoveObserver observer = mp.observer;
9836 if (observer != null) {
9837 try {
9838 observer.packageMoved(mp.packageName, returnCode);
9839 } catch (RemoteException e) {
9840 Log.i(TAG, "Observer no longer exists.");
9841 }
9842 }
9843 }
9844 });
9845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009846}