blob: 664f02889229d60fbe9afa9f8585147f50c12227 [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;
23import com.android.internal.util.XmlUtils;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080024import com.android.server.JournaledFile;
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.DevicePolicyManager;
33import android.app.admin.IDevicePolicyManager;
Christopher Tate1bb69062010-02-19 17:02:12 -080034import android.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
54import 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;
San Mehatb1043402010-02-05 08:26:50 -080081import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080087import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.util.*;
89import android.view.Display;
90import android.view.WindowManager;
91
92import java.io.File;
93import java.io.FileDescriptor;
94import java.io.FileInputStream;
95import java.io.FileNotFoundException;
96import java.io.FileOutputStream;
97import java.io.FileReader;
98import java.io.FilenameFilter;
99import java.io.IOException;
100import java.io.InputStream;
101import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800102import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800103import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.util.ArrayList;
105import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700106import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Collections;
108import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800109import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Enumeration;
111import java.util.HashMap;
112import java.util.HashSet;
113import java.util.Iterator;
114import java.util.List;
115import java.util.Map;
116import java.util.Set;
117import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800118import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import java.util.zip.ZipFile;
120import java.util.zip.ZipOutputStream;
121
122class PackageManagerService extends IPackageManager.Stub {
123 private static final String TAG = "PackageManager";
124 private static final boolean DEBUG_SETTINGS = false;
125 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800126 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800127 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
129 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
130 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400131 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final int FIRST_APPLICATION_UID =
133 Process.FIRST_APPLICATION_UID;
134 private static final int MAX_APPLICATION_UIDS = 1000;
135
136 private static final boolean SHOW_INFO = false;
137
138 private static final boolean GET_CERTIFICATES = true;
139
Oscar Montemayora8529f62009-11-18 10:14:20 -0800140 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 private static final int REMOVE_EVENTS =
143 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
144 private static final int ADD_EVENTS =
145 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
146
147 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800148 // Suffix used during package installation when copying/moving
149 // package apks to install directory.
150 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800152 /**
153 * Indicates the state of installation. Used by PackageManager to
154 * figure out incomplete installations. Say a package is being installed
155 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
156 * the package installation is successful or unsuccesful lin which case
157 * the PackageManager will no longer maintain state information associated
158 * with the package. If some exception(like device freeze or battery being
159 * pulled out) occurs during installation of a package, the PackageManager
160 * needs this information to clean up the previously failed installation.
161 */
162 private static final int PKG_INSTALL_INCOMPLETE = 0;
163 private static final int PKG_INSTALL_COMPLETE = 1;
164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final int SCAN_MONITOR = 1<<0;
166 static final int SCAN_NO_DEX = 1<<1;
167 static final int SCAN_FORCE_DEX = 1<<2;
168 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800169 static final int SCAN_NEW_INSTALL = 1<<4;
170 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800172 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
173 "com.android.defcontainer",
174 "com.android.defcontainer.DefaultContainerService");
175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
177 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700178 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Dianne Hackborn851a5412009-05-08 12:06:44 -0700180 final int mSdkVersion = Build.VERSION.SDK_INT;
181 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
182 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 final Context mContext;
185 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700186 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 final DisplayMetrics mMetrics;
188 final int mDefParseFlags;
189 final String[] mSeparateProcesses;
190
191 // This is where all application persistent data goes.
192 final File mAppDataDir;
193
Oscar Montemayora8529f62009-11-18 10:14:20 -0800194 // If Encrypted File System feature is enabled, all application persistent data
195 // should go here instead.
196 final File mSecureAppDataDir;
197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // This is the object monitoring the framework dir.
199 final FileObserver mFrameworkInstallObserver;
200
201 // This is the object monitoring the system app dir.
202 final FileObserver mSystemInstallObserver;
203
204 // This is the object monitoring mAppInstallDir.
205 final FileObserver mAppInstallObserver;
206
207 // This is the object monitoring mDrmAppPrivateInstallDir.
208 final FileObserver mDrmAppInstallObserver;
209
210 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
211 // LOCK HELD. Can be called with mInstallLock held.
212 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 final File mFrameworkDir;
215 final File mSystemAppDir;
216 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700217 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218
219 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
220 // apps.
221 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 // Lock for state used when installing and doing other long running
226 // operations. Methods that must be called with this lock held have
227 // the prefix "LI".
228 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 // These are the directories in the 3rd party applications installed dir
231 // that we have currently loaded packages from. Keys are the application's
232 // installed zip file (absolute codePath), and values are Package.
233 final HashMap<String, PackageParser.Package> mAppDirs =
234 new HashMap<String, PackageParser.Package>();
235
236 // Information for the parser to write more useful error messages.
237 File mScanningPath;
238 int mLastScanError;
239
240 final int[] mOutPermissions = new int[3];
241
242 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // Keys are String (package name), values are Package. This also serves
245 // as the lock for the global state. Methods that must be called with
246 // this lock held have the prefix "LP".
247 final HashMap<String, PackageParser.Package> mPackages =
248 new HashMap<String, PackageParser.Package>();
249
250 final Settings mSettings;
251 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
254 int[] mGlobalGids;
255
256 // These are the built-in uid -> permission mappings that were read from the
257 // etc/permissions.xml file.
258 final SparseArray<HashSet<String>> mSystemPermissions =
259 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 // These are the built-in shared libraries that were read from the
262 // etc/permissions.xml file.
263 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
Dianne Hackborn49237342009-08-27 20:08:01 -0700265 // Temporary for building the final shared libraries for an .apk.
266 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800267
Dianne Hackborn49237342009-08-27 20:08:01 -0700268 // These are the features this devices supports that were read from the
269 // etc/permissions.xml file.
270 final HashMap<String, FeatureInfo> mAvailableFeatures =
271 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // All available activities, for your resolving pleasure.
274 final ActivityIntentResolver mActivities =
275 new ActivityIntentResolver();
276
277 // All available receivers, for your resolving pleasure.
278 final ActivityIntentResolver mReceivers =
279 new ActivityIntentResolver();
280
281 // All available services, for your resolving pleasure.
282 final ServiceIntentResolver mServices = new ServiceIntentResolver();
283
284 // Keys are String (provider class name), values are Provider.
285 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
286 new HashMap<ComponentName, PackageParser.Provider>();
287
288 // Mapping from provider base names (first directory in content URI codePath)
289 // to the provider information.
290 final HashMap<String, PackageParser.Provider> mProviders =
291 new HashMap<String, PackageParser.Provider>();
292
293 // Mapping from instrumentation class names to info about them.
294 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
295 new HashMap<ComponentName, PackageParser.Instrumentation>();
296
297 // Mapping from permission names to info about them.
298 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
299 new HashMap<String, PackageParser.PermissionGroup>();
300
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800301 // Packages whose data we have transfered into another package, thus
302 // should no longer exist.
303 final HashSet<String> mTransferedPackages = new HashSet<String>();
304
Dianne Hackborn854060af2009-07-09 18:14:31 -0700305 // Broadcast actions that are only available to the system.
306 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 boolean mSystemReady;
309 boolean mSafeMode;
310 boolean mHasSystemUidErrors;
311
312 ApplicationInfo mAndroidApplication;
313 final ActivityInfo mResolveActivity = new ActivityInfo();
314 final ResolveInfo mResolveInfo = new ResolveInfo();
315 ComponentName mResolveComponentName;
316 PackageParser.Package mPlatformPackage;
317
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700318 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800319 final HashMap<String, ArrayList<String>> mPendingBroadcasts
320 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800321 // Service Connection to remote media container service to copy
322 // package uri's from external media onto secure containers
323 // or internal storage.
324 private IMediaContainerService mContainerService = null;
325
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700326 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800327 static final int MCS_BOUND = 3;
328 static final int END_COPY = 4;
329 static final int INIT_COPY = 5;
330 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800331 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800332 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800333 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800334 static final int MCS_RECONNECT = 10;
335 static final int MCS_GIVE_UP = 11;
336
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700337 // Delay time in millisecs
338 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800339 final private DefaultContainerConnection mDefContainerConn =
340 new DefaultContainerConnection();
341 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800342 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800343 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800344 IMediaContainerService imcs =
345 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800347 }
348
349 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800351 }
352 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700353
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 // Recordkeeping of restore-after-install operations that are currently in flight
355 // between the Package Manager and the Backup Manager
356 class PostInstallData {
357 public InstallArgs args;
358 public PackageInstalledInfo res;
359
360 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
361 args = _a;
362 res = _r;
363 }
364 };
365 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
366 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
367
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700368 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800370 final ArrayList<HandlerParams> mPendingInstalls =
371 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372
373 private boolean connectToService() {
374 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
375 " DefaultContainerService");
376 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
377 if (mContext.bindService(service, mDefContainerConn,
378 Context.BIND_AUTO_CREATE)) {
379 mBound = true;
380 return true;
381 }
382 return false;
383 }
384
385 private void disconnectService() {
386 mContainerService = null;
387 mBound = false;
388 mContext.unbindService(mDefContainerConn);
389 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800390
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700391 PackageHandler(Looper looper) {
392 super(looper);
393 }
394 public void handleMessage(Message msg) {
395 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800396 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800398 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 int idx = mPendingInstalls.size();
400 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
401 // If a bind was already initiated we dont really
402 // need to do anything. The pending install
403 // will be processed later on.
404 if (!mBound) {
405 // If this is the only one pending we might
406 // have to bind to the service again.
407 if (!connectToService()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800408 Log.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800409 params.serviceError();
410 return;
411 } else {
412 // Once we bind to the service, the first
413 // pending request will be processed.
414 mPendingInstalls.add(idx, params);
415 }
416 } else {
417 mPendingInstalls.add(idx, params);
418 // Already bound to the service. Just make
419 // sure we trigger off processing the first request.
420 if (idx == 0) {
421 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800422 }
423 }
424 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425 }
426 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428 if (msg.obj != null) {
429 mContainerService = (IMediaContainerService) msg.obj;
430 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800431 if (mContainerService == null) {
432 // Something seriously wrong. Bail out
433 Log.e(TAG, "Cannot bind to media container service");
434 for (HandlerParams params : mPendingInstalls) {
435 mPendingInstalls.remove(0);
436 // Indicate service bind error
437 params.serviceError();
438 }
439 mPendingInstalls.clear();
440 } else if (mPendingInstalls.size() > 0) {
441 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800442 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 params.startCopy();
444 }
445 } else {
446 // Should never happen ideally.
447 Log.w(TAG, "Empty queue");
448 }
449 break;
450 }
451 case MCS_RECONNECT : {
452 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
453 if (mPendingInstalls.size() > 0) {
454 if (mBound) {
455 disconnectService();
456 }
457 if (!connectToService()) {
458 Log.e(TAG, "Failed to bind to media container service");
459 for (HandlerParams params : mPendingInstalls) {
460 mPendingInstalls.remove(0);
461 // Indicate service bind error
462 params.serviceError();
463 }
464 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800465 }
466 }
467 break;
468 }
469 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
471 // Delete pending install
472 if (mPendingInstalls.size() > 0) {
473 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800474 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (mPendingInstalls.size() == 0) {
476 if (mBound) {
477 disconnectService();
478 }
479 } else {
480 // There are more pending requests in queue.
481 // Just post MCS_BOUND message to trigger processing
482 // of next pending install.
483 mHandler.sendEmptyMessage(MCS_BOUND);
484 }
485 break;
486 }
487 case MCS_GIVE_UP: {
488 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
489 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800490 break;
491 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700492 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800493 String packages[];
494 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700495 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700496 int uids[];
497 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800498 if (mPendingBroadcasts == null) {
499 return;
500 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700501 size = mPendingBroadcasts.size();
502 if (size <= 0) {
503 // Nothing to be done. Just return
504 return;
505 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800506 packages = new String[size];
507 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700508 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800509 Iterator<HashMap.Entry<String, ArrayList<String>>>
510 it = mPendingBroadcasts.entrySet().iterator();
511 int i = 0;
512 while (it.hasNext() && i < size) {
513 HashMap.Entry<String, ArrayList<String>> ent = it.next();
514 packages[i] = ent.getKey();
515 components[i] = ent.getValue();
516 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700517 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800518 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700519 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800520 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700521 mPendingBroadcasts.clear();
522 }
523 // Send broadcasts
524 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800525 sendPackageChangedBroadcast(packages[i], true,
526 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700527 }
528 break;
529 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800530 case START_CLEANING_PACKAGE: {
531 String packageName = (String)msg.obj;
532 synchronized (mPackages) {
533 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
534 mSettings.mPackagesToBeCleaned.add(packageName);
535 }
536 }
537 startCleaningPackages();
538 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800539 case POST_INSTALL: {
540 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
541 PostInstallData data = mRunningInstalls.get(msg.arg1);
542 mRunningInstalls.delete(msg.arg1);
543
544 if (data != null) {
545 InstallArgs args = data.args;
546 PackageInstalledInfo res = data.res;
547
548 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
549 res.removedInfo.sendBroadcast(false, true);
550 Bundle extras = new Bundle(1);
551 extras.putInt(Intent.EXTRA_UID, res.uid);
552 final boolean update = res.removedInfo.removedPackage != null;
553 if (update) {
554 extras.putBoolean(Intent.EXTRA_REPLACING, true);
555 }
556 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
557 res.pkg.applicationInfo.packageName,
558 extras);
559 if (update) {
560 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
561 res.pkg.applicationInfo.packageName,
562 extras);
563 }
564 if (res.removedInfo.args != null) {
565 // Remove the replaced package's older resources safely now
566 synchronized (mInstallLock) {
567 res.removedInfo.args.doPostDeleteLI(true);
568 }
569 }
570 }
571 Runtime.getRuntime().gc();
572
573 if (args.observer != null) {
574 try {
575 args.observer.packageInstalled(res.name, res.returnCode);
576 } catch (RemoteException e) {
577 Log.i(TAG, "Observer no longer exists.");
578 }
579 }
580 } else {
581 Log.e(TAG, "Bogus post-install token " + msg.arg1);
582 }
583 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700584 }
585 }
586 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800587
588 static boolean installOnSd(int flags) {
589 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800590 ((flags & PackageManager.INSTALL_EXTERNAL) == 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800591 return false;
592 }
593 return true;
594 }
595
596 static boolean isFwdLocked(int flags) {
597 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
598 return true;
599 }
600 return false;
601 }
602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 public static final IPackageManager main(Context context, boolean factoryTest) {
604 PackageManagerService m = new PackageManagerService(context, factoryTest);
605 ServiceManager.addService("package", m);
606 return m;
607 }
608
609 static String[] splitString(String str, char sep) {
610 int count = 1;
611 int i = 0;
612 while ((i=str.indexOf(sep, i)) >= 0) {
613 count++;
614 i++;
615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 String[] res = new String[count];
618 i=0;
619 count = 0;
620 int lastI=0;
621 while ((i=str.indexOf(sep, i)) >= 0) {
622 res[count] = str.substring(lastI, i);
623 count++;
624 i++;
625 lastI = i;
626 }
627 res[count] = str.substring(lastI, str.length());
628 return res;
629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800632 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 if (mSdkVersion <= 0) {
636 Log.w(TAG, "**** ro.build.version.sdk not set!");
637 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 mContext = context;
640 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700641 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 mMetrics = new DisplayMetrics();
643 mSettings = new Settings();
644 mSettings.addSharedUserLP("android.uid.system",
645 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
646 mSettings.addSharedUserLP("android.uid.phone",
647 MULTIPLE_APPLICATION_UIDS
648 ? RADIO_UID : FIRST_APPLICATION_UID,
649 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400650 mSettings.addSharedUserLP("android.uid.log",
651 MULTIPLE_APPLICATION_UIDS
652 ? LOG_UID : FIRST_APPLICATION_UID,
653 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654
655 String separateProcesses = SystemProperties.get("debug.separate_processes");
656 if (separateProcesses != null && separateProcesses.length() > 0) {
657 if ("*".equals(separateProcesses)) {
658 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
659 mSeparateProcesses = null;
660 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
661 } else {
662 mDefParseFlags = 0;
663 mSeparateProcesses = separateProcesses.split(",");
664 Log.w(TAG, "Running with debug.separate_processes: "
665 + separateProcesses);
666 }
667 } else {
668 mDefParseFlags = 0;
669 mSeparateProcesses = null;
670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 Installer installer = new Installer();
673 // Little hacky thing to check if installd is here, to determine
674 // whether we are running on the simulator and thus need to take
675 // care of building the /data file structure ourself.
676 // (apparently the sim now has a working installer)
677 if (installer.ping() && Process.supportsProcesses()) {
678 mInstaller = installer;
679 } else {
680 mInstaller = null;
681 }
682
683 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
684 Display d = wm.getDefaultDisplay();
685 d.getMetrics(mMetrics);
686
687 synchronized (mInstallLock) {
688 synchronized (mPackages) {
689 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700690 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 File dataDir = Environment.getDataDirectory();
693 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800694 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800695 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
696
697 if (mInstaller == null) {
698 // Make sure these dirs exist, when we are running in
699 // the simulator.
700 // Make a wide-open directory for random misc stuff.
701 File miscDir = new File(dataDir, "misc");
702 miscDir.mkdirs();
703 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800704 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 mDrmAppPrivateInstallDir.mkdirs();
706 }
707
708 readPermissions();
709
710 mRestoredSettings = mSettings.readLP();
711 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
713 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800714 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800716 // Set flag to monitor and not change apk file paths when
717 // scanning install directories.
718 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700719 if (mNoDexOpt) {
720 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700727 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700730 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 /**
733 * Out of paranoia, ensure that everything in the boot class
734 * path has been dexed.
735 */
736 String bootClassPath = System.getProperty("java.boot.class.path");
737 if (bootClassPath != null) {
738 String[] paths = splitString(bootClassPath, ':');
739 for (int i=0; i<paths.length; i++) {
740 try {
741 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
742 libFiles.add(paths[i]);
743 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700744 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 }
746 } catch (FileNotFoundException e) {
747 Log.w(TAG, "Boot class path not found: " + paths[i]);
748 } catch (IOException e) {
749 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
750 }
751 }
752 } else {
753 Log.w(TAG, "No BOOTCLASSPATH found!");
754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 /**
757 * Also ensure all external libraries have had dexopt run on them.
758 */
759 if (mSharedLibraries.size() > 0) {
760 Iterator<String> libs = mSharedLibraries.values().iterator();
761 while (libs.hasNext()) {
762 String lib = libs.next();
763 try {
764 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
765 libFiles.add(lib);
766 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700767 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 }
769 } catch (FileNotFoundException e) {
770 Log.w(TAG, "Library not found: " + lib);
771 } catch (IOException e) {
772 Log.w(TAG, "Exception reading library: " + lib, e);
773 }
774 }
775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 // Gross hack for now: we know this file doesn't contain any
778 // code, so don't dexopt it to avoid the resulting log spew.
779 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 /**
782 * And there are a number of commands implemented in Java, which
783 * we currently need to do the dexopt on so that they can be
784 * run from a non-root shell.
785 */
786 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700787 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 for (int i=0; i<frameworkFiles.length; i++) {
789 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
790 String path = libPath.getPath();
791 // Skip the file if we alrady did it.
792 if (libFiles.contains(path)) {
793 continue;
794 }
795 // Skip the file if it is not a type we want to dexopt.
796 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
797 continue;
798 }
799 try {
800 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
801 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700802 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 }
804 } catch (FileNotFoundException e) {
805 Log.w(TAG, "Jar not found: " + path);
806 } catch (IOException e) {
807 Log.w(TAG, "Exception reading jar: " + path, e);
808 }
809 }
810 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 if (didDexOpt) {
813 // If we had to do a dexopt of one of the previous
814 // things, then something on the system has changed.
815 // Consider this significant, and wipe away all other
816 // existing dexopt files to ensure we don't leave any
817 // dangling around.
818 String[] files = mDalvikCacheDir.list();
819 if (files != null) {
820 for (int i=0; i<files.length; i++) {
821 String fn = files[i];
822 if (fn.startsWith("data@app@")
823 || fn.startsWith("data@app-private@")) {
824 Log.i(TAG, "Pruning dalvik file: " + fn);
825 (new File(mDalvikCacheDir, fn)).delete();
826 }
827 }
828 }
829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800831
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800832 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 mFrameworkInstallObserver = new AppDirObserver(
834 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
835 mFrameworkInstallObserver.startWatching();
836 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800837 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800838
839 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
841 mSystemInstallObserver = new AppDirObserver(
842 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
843 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800844 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800845
846 if (mInstaller != null) {
847 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
848 mInstaller.moveFiles();
849 }
850
851 // Prune any system packages that no longer exist.
852 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
853 while (psit.hasNext()) {
854 PackageSetting ps = psit.next();
855 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800856 && !mPackages.containsKey(ps.name)
857 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800858 psit.remove();
859 String msg = "System package " + ps.name
860 + " no longer exists; wiping its data";
861 reportSettingsProblem(Log.WARN, msg);
862 if (mInstaller != null) {
863 // XXX how to set useEncryptedFSDir for packages that
864 // are not encrypted?
865 mInstaller.remove(ps.name, true);
866 }
867 }
868 }
869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 mAppInstallDir = new File(dataDir, "app");
871 if (mInstaller == null) {
872 // Make sure these dirs exist, when we are running in
873 // the simulator.
874 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
875 }
876 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800877 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 //clean up list
879 for(int i = 0; i < deletePkgsList.size(); i++) {
880 //clean up here
881 cleanupInstallFailedPackage(deletePkgsList.get(i));
882 }
883 //delete tmp files
884 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800885
886 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 SystemClock.uptimeMillis());
888 mAppInstallObserver = new AppDirObserver(
889 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
890 mAppInstallObserver.startWatching();
891 scanDirLI(mAppInstallDir, 0, scanMode);
892
893 mDrmAppInstallObserver = new AppDirObserver(
894 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
895 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800896 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800899 SystemClock.uptimeMillis());
900 Log.i(TAG, "Time to scan packages: "
901 + ((SystemClock.uptimeMillis()-startTime)/1000f)
902 + " seconds");
903
904 updatePermissionsLP();
905
906 mSettings.writeLP();
907
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800908 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 // Now after opening every single application zip, make sure they
912 // are all flushed. Not really needed, but keeps things nice and
913 // tidy.
914 Runtime.getRuntime().gc();
915 } // synchronized (mPackages)
916 } // synchronized (mInstallLock)
917 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 @Override
920 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
921 throws RemoteException {
922 try {
923 return super.onTransact(code, data, reply, flags);
924 } catch (RuntimeException e) {
925 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
926 Log.e(TAG, "Package Manager Crash", e);
927 }
928 throw e;
929 }
930 }
931
Dianne Hackborne6620b22010-01-22 14:46:21 -0800932 void cleanupInstallFailedPackage(PackageSetting ps) {
933 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800935 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
936 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 if (retCode < 0) {
938 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800939 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 }
941 } else {
942 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800943 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 File dataDir = new File(pkg.applicationInfo.dataDir);
945 dataDir.delete();
946 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800947 if (ps.codePath != null) {
948 if (!ps.codePath.delete()) {
949 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
950 }
951 }
952 if (ps.resourcePath != null) {
953 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
954 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
955 }
956 }
957 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 }
959
960 void readPermissions() {
961 // Read permissions from .../etc/permission directory.
962 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
963 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
964 Log.w(TAG, "No directory " + libraryDir + ", skipping");
965 return;
966 }
967 if (!libraryDir.canRead()) {
968 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
969 return;
970 }
971
972 // Iterate over the files in the directory and scan .xml files
973 for (File f : libraryDir.listFiles()) {
974 // We'll read platform.xml last
975 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
976 continue;
977 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 if (!f.getPath().endsWith(".xml")) {
980 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
981 continue;
982 }
983 if (!f.canRead()) {
984 Log.w(TAG, "Permissions library file " + f + " cannot be read");
985 continue;
986 }
987
988 readPermissionsFromXml(f);
989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
992 final File permFile = new File(Environment.getRootDirectory(),
993 "etc/permissions/platform.xml");
994 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700996 StringBuilder sb = new StringBuilder(128);
997 sb.append("Libs:");
998 Iterator<String> it = mSharedLibraries.keySet().iterator();
999 while (it.hasNext()) {
1000 sb.append(' ');
1001 String name = it.next();
1002 sb.append(name);
1003 sb.append(':');
1004 sb.append(mSharedLibraries.get(name));
1005 }
1006 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001008 sb.setLength(0);
1009 sb.append("Features:");
1010 it = mAvailableFeatures.keySet().iterator();
1011 while (it.hasNext()) {
1012 sb.append(' ');
1013 sb.append(it.next());
1014 }
1015 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001017
1018 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 FileReader permReader = null;
1020 try {
1021 permReader = new FileReader(permFile);
1022 } catch (FileNotFoundException e) {
1023 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
1024 return;
1025 }
1026
1027 try {
1028 XmlPullParser parser = Xml.newPullParser();
1029 parser.setInput(permReader);
1030
1031 XmlUtils.beginDocument(parser, "permissions");
1032
1033 while (true) {
1034 XmlUtils.nextElement(parser);
1035 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1036 break;
1037 }
1038
1039 String name = parser.getName();
1040 if ("group".equals(name)) {
1041 String gidStr = parser.getAttributeValue(null, "gid");
1042 if (gidStr != null) {
1043 int gid = Integer.parseInt(gidStr);
1044 mGlobalGids = appendInt(mGlobalGids, gid);
1045 } else {
1046 Log.w(TAG, "<group> without gid at "
1047 + parser.getPositionDescription());
1048 }
1049
1050 XmlUtils.skipCurrentTag(parser);
1051 continue;
1052 } else if ("permission".equals(name)) {
1053 String perm = parser.getAttributeValue(null, "name");
1054 if (perm == null) {
1055 Log.w(TAG, "<permission> without name at "
1056 + parser.getPositionDescription());
1057 XmlUtils.skipCurrentTag(parser);
1058 continue;
1059 }
1060 perm = perm.intern();
1061 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 } else if ("assign-permission".equals(name)) {
1064 String perm = parser.getAttributeValue(null, "name");
1065 if (perm == null) {
1066 Log.w(TAG, "<assign-permission> without name at "
1067 + parser.getPositionDescription());
1068 XmlUtils.skipCurrentTag(parser);
1069 continue;
1070 }
1071 String uidStr = parser.getAttributeValue(null, "uid");
1072 if (uidStr == null) {
1073 Log.w(TAG, "<assign-permission> without uid at "
1074 + parser.getPositionDescription());
1075 XmlUtils.skipCurrentTag(parser);
1076 continue;
1077 }
1078 int uid = Process.getUidForName(uidStr);
1079 if (uid < 0) {
1080 Log.w(TAG, "<assign-permission> with unknown uid \""
1081 + uidStr + "\" at "
1082 + parser.getPositionDescription());
1083 XmlUtils.skipCurrentTag(parser);
1084 continue;
1085 }
1086 perm = perm.intern();
1087 HashSet<String> perms = mSystemPermissions.get(uid);
1088 if (perms == null) {
1089 perms = new HashSet<String>();
1090 mSystemPermissions.put(uid, perms);
1091 }
1092 perms.add(perm);
1093 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 } else if ("library".equals(name)) {
1096 String lname = parser.getAttributeValue(null, "name");
1097 String lfile = parser.getAttributeValue(null, "file");
1098 if (lname == null) {
1099 Log.w(TAG, "<library> without name at "
1100 + parser.getPositionDescription());
1101 } else if (lfile == null) {
1102 Log.w(TAG, "<library> without file at "
1103 + parser.getPositionDescription());
1104 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001106 mSharedLibraries.put(lname, lfile);
1107 }
1108 XmlUtils.skipCurrentTag(parser);
1109 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001110
Dianne Hackborn49237342009-08-27 20:08:01 -07001111 } else if ("feature".equals(name)) {
1112 String fname = parser.getAttributeValue(null, "name");
1113 if (fname == null) {
1114 Log.w(TAG, "<feature> without name at "
1115 + parser.getPositionDescription());
1116 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001117 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001118 FeatureInfo fi = new FeatureInfo();
1119 fi.name = fname;
1120 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
1122 XmlUtils.skipCurrentTag(parser);
1123 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 } else {
1126 XmlUtils.skipCurrentTag(parser);
1127 continue;
1128 }
1129
1130 }
1131 } catch (XmlPullParserException e) {
1132 Log.w(TAG, "Got execption parsing permissions.", e);
1133 } catch (IOException e) {
1134 Log.w(TAG, "Got execption parsing permissions.", e);
1135 }
1136 }
1137
1138 void readPermission(XmlPullParser parser, String name)
1139 throws IOException, XmlPullParserException {
1140
1141 name = name.intern();
1142
1143 BasePermission bp = mSettings.mPermissions.get(name);
1144 if (bp == null) {
1145 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1146 mSettings.mPermissions.put(name, bp);
1147 }
1148 int outerDepth = parser.getDepth();
1149 int type;
1150 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1151 && (type != XmlPullParser.END_TAG
1152 || parser.getDepth() > outerDepth)) {
1153 if (type == XmlPullParser.END_TAG
1154 || type == XmlPullParser.TEXT) {
1155 continue;
1156 }
1157
1158 String tagName = parser.getName();
1159 if ("group".equals(tagName)) {
1160 String gidStr = parser.getAttributeValue(null, "gid");
1161 if (gidStr != null) {
1162 int gid = Process.getGidForName(gidStr);
1163 bp.gids = appendInt(bp.gids, gid);
1164 } else {
1165 Log.w(TAG, "<group> without gid at "
1166 + parser.getPositionDescription());
1167 }
1168 }
1169 XmlUtils.skipCurrentTag(parser);
1170 }
1171 }
1172
1173 static int[] appendInt(int[] cur, int val) {
1174 if (cur == null) {
1175 return new int[] { val };
1176 }
1177 final int N = cur.length;
1178 for (int i=0; i<N; i++) {
1179 if (cur[i] == val) {
1180 return cur;
1181 }
1182 }
1183 int[] ret = new int[N+1];
1184 System.arraycopy(cur, 0, ret, 0, N);
1185 ret[N] = val;
1186 return ret;
1187 }
1188
1189 static int[] appendInts(int[] cur, int[] add) {
1190 if (add == null) return cur;
1191 if (cur == null) return add;
1192 final int N = add.length;
1193 for (int i=0; i<N; i++) {
1194 cur = appendInt(cur, add[i]);
1195 }
1196 return cur;
1197 }
1198
1199 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001200 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1201 // The package has been uninstalled but has retained data and resources.
1202 return PackageParser.generatePackageInfo(p, null, flags);
1203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 final PackageSetting ps = (PackageSetting)p.mExtras;
1205 if (ps == null) {
1206 return null;
1207 }
1208 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1209 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1210 }
1211
1212 public PackageInfo getPackageInfo(String packageName, int flags) {
1213 synchronized (mPackages) {
1214 PackageParser.Package p = mPackages.get(packageName);
1215 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001216 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 + ": " + p);
1218 if (p != null) {
1219 return generatePackageInfo(p, flags);
1220 }
1221 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1222 return generatePackageInfoFromSettingsLP(packageName, flags);
1223 }
1224 }
1225 return null;
1226 }
1227
Dianne Hackborn47096932010-02-11 15:57:09 -08001228 public String[] currentToCanonicalPackageNames(String[] names) {
1229 String[] out = new String[names.length];
1230 synchronized (mPackages) {
1231 for (int i=names.length-1; i>=0; i--) {
1232 PackageSetting ps = mSettings.mPackages.get(names[i]);
1233 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1234 }
1235 }
1236 return out;
1237 }
1238
1239 public String[] canonicalToCurrentPackageNames(String[] names) {
1240 String[] out = new String[names.length];
1241 synchronized (mPackages) {
1242 for (int i=names.length-1; i>=0; i--) {
1243 String cur = mSettings.mRenamedPackages.get(names[i]);
1244 out[i] = cur != null ? cur : names[i];
1245 }
1246 }
1247 return out;
1248 }
1249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001250 public int getPackageUid(String packageName) {
1251 synchronized (mPackages) {
1252 PackageParser.Package p = mPackages.get(packageName);
1253 if(p != null) {
1254 return p.applicationInfo.uid;
1255 }
1256 PackageSetting ps = mSettings.mPackages.get(packageName);
1257 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1258 return -1;
1259 }
1260 p = ps.pkg;
1261 return p != null ? p.applicationInfo.uid : -1;
1262 }
1263 }
1264
1265 public int[] getPackageGids(String packageName) {
1266 synchronized (mPackages) {
1267 PackageParser.Package p = mPackages.get(packageName);
1268 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001269 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 + ": " + p);
1271 if (p != null) {
1272 final PackageSetting ps = (PackageSetting)p.mExtras;
1273 final SharedUserSetting suid = ps.sharedUser;
1274 return suid != null ? suid.gids : ps.gids;
1275 }
1276 }
1277 // stupid thing to indicate an error.
1278 return new int[0];
1279 }
1280
1281 public PermissionInfo getPermissionInfo(String name, int flags) {
1282 synchronized (mPackages) {
1283 final BasePermission p = mSettings.mPermissions.get(name);
1284 if (p != null && p.perm != null) {
1285 return PackageParser.generatePermissionInfo(p.perm, flags);
1286 }
1287 return null;
1288 }
1289 }
1290
1291 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1292 synchronized (mPackages) {
1293 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1294 for (BasePermission p : mSettings.mPermissions.values()) {
1295 if (group == null) {
1296 if (p.perm.info.group == null) {
1297 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1298 }
1299 } else {
1300 if (group.equals(p.perm.info.group)) {
1301 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1302 }
1303 }
1304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if (out.size() > 0) {
1307 return out;
1308 }
1309 return mPermissionGroups.containsKey(group) ? out : null;
1310 }
1311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1314 synchronized (mPackages) {
1315 return PackageParser.generatePermissionGroupInfo(
1316 mPermissionGroups.get(name), flags);
1317 }
1318 }
1319
1320 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1321 synchronized (mPackages) {
1322 final int N = mPermissionGroups.size();
1323 ArrayList<PermissionGroupInfo> out
1324 = new ArrayList<PermissionGroupInfo>(N);
1325 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1326 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1327 }
1328 return out;
1329 }
1330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1333 PackageSetting ps = mSettings.mPackages.get(packageName);
1334 if(ps != null) {
1335 if(ps.pkg == null) {
1336 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1337 if(pInfo != null) {
1338 return pInfo.applicationInfo;
1339 }
1340 return null;
1341 }
1342 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1343 }
1344 return null;
1345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1348 PackageSetting ps = mSettings.mPackages.get(packageName);
1349 if(ps != null) {
1350 if(ps.pkg == null) {
1351 ps.pkg = new PackageParser.Package(packageName);
1352 ps.pkg.applicationInfo.packageName = packageName;
1353 }
1354 return generatePackageInfo(ps.pkg, flags);
1355 }
1356 return null;
1357 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1360 synchronized (mPackages) {
1361 PackageParser.Package p = mPackages.get(packageName);
1362 if (Config.LOGV) Log.v(
1363 TAG, "getApplicationInfo " + packageName
1364 + ": " + p);
1365 if (p != null) {
1366 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001367 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 }
1369 if ("android".equals(packageName)||"system".equals(packageName)) {
1370 return mAndroidApplication;
1371 }
1372 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1373 return generateApplicationInfoFromSettingsLP(packageName, flags);
1374 }
1375 }
1376 return null;
1377 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001378
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1381 mContext.enforceCallingOrSelfPermission(
1382 android.Manifest.permission.CLEAR_APP_CACHE, null);
1383 // Queue up an async operation since clearing cache may take a little while.
1384 mHandler.post(new Runnable() {
1385 public void run() {
1386 mHandler.removeCallbacks(this);
1387 int retCode = -1;
1388 if (mInstaller != null) {
1389 retCode = mInstaller.freeCache(freeStorageSize);
1390 if (retCode < 0) {
1391 Log.w(TAG, "Couldn't clear application caches");
1392 }
1393 } //end if mInstaller
1394 if (observer != null) {
1395 try {
1396 observer.onRemoveCompleted(null, (retCode >= 0));
1397 } catch (RemoteException e) {
1398 Log.w(TAG, "RemoveException when invoking call back");
1399 }
1400 }
1401 }
1402 });
1403 }
1404
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001405 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001406 mContext.enforceCallingOrSelfPermission(
1407 android.Manifest.permission.CLEAR_APP_CACHE, null);
1408 // Queue up an async operation since clearing cache may take a little while.
1409 mHandler.post(new Runnable() {
1410 public void run() {
1411 mHandler.removeCallbacks(this);
1412 int retCode = -1;
1413 if (mInstaller != null) {
1414 retCode = mInstaller.freeCache(freeStorageSize);
1415 if (retCode < 0) {
1416 Log.w(TAG, "Couldn't clear application caches");
1417 }
1418 }
1419 if(pi != null) {
1420 try {
1421 // Callback via pending intent
1422 int code = (retCode >= 0) ? 1 : 0;
1423 pi.sendIntent(null, code, null,
1424 null, null);
1425 } catch (SendIntentException e1) {
1426 Log.i(TAG, "Failed to send pending intent");
1427 }
1428 }
1429 }
1430 });
1431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1434 synchronized (mPackages) {
1435 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001436
1437 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001439 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 if (mResolveComponentName.equals(component)) {
1442 return mResolveActivity;
1443 }
1444 }
1445 return null;
1446 }
1447
1448 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1449 synchronized (mPackages) {
1450 PackageParser.Activity a = mReceivers.mActivities.get(component);
1451 if (Config.LOGV) Log.v(
1452 TAG, "getReceiverInfo " + component + ": " + a);
1453 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1454 return PackageParser.generateActivityInfo(a, flags);
1455 }
1456 }
1457 return null;
1458 }
1459
1460 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1461 synchronized (mPackages) {
1462 PackageParser.Service s = mServices.mServices.get(component);
1463 if (Config.LOGV) Log.v(
1464 TAG, "getServiceInfo " + component + ": " + s);
1465 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1466 return PackageParser.generateServiceInfo(s, flags);
1467 }
1468 }
1469 return null;
1470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 public String[] getSystemSharedLibraryNames() {
1473 Set<String> libSet;
1474 synchronized (mPackages) {
1475 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001476 int size = libSet.size();
1477 if (size > 0) {
1478 String[] libs = new String[size];
1479 libSet.toArray(libs);
1480 return libs;
1481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001483 return null;
1484 }
1485
1486 public FeatureInfo[] getSystemAvailableFeatures() {
1487 Collection<FeatureInfo> featSet;
1488 synchronized (mPackages) {
1489 featSet = mAvailableFeatures.values();
1490 int size = featSet.size();
1491 if (size > 0) {
1492 FeatureInfo[] features = new FeatureInfo[size+1];
1493 featSet.toArray(features);
1494 FeatureInfo fi = new FeatureInfo();
1495 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1496 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1497 features[size] = fi;
1498 return features;
1499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 }
1501 return null;
1502 }
1503
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001504 public boolean hasSystemFeature(String name) {
1505 synchronized (mPackages) {
1506 return mAvailableFeatures.containsKey(name);
1507 }
1508 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 public int checkPermission(String permName, String pkgName) {
1511 synchronized (mPackages) {
1512 PackageParser.Package p = mPackages.get(pkgName);
1513 if (p != null && p.mExtras != null) {
1514 PackageSetting ps = (PackageSetting)p.mExtras;
1515 if (ps.sharedUser != null) {
1516 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1517 return PackageManager.PERMISSION_GRANTED;
1518 }
1519 } else if (ps.grantedPermissions.contains(permName)) {
1520 return PackageManager.PERMISSION_GRANTED;
1521 }
1522 }
1523 }
1524 return PackageManager.PERMISSION_DENIED;
1525 }
1526
1527 public int checkUidPermission(String permName, int uid) {
1528 synchronized (mPackages) {
1529 Object obj = mSettings.getUserIdLP(uid);
1530 if (obj != null) {
1531 if (obj instanceof SharedUserSetting) {
1532 SharedUserSetting sus = (SharedUserSetting)obj;
1533 if (sus.grantedPermissions.contains(permName)) {
1534 return PackageManager.PERMISSION_GRANTED;
1535 }
1536 } else if (obj instanceof PackageSetting) {
1537 PackageSetting ps = (PackageSetting)obj;
1538 if (ps.grantedPermissions.contains(permName)) {
1539 return PackageManager.PERMISSION_GRANTED;
1540 }
1541 }
1542 } else {
1543 HashSet<String> perms = mSystemPermissions.get(uid);
1544 if (perms != null && perms.contains(permName)) {
1545 return PackageManager.PERMISSION_GRANTED;
1546 }
1547 }
1548 }
1549 return PackageManager.PERMISSION_DENIED;
1550 }
1551
1552 private BasePermission findPermissionTreeLP(String permName) {
1553 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1554 if (permName.startsWith(bp.name) &&
1555 permName.length() > bp.name.length() &&
1556 permName.charAt(bp.name.length()) == '.') {
1557 return bp;
1558 }
1559 }
1560 return null;
1561 }
1562
1563 private BasePermission checkPermissionTreeLP(String permName) {
1564 if (permName != null) {
1565 BasePermission bp = findPermissionTreeLP(permName);
1566 if (bp != null) {
1567 if (bp.uid == Binder.getCallingUid()) {
1568 return bp;
1569 }
1570 throw new SecurityException("Calling uid "
1571 + Binder.getCallingUid()
1572 + " is not allowed to add to permission tree "
1573 + bp.name + " owned by uid " + bp.uid);
1574 }
1575 }
1576 throw new SecurityException("No permission tree found for " + permName);
1577 }
1578
1579 public boolean addPermission(PermissionInfo info) {
1580 synchronized (mPackages) {
1581 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1582 throw new SecurityException("Label must be specified in permission");
1583 }
1584 BasePermission tree = checkPermissionTreeLP(info.name);
1585 BasePermission bp = mSettings.mPermissions.get(info.name);
1586 boolean added = bp == null;
1587 if (added) {
1588 bp = new BasePermission(info.name, tree.sourcePackage,
1589 BasePermission.TYPE_DYNAMIC);
1590 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1591 throw new SecurityException(
1592 "Not allowed to modify non-dynamic permission "
1593 + info.name);
1594 }
1595 bp.perm = new PackageParser.Permission(tree.perm.owner,
1596 new PermissionInfo(info));
1597 bp.perm.info.packageName = tree.perm.info.packageName;
1598 bp.uid = tree.uid;
1599 if (added) {
1600 mSettings.mPermissions.put(info.name, bp);
1601 }
1602 mSettings.writeLP();
1603 return added;
1604 }
1605 }
1606
1607 public void removePermission(String name) {
1608 synchronized (mPackages) {
1609 checkPermissionTreeLP(name);
1610 BasePermission bp = mSettings.mPermissions.get(name);
1611 if (bp != null) {
1612 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1613 throw new SecurityException(
1614 "Not allowed to modify non-dynamic permission "
1615 + name);
1616 }
1617 mSettings.mPermissions.remove(name);
1618 mSettings.writeLP();
1619 }
1620 }
1621 }
1622
Dianne Hackborn854060af2009-07-09 18:14:31 -07001623 public boolean isProtectedBroadcast(String actionName) {
1624 synchronized (mPackages) {
1625 return mProtectedBroadcasts.contains(actionName);
1626 }
1627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 public int checkSignatures(String pkg1, String pkg2) {
1630 synchronized (mPackages) {
1631 PackageParser.Package p1 = mPackages.get(pkg1);
1632 PackageParser.Package p2 = mPackages.get(pkg2);
1633 if (p1 == null || p1.mExtras == null
1634 || p2 == null || p2.mExtras == null) {
1635 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1636 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001637 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639 }
1640
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001641 public int checkUidSignatures(int uid1, int uid2) {
1642 synchronized (mPackages) {
1643 Signature[] s1;
1644 Signature[] s2;
1645 Object obj = mSettings.getUserIdLP(uid1);
1646 if (obj != null) {
1647 if (obj instanceof SharedUserSetting) {
1648 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1649 } else if (obj instanceof PackageSetting) {
1650 s1 = ((PackageSetting)obj).signatures.mSignatures;
1651 } else {
1652 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1653 }
1654 } else {
1655 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1656 }
1657 obj = mSettings.getUserIdLP(uid2);
1658 if (obj != null) {
1659 if (obj instanceof SharedUserSetting) {
1660 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1661 } else if (obj instanceof PackageSetting) {
1662 s2 = ((PackageSetting)obj).signatures.mSignatures;
1663 } else {
1664 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1665 }
1666 } else {
1667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1668 }
1669 return checkSignaturesLP(s1, s2);
1670 }
1671 }
1672
1673 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1674 if (s1 == null) {
1675 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1677 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1678 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001679 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1681 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001682 final int N1 = s1.length;
1683 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 for (int i=0; i<N1; i++) {
1685 boolean match = false;
1686 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001687 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 match = true;
1689 break;
1690 }
1691 }
1692 if (!match) {
1693 return PackageManager.SIGNATURE_NO_MATCH;
1694 }
1695 }
1696 return PackageManager.SIGNATURE_MATCH;
1697 }
1698
1699 public String[] getPackagesForUid(int uid) {
1700 synchronized (mPackages) {
1701 Object obj = mSettings.getUserIdLP(uid);
1702 if (obj instanceof SharedUserSetting) {
1703 SharedUserSetting sus = (SharedUserSetting)obj;
1704 final int N = sus.packages.size();
1705 String[] res = new String[N];
1706 Iterator<PackageSetting> it = sus.packages.iterator();
1707 int i=0;
1708 while (it.hasNext()) {
1709 res[i++] = it.next().name;
1710 }
1711 return res;
1712 } else if (obj instanceof PackageSetting) {
1713 PackageSetting ps = (PackageSetting)obj;
1714 return new String[] { ps.name };
1715 }
1716 }
1717 return null;
1718 }
1719
1720 public String getNameForUid(int uid) {
1721 synchronized (mPackages) {
1722 Object obj = mSettings.getUserIdLP(uid);
1723 if (obj instanceof SharedUserSetting) {
1724 SharedUserSetting sus = (SharedUserSetting)obj;
1725 return sus.name + ":" + sus.userId;
1726 } else if (obj instanceof PackageSetting) {
1727 PackageSetting ps = (PackageSetting)obj;
1728 return ps.name;
1729 }
1730 }
1731 return null;
1732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 public int getUidForSharedUser(String sharedUserName) {
1735 if(sharedUserName == null) {
1736 return -1;
1737 }
1738 synchronized (mPackages) {
1739 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1740 if(suid == null) {
1741 return -1;
1742 }
1743 return suid.userId;
1744 }
1745 }
1746
1747 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1748 int flags) {
1749 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001750 return chooseBestActivity(intent, resolvedType, flags, query);
1751 }
1752
Mihai Predaeae850c2009-05-13 10:13:48 +02001753 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1754 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 if (query != null) {
1756 final int N = query.size();
1757 if (N == 1) {
1758 return query.get(0);
1759 } else if (N > 1) {
1760 // If there is more than one activity with the same priority,
1761 // then let the user decide between them.
1762 ResolveInfo r0 = query.get(0);
1763 ResolveInfo r1 = query.get(1);
1764 if (false) {
1765 System.out.println(r0.activityInfo.name +
1766 "=" + r0.priority + " vs " +
1767 r1.activityInfo.name +
1768 "=" + r1.priority);
1769 }
1770 // If the first activity has a higher priority, or a different
1771 // default, then it is always desireable to pick it.
1772 if (r0.priority != r1.priority
1773 || r0.preferredOrder != r1.preferredOrder
1774 || r0.isDefault != r1.isDefault) {
1775 return query.get(0);
1776 }
1777 // If we have saved a preference for a preferred activity for
1778 // this Intent, use that.
1779 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1780 flags, query, r0.priority);
1781 if (ri != null) {
1782 return ri;
1783 }
1784 return mResolveInfo;
1785 }
1786 }
1787 return null;
1788 }
1789
1790 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1791 int flags, List<ResolveInfo> query, int priority) {
1792 synchronized (mPackages) {
1793 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1794 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001795 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1797 if (prefs != null && prefs.size() > 0) {
1798 // First figure out how good the original match set is.
1799 // We will only allow preferred activities that came
1800 // from the same match quality.
1801 int match = 0;
1802 final int N = query.size();
1803 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1804 for (int j=0; j<N; j++) {
1805 ResolveInfo ri = query.get(j);
1806 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1807 + ": 0x" + Integer.toHexString(match));
1808 if (ri.match > match) match = ri.match;
1809 }
1810 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1811 + Integer.toHexString(match));
1812 match &= IntentFilter.MATCH_CATEGORY_MASK;
1813 final int M = prefs.size();
1814 for (int i=0; i<M; i++) {
1815 PreferredActivity pa = prefs.get(i);
1816 if (pa.mMatch != match) {
1817 continue;
1818 }
1819 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1820 if (DEBUG_PREFERRED) {
1821 Log.v(TAG, "Got preferred activity:");
1822 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1823 }
1824 if (ai != null) {
1825 for (int j=0; j<N; j++) {
1826 ResolveInfo ri = query.get(j);
1827 if (!ri.activityInfo.applicationInfo.packageName
1828 .equals(ai.applicationInfo.packageName)) {
1829 continue;
1830 }
1831 if (!ri.activityInfo.name.equals(ai.name)) {
1832 continue;
1833 }
1834
1835 // Okay we found a previously set preferred app.
1836 // If the result set is different from when this
1837 // was created, we need to clear it and re-ask the
1838 // user their preference.
1839 if (!pa.sameSet(query, priority)) {
1840 Log.i(TAG, "Result set changed, dropping preferred activity for "
1841 + intent + " type " + resolvedType);
1842 mSettings.mPreferredActivities.removeFilter(pa);
1843 return null;
1844 }
1845
1846 // Yay!
1847 return ri;
1848 }
1849 }
1850 }
1851 }
1852 }
1853 return null;
1854 }
1855
1856 public List<ResolveInfo> queryIntentActivities(Intent intent,
1857 String resolvedType, int flags) {
1858 ComponentName comp = intent.getComponent();
1859 if (comp != null) {
1860 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1861 ActivityInfo ai = getActivityInfo(comp, flags);
1862 if (ai != null) {
1863 ResolveInfo ri = new ResolveInfo();
1864 ri.activityInfo = ai;
1865 list.add(ri);
1866 }
1867 return list;
1868 }
1869
1870 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001871 String pkgName = intent.getPackage();
1872 if (pkgName == null) {
1873 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1874 resolvedType, flags);
1875 }
1876 PackageParser.Package pkg = mPackages.get(pkgName);
1877 if (pkg != null) {
1878 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1879 resolvedType, flags, pkg.activities);
1880 }
1881 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 }
1883 }
1884
1885 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1886 Intent[] specifics, String[] specificTypes, Intent intent,
1887 String resolvedType, int flags) {
1888 final String resultsAction = intent.getAction();
1889
1890 List<ResolveInfo> results = queryIntentActivities(
1891 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1892 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1893
1894 int specificsPos = 0;
1895 int N;
1896
1897 // todo: note that the algorithm used here is O(N^2). This
1898 // isn't a problem in our current environment, but if we start running
1899 // into situations where we have more than 5 or 10 matches then this
1900 // should probably be changed to something smarter...
1901
1902 // First we go through and resolve each of the specific items
1903 // that were supplied, taking care of removing any corresponding
1904 // duplicate items in the generic resolve list.
1905 if (specifics != null) {
1906 for (int i=0; i<specifics.length; i++) {
1907 final Intent sintent = specifics[i];
1908 if (sintent == null) {
1909 continue;
1910 }
1911
1912 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1913 String action = sintent.getAction();
1914 if (resultsAction != null && resultsAction.equals(action)) {
1915 // If this action was explicitly requested, then don't
1916 // remove things that have it.
1917 action = null;
1918 }
1919 ComponentName comp = sintent.getComponent();
1920 ResolveInfo ri = null;
1921 ActivityInfo ai = null;
1922 if (comp == null) {
1923 ri = resolveIntent(
1924 sintent,
1925 specificTypes != null ? specificTypes[i] : null,
1926 flags);
1927 if (ri == null) {
1928 continue;
1929 }
1930 if (ri == mResolveInfo) {
1931 // ACK! Must do something better with this.
1932 }
1933 ai = ri.activityInfo;
1934 comp = new ComponentName(ai.applicationInfo.packageName,
1935 ai.name);
1936 } else {
1937 ai = getActivityInfo(comp, flags);
1938 if (ai == null) {
1939 continue;
1940 }
1941 }
1942
1943 // Look for any generic query activities that are duplicates
1944 // of this specific one, and remove them from the results.
1945 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1946 N = results.size();
1947 int j;
1948 for (j=specificsPos; j<N; j++) {
1949 ResolveInfo sri = results.get(j);
1950 if ((sri.activityInfo.name.equals(comp.getClassName())
1951 && sri.activityInfo.applicationInfo.packageName.equals(
1952 comp.getPackageName()))
1953 || (action != null && sri.filter.matchAction(action))) {
1954 results.remove(j);
1955 if (Config.LOGV) Log.v(
1956 TAG, "Removing duplicate item from " + j
1957 + " due to specific " + specificsPos);
1958 if (ri == null) {
1959 ri = sri;
1960 }
1961 j--;
1962 N--;
1963 }
1964 }
1965
1966 // Add this specific item to its proper place.
1967 if (ri == null) {
1968 ri = new ResolveInfo();
1969 ri.activityInfo = ai;
1970 }
1971 results.add(specificsPos, ri);
1972 ri.specificIndex = i;
1973 specificsPos++;
1974 }
1975 }
1976
1977 // Now we go through the remaining generic results and remove any
1978 // duplicate actions that are found here.
1979 N = results.size();
1980 for (int i=specificsPos; i<N-1; i++) {
1981 final ResolveInfo rii = results.get(i);
1982 if (rii.filter == null) {
1983 continue;
1984 }
1985
1986 // Iterate over all of the actions of this result's intent
1987 // filter... typically this should be just one.
1988 final Iterator<String> it = rii.filter.actionsIterator();
1989 if (it == null) {
1990 continue;
1991 }
1992 while (it.hasNext()) {
1993 final String action = it.next();
1994 if (resultsAction != null && resultsAction.equals(action)) {
1995 // If this action was explicitly requested, then don't
1996 // remove things that have it.
1997 continue;
1998 }
1999 for (int j=i+1; j<N; j++) {
2000 final ResolveInfo rij = results.get(j);
2001 if (rij.filter != null && rij.filter.hasAction(action)) {
2002 results.remove(j);
2003 if (Config.LOGV) Log.v(
2004 TAG, "Removing duplicate item from " + j
2005 + " due to action " + action + " at " + i);
2006 j--;
2007 N--;
2008 }
2009 }
2010 }
2011
2012 // If the caller didn't request filter information, drop it now
2013 // so we don't have to marshall/unmarshall it.
2014 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2015 rii.filter = null;
2016 }
2017 }
2018
2019 // Filter out the caller activity if so requested.
2020 if (caller != null) {
2021 N = results.size();
2022 for (int i=0; i<N; i++) {
2023 ActivityInfo ainfo = results.get(i).activityInfo;
2024 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2025 && caller.getClassName().equals(ainfo.name)) {
2026 results.remove(i);
2027 break;
2028 }
2029 }
2030 }
2031
2032 // If the caller didn't request filter information,
2033 // drop them now so we don't have to
2034 // marshall/unmarshall it.
2035 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2036 N = results.size();
2037 for (int i=0; i<N; i++) {
2038 results.get(i).filter = null;
2039 }
2040 }
2041
2042 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2043 return results;
2044 }
2045
2046 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2047 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002048 ComponentName comp = intent.getComponent();
2049 if (comp != null) {
2050 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2051 ActivityInfo ai = getReceiverInfo(comp, flags);
2052 if (ai != null) {
2053 ResolveInfo ri = new ResolveInfo();
2054 ri.activityInfo = ai;
2055 list.add(ri);
2056 }
2057 return list;
2058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002061 String pkgName = intent.getPackage();
2062 if (pkgName == null) {
2063 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2064 resolvedType, flags);
2065 }
2066 PackageParser.Package pkg = mPackages.get(pkgName);
2067 if (pkg != null) {
2068 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2069 resolvedType, flags, pkg.receivers);
2070 }
2071 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072 }
2073 }
2074
2075 public ResolveInfo resolveService(Intent intent, String resolvedType,
2076 int flags) {
2077 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2078 flags);
2079 if (query != null) {
2080 if (query.size() >= 1) {
2081 // If there is more than one service with the same priority,
2082 // just arbitrarily pick the first one.
2083 return query.get(0);
2084 }
2085 }
2086 return null;
2087 }
2088
2089 public List<ResolveInfo> queryIntentServices(Intent intent,
2090 String resolvedType, int flags) {
2091 ComponentName comp = intent.getComponent();
2092 if (comp != null) {
2093 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2094 ServiceInfo si = getServiceInfo(comp, flags);
2095 if (si != null) {
2096 ResolveInfo ri = new ResolveInfo();
2097 ri.serviceInfo = si;
2098 list.add(ri);
2099 }
2100 return list;
2101 }
2102
2103 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002104 String pkgName = intent.getPackage();
2105 if (pkgName == null) {
2106 return (List<ResolveInfo>)mServices.queryIntent(intent,
2107 resolvedType, flags);
2108 }
2109 PackageParser.Package pkg = mPackages.get(pkgName);
2110 if (pkg != null) {
2111 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2112 resolvedType, flags, pkg.services);
2113 }
2114 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 }
2116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 public List<PackageInfo> getInstalledPackages(int flags) {
2119 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2120
2121 synchronized (mPackages) {
2122 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2123 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2124 while (i.hasNext()) {
2125 final PackageSetting ps = i.next();
2126 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2127 if(psPkg != null) {
2128 finalList.add(psPkg);
2129 }
2130 }
2131 }
2132 else {
2133 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2134 while (i.hasNext()) {
2135 final PackageParser.Package p = i.next();
2136 if (p.applicationInfo != null) {
2137 PackageInfo pi = generatePackageInfo(p, flags);
2138 if(pi != null) {
2139 finalList.add(pi);
2140 }
2141 }
2142 }
2143 }
2144 }
2145 return finalList;
2146 }
2147
2148 public List<ApplicationInfo> getInstalledApplications(int flags) {
2149 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2150 synchronized(mPackages) {
2151 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2152 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2153 while (i.hasNext()) {
2154 final PackageSetting ps = i.next();
2155 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2156 if(ai != null) {
2157 finalList.add(ai);
2158 }
2159 }
2160 }
2161 else {
2162 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2163 while (i.hasNext()) {
2164 final PackageParser.Package p = i.next();
2165 if (p.applicationInfo != null) {
2166 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2167 if(ai != null) {
2168 finalList.add(ai);
2169 }
2170 }
2171 }
2172 }
2173 }
2174 return finalList;
2175 }
2176
2177 public List<ApplicationInfo> getPersistentApplications(int flags) {
2178 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2179
2180 synchronized (mPackages) {
2181 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2182 while (i.hasNext()) {
2183 PackageParser.Package p = i.next();
2184 if (p.applicationInfo != null
2185 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2186 && (!mSafeMode || (p.applicationInfo.flags
2187 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2188 finalList.add(p.applicationInfo);
2189 }
2190 }
2191 }
2192
2193 return finalList;
2194 }
2195
2196 public ProviderInfo resolveContentProvider(String name, int flags) {
2197 synchronized (mPackages) {
2198 final PackageParser.Provider provider = mProviders.get(name);
2199 return provider != null
2200 && mSettings.isEnabledLP(provider.info, flags)
2201 && (!mSafeMode || (provider.info.applicationInfo.flags
2202 &ApplicationInfo.FLAG_SYSTEM) != 0)
2203 ? PackageParser.generateProviderInfo(provider, flags)
2204 : null;
2205 }
2206 }
2207
Fred Quintana718d8a22009-04-29 17:53:20 -07002208 /**
2209 * @deprecated
2210 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 public void querySyncProviders(List outNames, List outInfo) {
2212 synchronized (mPackages) {
2213 Iterator<Map.Entry<String, PackageParser.Provider>> i
2214 = mProviders.entrySet().iterator();
2215
2216 while (i.hasNext()) {
2217 Map.Entry<String, PackageParser.Provider> entry = i.next();
2218 PackageParser.Provider p = entry.getValue();
2219
2220 if (p.syncable
2221 && (!mSafeMode || (p.info.applicationInfo.flags
2222 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2223 outNames.add(entry.getKey());
2224 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2225 }
2226 }
2227 }
2228 }
2229
2230 public List<ProviderInfo> queryContentProviders(String processName,
2231 int uid, int flags) {
2232 ArrayList<ProviderInfo> finalList = null;
2233
2234 synchronized (mPackages) {
2235 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2236 while (i.hasNext()) {
2237 PackageParser.Provider p = i.next();
2238 if (p.info.authority != null
2239 && (processName == null ||
2240 (p.info.processName.equals(processName)
2241 && p.info.applicationInfo.uid == uid))
2242 && mSettings.isEnabledLP(p.info, flags)
2243 && (!mSafeMode || (p.info.applicationInfo.flags
2244 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2245 if (finalList == null) {
2246 finalList = new ArrayList<ProviderInfo>(3);
2247 }
2248 finalList.add(PackageParser.generateProviderInfo(p,
2249 flags));
2250 }
2251 }
2252 }
2253
2254 if (finalList != null) {
2255 Collections.sort(finalList, mProviderInitOrderSorter);
2256 }
2257
2258 return finalList;
2259 }
2260
2261 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2262 int flags) {
2263 synchronized (mPackages) {
2264 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2265 return PackageParser.generateInstrumentationInfo(i, flags);
2266 }
2267 }
2268
2269 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2270 int flags) {
2271 ArrayList<InstrumentationInfo> finalList =
2272 new ArrayList<InstrumentationInfo>();
2273
2274 synchronized (mPackages) {
2275 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2276 while (i.hasNext()) {
2277 PackageParser.Instrumentation p = i.next();
2278 if (targetPackage == null
2279 || targetPackage.equals(p.info.targetPackage)) {
2280 finalList.add(PackageParser.generateInstrumentationInfo(p,
2281 flags));
2282 }
2283 }
2284 }
2285
2286 return finalList;
2287 }
2288
2289 private void scanDirLI(File dir, int flags, int scanMode) {
2290 Log.d(TAG, "Scanning app dir " + dir);
2291
2292 String[] files = dir.list();
2293
2294 int i;
2295 for (i=0; i<files.length; i++) {
2296 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002297 if (!isPackageFilename(files[i])) {
2298 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002299 continue;
2300 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002301 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002303 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002304 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2305 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002306 // Delete the apk
2307 Log.w(TAG, "Cleaning up failed install of " + file);
2308 file.delete();
2309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311 }
2312
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002313 private static File getSettingsProblemFile() {
2314 File dataDir = Environment.getDataDirectory();
2315 File systemDir = new File(dataDir, "system");
2316 File fname = new File(systemDir, "uiderrors.txt");
2317 return fname;
2318 }
2319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 private static void reportSettingsProblem(int priority, String msg) {
2321 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002322 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 FileOutputStream out = new FileOutputStream(fname, true);
2324 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002325 SimpleDateFormat formatter = new SimpleDateFormat();
2326 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2327 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002328 pw.close();
2329 FileUtils.setPermissions(
2330 fname.toString(),
2331 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2332 -1, -1);
2333 } catch (java.io.IOException e) {
2334 }
2335 Log.println(priority, TAG, msg);
2336 }
2337
2338 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2339 PackageParser.Package pkg, File srcFile, int parseFlags) {
2340 if (GET_CERTIFICATES) {
2341 if (ps == null || !ps.codePath.equals(srcFile)
2342 || ps.getTimeStamp() != srcFile.lastModified()) {
2343 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2344 if (!pp.collectCertificates(pkg, parseFlags)) {
2345 mLastScanError = pp.getParseError();
2346 return false;
2347 }
2348 }
2349 }
2350 return true;
2351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 /*
2354 * Scan a package and return the newly parsed package.
2355 * Returns null in case of errors and the error code is stored in mLastScanError
2356 */
2357 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002358 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002360 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002362 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002365 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (pkg == null) {
2367 mLastScanError = pp.getParseError();
2368 return null;
2369 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002370 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002371 PackageSetting updatedPkg;
2372 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002373 // Look to see if we already know about this package.
2374 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002375 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002376 // This package has been renamed to its original name. Let's
2377 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002378 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002379 }
2380 // If there was no original package, see one for the real package name.
2381 if (ps == null) {
2382 ps = mSettings.peekPackageLP(pkg.packageName);
2383 }
2384 // Check to see if this package could be hiding/updating a system
2385 // package. Must look for it either under the original or real
2386 // package name depending on our state.
2387 updatedPkg = mSettings.mDisabledSysPackages.get(
2388 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002390 // First check if this is a system package that may involve an update
2391 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2392 if (!ps.codePath.equals(scanFile)) {
2393 // The path has changed from what was last scanned... check the
2394 // version of the new path against what we have stored to determine
2395 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002396 if (pkg.mVersionCode < ps.versionCode) {
2397 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002398 // Ignore entry. Skip it.
2399 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2400 + "ignored: updated version " + ps.versionCode
2401 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002402 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2403 return null;
2404 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002405 // The current app on the system partion is better than
2406 // what we have updated to on the data partition; switch
2407 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002408 // At this point, its safely assumed that package installation for
2409 // apps in system partition will go through. If not there won't be a working
2410 // version of the app
2411 synchronized (mPackages) {
2412 // Just remove the loaded entries from package lists.
2413 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002414 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002415 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2416 + "reverting from " + ps.codePathString
2417 + ": new version " + pkg.mVersionCode
2418 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002419 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2420 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002421 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 }
2424 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002425 if (updatedPkg != null) {
2426 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2427 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2428 }
2429 // Verify certificates against what was last scanned
2430 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2431 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2432 return null;
2433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002434 // The apk is forward locked (not public) if its code and resources
2435 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002436 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002438 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002439 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002440
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002441 String codePath = null;
2442 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002443 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2444 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002445 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002446 } else {
2447 // Should not happen at all. Just log an error.
2448 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2449 }
2450 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002451 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002452 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002453 codePath = pkg.mScanPath;
2454 // Set application objects path explicitly.
2455 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002457 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 }
2459
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002460 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2461 String destCodePath, String destResPath) {
2462 pkg.mPath = pkg.mScanPath = destCodePath;
2463 pkg.applicationInfo.sourceDir = destCodePath;
2464 pkg.applicationInfo.publicSourceDir = destResPath;
2465 }
2466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 private static String fixProcessName(String defProcessName,
2468 String processName, int uid) {
2469 if (processName == null) {
2470 return defProcessName;
2471 }
2472 return processName;
2473 }
2474
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002475 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2477 if (pkg.mSignatures != null) {
2478 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2479 updateSignature)) {
2480 Log.e(TAG, "Package " + pkg.packageName
2481 + " signatures do not match the previously installed version; ignoring!");
2482 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2483 return false;
2484 }
2485
2486 if (pkgSetting.sharedUser != null) {
2487 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2488 pkg.mSignatures, updateSignature)) {
2489 Log.e(TAG, "Package " + pkg.packageName
2490 + " has no signatures that match those in shared user "
2491 + pkgSetting.sharedUser.name + "; ignoring!");
2492 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2493 return false;
2494 }
2495 }
2496 } else {
2497 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2498 }
2499 return true;
2500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002501
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002502 public boolean performDexOpt(String packageName) {
2503 if (!mNoDexOpt) {
2504 return false;
2505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002506
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002507 PackageParser.Package p;
2508 synchronized (mPackages) {
2509 p = mPackages.get(packageName);
2510 if (p == null || p.mDidDexOpt) {
2511 return false;
2512 }
2513 }
2514 synchronized (mInstallLock) {
2515 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2516 }
2517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002518
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002519 static final int DEX_OPT_SKIPPED = 0;
2520 static final int DEX_OPT_PERFORMED = 1;
2521 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002522
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002523 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2524 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002525 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002526 String path = pkg.mScanPath;
2527 int ret = 0;
2528 try {
2529 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002530 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002531 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002532 pkg.mDidDexOpt = true;
2533 performed = true;
2534 }
2535 } catch (FileNotFoundException e) {
2536 Log.w(TAG, "Apk not found for dexopt: " + path);
2537 ret = -1;
2538 } catch (IOException e) {
2539 Log.w(TAG, "Exception reading apk: " + path, e);
2540 ret = -1;
2541 }
2542 if (ret < 0) {
2543 //error from installer
2544 return DEX_OPT_FAILED;
2545 }
2546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002547
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002548 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2549 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002550
2551 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2552 return Environment.isEncryptedFilesystemEnabled() &&
2553 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2554 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002555
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002556 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2557 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2558 Log.w(TAG, "Unable to update from " + oldPkg.name
2559 + " to " + newPkg.packageName
2560 + ": old package not in system partition");
2561 return false;
2562 } else if (mPackages.get(oldPkg.name) != null) {
2563 Log.w(TAG, "Unable to update from " + oldPkg.name
2564 + " to " + newPkg.packageName
2565 + ": old package still exists");
2566 return false;
2567 }
2568 return true;
2569 }
2570
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002571 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2572 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002573 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002574 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2575 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002576 // Bail out. The resource and code paths haven't been set.
2577 Log.w(TAG, " Code and resource paths haven't been set correctly");
2578 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2579 return null;
2580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 mScanningPath = scanFile;
2582 if (pkg == null) {
2583 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2584 return null;
2585 }
2586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2588 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2589 }
2590
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 synchronized (mPackages) {
2593 if (mAndroidApplication != null) {
2594 Log.w(TAG, "*************************************************");
2595 Log.w(TAG, "Core android package being redefined. Skipping.");
2596 Log.w(TAG, " file=" + mScanningPath);
2597 Log.w(TAG, "*************************************************");
2598 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2599 return null;
2600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 // Set up information for our fall-back user intent resolution
2603 // activity.
2604 mPlatformPackage = pkg;
2605 pkg.mVersionCode = mSdkVersion;
2606 mAndroidApplication = pkg.applicationInfo;
2607 mResolveActivity.applicationInfo = mAndroidApplication;
2608 mResolveActivity.name = ResolverActivity.class.getName();
2609 mResolveActivity.packageName = mAndroidApplication.packageName;
2610 mResolveActivity.processName = mAndroidApplication.processName;
2611 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2612 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2613 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2614 mResolveActivity.exported = true;
2615 mResolveActivity.enabled = true;
2616 mResolveInfo.activityInfo = mResolveActivity;
2617 mResolveInfo.priority = 0;
2618 mResolveInfo.preferredOrder = 0;
2619 mResolveInfo.match = 0;
2620 mResolveComponentName = new ComponentName(
2621 mAndroidApplication.packageName, mResolveActivity.name);
2622 }
2623 }
2624
2625 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002626 TAG, "Scanning package " + pkg.packageName);
2627 if (mPackages.containsKey(pkg.packageName)
2628 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 + " already installed. Skipping duplicate.");
2632 Log.w(TAG, "*************************************************");
2633 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2634 return null;
2635 }
2636
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002637 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002638 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2639 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 SharedUserSetting suid = null;
2642 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002645
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002646 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2647 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002648 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002649 pkg.mRealPackage = null;
2650 pkg.mAdoptPermissions = null;
2651 }
2652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 synchronized (mPackages) {
2654 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002655 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2656 if (mTmpSharedLibraries == null ||
2657 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2658 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2659 }
2660 int num = 0;
2661 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2662 for (int i=0; i<N; i++) {
2663 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 if (file == null) {
2665 Log.e(TAG, "Package " + pkg.packageName
2666 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002667 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2669 return null;
2670 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002671 mTmpSharedLibraries[num] = file;
2672 num++;
2673 }
2674 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2675 for (int i=0; i<N; i++) {
2676 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2677 if (file == null) {
2678 Log.w(TAG, "Package " + pkg.packageName
2679 + " desires unavailable shared library "
2680 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2681 } else {
2682 mTmpSharedLibraries[num] = file;
2683 num++;
2684 }
2685 }
2686 if (num > 0) {
2687 pkg.usesLibraryFiles = new String[num];
2688 System.arraycopy(mTmpSharedLibraries, 0,
2689 pkg.usesLibraryFiles, 0, num);
2690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002691
Dianne Hackborn49237342009-08-27 20:08:01 -07002692 if (pkg.reqFeatures != null) {
2693 N = pkg.reqFeatures.size();
2694 for (int i=0; i<N; i++) {
2695 FeatureInfo fi = pkg.reqFeatures.get(i);
2696 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2697 // Don't care.
2698 continue;
2699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002700
Dianne Hackborn49237342009-08-27 20:08:01 -07002701 if (fi.name != null) {
2702 if (mAvailableFeatures.get(fi.name) == null) {
2703 Log.e(TAG, "Package " + pkg.packageName
2704 + " requires unavailable feature "
2705 + fi.name + "; failing!");
2706 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2707 return null;
2708 }
2709 }
2710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
2712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 if (pkg.mSharedUserId != null) {
2715 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2716 pkg.applicationInfo.flags, true);
2717 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002718 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 + " for shared user failed");
2720 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2721 return null;
2722 }
2723 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2724 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2725 + suid.userId + "): packages=" + suid.packages);
2726 }
2727 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002728
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002729 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002730 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002731 Log.w(TAG, "WAITING FOR DEBUGGER");
2732 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002733 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2734 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002735 }
2736 }
2737
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002738 // Check if we are renaming from an original package name.
2739 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002740 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002741 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002742 // This package may need to be renamed to a previously
2743 // installed name. Let's check on that...
2744 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002745 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002746 // This package had originally been installed as the
2747 // original name, and we have already taken care of
2748 // transitioning to the new one. Just update the new
2749 // one to continue using the old name.
2750 realName = pkg.mRealPackage;
2751 if (!pkg.packageName.equals(renamed)) {
2752 // Callers into this function may have already taken
2753 // care of renaming the package; only do it here if
2754 // it is not already done.
2755 pkg.setPackageName(renamed);
2756 }
2757
Dianne Hackbornc1552392010-03-03 16:19:01 -08002758 } else {
2759 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2760 if ((origPackage=mSettings.peekPackageLP(
2761 pkg.mOriginalPackages.get(i))) != null) {
2762 // We do have the package already installed under its
2763 // original name... should we use it?
2764 if (!verifyPackageUpdate(origPackage, pkg)) {
2765 // New package is not compatible with original.
2766 origPackage = null;
2767 continue;
2768 } else if (origPackage.sharedUser != null) {
2769 // Make sure uid is compatible between packages.
2770 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2771 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2772 + " to " + pkg.packageName + ": old uid "
2773 + origPackage.sharedUser.name
2774 + " differs from " + pkg.mSharedUserId);
2775 origPackage = null;
2776 continue;
2777 }
2778 } else {
2779 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2780 + pkg.packageName + " to old name " + origPackage.name);
2781 }
2782 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002784 }
2785 }
2786 }
2787
2788 if (mTransferedPackages.contains(pkg.packageName)) {
2789 Log.w(TAG, "Package " + pkg.packageName
2790 + " was transferred to another, but its .apk remains");
2791 }
2792
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002793 // Just create the setting, don't add it yet. For already existing packages
2794 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002795 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 destResourceFile, pkg.applicationInfo.flags, true, false);
2797 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002798 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2800 return null;
2801 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002802
2803 if (pkgSetting.origPackage != null) {
2804 // If we are first transitioning from an original package,
2805 // fix up the new package's name now. We need to do this after
2806 // looking up the package under its new name, so getPackageLP
2807 // can take care of fiddling things correctly.
2808 pkg.setPackageName(origPackage.name);
2809
2810 // File a report about this.
2811 String msg = "New package " + pkgSetting.realName
2812 + " renamed to replace old package " + pkgSetting.name;
2813 reportSettingsProblem(Log.WARN, msg);
2814
2815 // Make a note of it.
2816 mTransferedPackages.add(origPackage.name);
2817
2818 // No longer need to retain this.
2819 pkgSetting.origPackage = null;
2820 }
2821
2822 if (realName != null) {
2823 // Make a note of it.
2824 mTransferedPackages.add(pkg.packageName);
2825 }
2826
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002827 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 pkg.applicationInfo.uid = pkgSetting.userId;
2832 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002833
2834 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2836 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2837 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2838 return null;
2839 }
2840 // The signature has changed, but this package is in the system
2841 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002842 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 // However... if this package is part of a shared user, but it
2844 // doesn't match the signature of the shared user, let's fail.
2845 // What this means is that you can't change the signatures
2846 // associated with an overall shared user, which doesn't seem all
2847 // that unreasonable.
2848 if (pkgSetting.sharedUser != null) {
2849 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2850 pkg.mSignatures, false)) {
2851 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2852 return null;
2853 }
2854 }
2855 removeExisting = true;
2856 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002857
The Android Open Source Project10592532009-03-18 17:39:46 -07002858 // Verify that this new package doesn't have any content providers
2859 // that conflict with existing packages. Only do this if the
2860 // package isn't already installed, since we don't want to break
2861 // things that are installed.
2862 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2863 int N = pkg.providers.size();
2864 int i;
2865 for (i=0; i<N; i++) {
2866 PackageParser.Provider p = pkg.providers.get(i);
2867 String names[] = p.info.authority.split(";");
2868 for (int j = 0; j < names.length; j++) {
2869 if (mProviders.containsKey(names[j])) {
2870 PackageParser.Provider other = mProviders.get(names[j]);
2871 Log.w(TAG, "Can't install because provider name " + names[j] +
2872 " (in package " + pkg.applicationInfo.packageName +
2873 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002874 + ((other != null && other.getComponentName() != null)
2875 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002876 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2877 return null;
2878 }
2879 }
2880 }
2881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 }
2883
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002884 final String pkgName = pkg.packageName;
2885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002887 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002889 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 if (ret != 0) {
2891 String msg = "System package " + pkg.packageName
2892 + " could not have data directory erased after signature change.";
2893 reportSettingsProblem(Log.WARN, msg);
2894 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2895 return null;
2896 }
2897 }
2898 Log.w(TAG, "System package " + pkg.packageName
2899 + " signature changed: existing data removed.");
2900 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002902
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002903 if (pkg.mAdoptPermissions != null) {
2904 // This package wants to adopt ownership of permissions from
2905 // another package.
2906 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2907 String origName = pkg.mAdoptPermissions.get(i);
2908 PackageSetting orig = mSettings.peekPackageLP(origName);
2909 if (orig != null) {
2910 if (verifyPackageUpdate(orig, pkg)) {
2911 Log.i(TAG, "Adopting permissions from "
2912 + origName + " to " + pkg.packageName);
2913 mSettings.transferPermissions(origName, pkg.packageName);
2914 }
2915 }
2916 }
2917 }
2918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 long scanFileTime = scanFile.lastModified();
2920 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2921 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2922 pkg.applicationInfo.processName = fixProcessName(
2923 pkg.applicationInfo.packageName,
2924 pkg.applicationInfo.processName,
2925 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926
2927 File dataPath;
2928 if (mPlatformPackage == pkg) {
2929 // The system package is special.
2930 dataPath = new File (Environment.getDataDirectory(), "system");
2931 pkg.applicationInfo.dataDir = dataPath.getPath();
2932 } else {
2933 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002934 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2935 if (useEncryptedFSDir) {
2936 dataPath = new File(mSecureAppDataDir, pkgName);
2937 } else {
2938 dataPath = new File(mAppDataDir, pkgName);
2939 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002940
2941 boolean uidError = false;
2942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 if (dataPath.exists()) {
2944 mOutPermissions[1] = 0;
2945 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2946 if (mOutPermissions[1] == pkg.applicationInfo.uid
2947 || !Process.supportsProcesses()) {
2948 pkg.applicationInfo.dataDir = dataPath.getPath();
2949 } else {
2950 boolean recovered = false;
2951 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2952 // If this is a system app, we can at least delete its
2953 // current data so the application will still work.
2954 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002955 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002956 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 // Old data gone!
2958 String msg = "System package " + pkg.packageName
2959 + " has changed from uid: "
2960 + mOutPermissions[1] + " to "
2961 + pkg.applicationInfo.uid + "; old data erased";
2962 reportSettingsProblem(Log.WARN, msg);
2963 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002966 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 pkg.applicationInfo.uid);
2968 if (ret == -1) {
2969 // Ack should not happen!
2970 msg = "System package " + pkg.packageName
2971 + " could not have data directory re-created after delete.";
2972 reportSettingsProblem(Log.WARN, msg);
2973 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2974 return null;
2975 }
2976 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 if (!recovered) {
2979 mHasSystemUidErrors = true;
2980 }
2981 }
2982 if (!recovered) {
2983 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2984 + pkg.applicationInfo.uid + "/fs_"
2985 + mOutPermissions[1];
2986 String msg = "Package " + pkg.packageName
2987 + " has mismatched uid: "
2988 + mOutPermissions[1] + " on disk, "
2989 + pkg.applicationInfo.uid + " in settings";
2990 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002991 mSettings.mReadMessages.append(msg);
2992 mSettings.mReadMessages.append('\n');
2993 uidError = true;
2994 if (!pkgSetting.uidError) {
2995 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 }
2998 }
2999 }
3000 pkg.applicationInfo.dataDir = dataPath.getPath();
3001 } else {
3002 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3003 Log.v(TAG, "Want this data dir: " + dataPath);
3004 //invoke installer to do the actual installation
3005 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003006 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 pkg.applicationInfo.uid);
3008 if(ret < 0) {
3009 // Error from installer
3010 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3011 return null;
3012 }
3013 } else {
3014 dataPath.mkdirs();
3015 if (dataPath.exists()) {
3016 FileUtils.setPermissions(
3017 dataPath.toString(),
3018 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3019 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3020 }
3021 }
3022 if (dataPath.exists()) {
3023 pkg.applicationInfo.dataDir = dataPath.getPath();
3024 } else {
3025 Log.w(TAG, "Unable to create data directory: " + dataPath);
3026 pkg.applicationInfo.dataDir = null;
3027 }
3028 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003029
3030 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032
3033 // Perform shared library installation and dex validation and
3034 // optimization, if this is not a system app.
3035 if (mInstaller != null) {
3036 String path = scanFile.getPath();
3037 if (scanFileNewer) {
3038 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003039 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3040 if (err != PackageManager.INSTALL_SUCCEEDED) {
3041 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 return null;
3043 }
3044 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003045 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003046
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003047 if ((scanMode&SCAN_NO_DEX) == 0) {
3048 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3050 return null;
3051 }
3052 }
3053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 if (mFactoryTest && pkg.requestedPermissions.contains(
3056 android.Manifest.permission.FACTORY_TEST)) {
3057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3058 }
3059
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003060 // Request the ActivityManager to kill the process(only for existing packages)
3061 // so that we do not end up in a confused state while the user is still using the older
3062 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003063 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003064 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003065 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003066 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003069 // We don't expect installation to fail beyond this point,
3070 if ((scanMode&SCAN_MONITOR) != 0) {
3071 mAppDirs.put(pkg.mPath, pkg);
3072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003074 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003076 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003077 // Make sure we don't accidentally delete its data.
3078 mSettings.mPackagesToBeCleaned.remove(pkgName);
3079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 int N = pkg.providers.size();
3081 StringBuilder r = null;
3082 int i;
3083 for (i=0; i<N; i++) {
3084 PackageParser.Provider p = pkg.providers.get(i);
3085 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3086 p.info.processName, pkg.applicationInfo.uid);
3087 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3088 p.info.name), p);
3089 p.syncable = p.info.isSyncable;
3090 String names[] = p.info.authority.split(";");
3091 p.info.authority = null;
3092 for (int j = 0; j < names.length; j++) {
3093 if (j == 1 && p.syncable) {
3094 // We only want the first authority for a provider to possibly be
3095 // syncable, so if we already added this provider using a different
3096 // authority clear the syncable flag. We copy the provider before
3097 // changing it because the mProviders object contains a reference
3098 // to a provider that we don't want to change.
3099 // Only do this for the second authority since the resulting provider
3100 // object can be the same for all future authorities for this provider.
3101 p = new PackageParser.Provider(p);
3102 p.syncable = false;
3103 }
3104 if (!mProviders.containsKey(names[j])) {
3105 mProviders.put(names[j], p);
3106 if (p.info.authority == null) {
3107 p.info.authority = names[j];
3108 } else {
3109 p.info.authority = p.info.authority + ";" + names[j];
3110 }
3111 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3112 Log.d(TAG, "Registered content provider: " + names[j] +
3113 ", className = " + p.info.name +
3114 ", isSyncable = " + p.info.isSyncable);
3115 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003116 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 Log.w(TAG, "Skipping provider name " + names[j] +
3118 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07003119 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003120 + ((other != null && other.getComponentName() != null)
3121 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 }
3123 }
3124 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3125 if (r == null) {
3126 r = new StringBuilder(256);
3127 } else {
3128 r.append(' ');
3129 }
3130 r.append(p.info.name);
3131 }
3132 }
3133 if (r != null) {
3134 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3135 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 N = pkg.services.size();
3138 r = null;
3139 for (i=0; i<N; i++) {
3140 PackageParser.Service s = pkg.services.get(i);
3141 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3142 s.info.processName, pkg.applicationInfo.uid);
3143 mServices.addService(s);
3144 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3145 if (r == null) {
3146 r = new StringBuilder(256);
3147 } else {
3148 r.append(' ');
3149 }
3150 r.append(s.info.name);
3151 }
3152 }
3153 if (r != null) {
3154 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 N = pkg.receivers.size();
3158 r = null;
3159 for (i=0; i<N; i++) {
3160 PackageParser.Activity a = pkg.receivers.get(i);
3161 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3162 a.info.processName, pkg.applicationInfo.uid);
3163 mReceivers.addActivity(a, "receiver");
3164 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3165 if (r == null) {
3166 r = new StringBuilder(256);
3167 } else {
3168 r.append(' ');
3169 }
3170 r.append(a.info.name);
3171 }
3172 }
3173 if (r != null) {
3174 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 N = pkg.activities.size();
3178 r = null;
3179 for (i=0; i<N; i++) {
3180 PackageParser.Activity a = pkg.activities.get(i);
3181 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3182 a.info.processName, pkg.applicationInfo.uid);
3183 mActivities.addActivity(a, "activity");
3184 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3185 if (r == null) {
3186 r = new StringBuilder(256);
3187 } else {
3188 r.append(' ');
3189 }
3190 r.append(a.info.name);
3191 }
3192 }
3193 if (r != null) {
3194 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3195 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 N = pkg.permissionGroups.size();
3198 r = null;
3199 for (i=0; i<N; i++) {
3200 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3201 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3202 if (cur == null) {
3203 mPermissionGroups.put(pg.info.name, pg);
3204 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3205 if (r == null) {
3206 r = new StringBuilder(256);
3207 } else {
3208 r.append(' ');
3209 }
3210 r.append(pg.info.name);
3211 }
3212 } else {
3213 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3214 + pg.info.packageName + " ignored: original from "
3215 + cur.info.packageName);
3216 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3217 if (r == null) {
3218 r = new StringBuilder(256);
3219 } else {
3220 r.append(' ');
3221 }
3222 r.append("DUP:");
3223 r.append(pg.info.name);
3224 }
3225 }
3226 }
3227 if (r != null) {
3228 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3229 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 N = pkg.permissions.size();
3232 r = null;
3233 for (i=0; i<N; i++) {
3234 PackageParser.Permission p = pkg.permissions.get(i);
3235 HashMap<String, BasePermission> permissionMap =
3236 p.tree ? mSettings.mPermissionTrees
3237 : mSettings.mPermissions;
3238 p.group = mPermissionGroups.get(p.info.group);
3239 if (p.info.group == null || p.group != null) {
3240 BasePermission bp = permissionMap.get(p.info.name);
3241 if (bp == null) {
3242 bp = new BasePermission(p.info.name, p.info.packageName,
3243 BasePermission.TYPE_NORMAL);
3244 permissionMap.put(p.info.name, bp);
3245 }
3246 if (bp.perm == null) {
3247 if (bp.sourcePackage == null
3248 || bp.sourcePackage.equals(p.info.packageName)) {
3249 BasePermission tree = findPermissionTreeLP(p.info.name);
3250 if (tree == null
3251 || tree.sourcePackage.equals(p.info.packageName)) {
3252 bp.perm = p;
3253 bp.uid = pkg.applicationInfo.uid;
3254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3255 if (r == null) {
3256 r = new StringBuilder(256);
3257 } else {
3258 r.append(' ');
3259 }
3260 r.append(p.info.name);
3261 }
3262 } else {
3263 Log.w(TAG, "Permission " + p.info.name + " from package "
3264 + p.info.packageName + " ignored: base tree "
3265 + tree.name + " is from package "
3266 + tree.sourcePackage);
3267 }
3268 } else {
3269 Log.w(TAG, "Permission " + p.info.name + " from package "
3270 + p.info.packageName + " ignored: original from "
3271 + bp.sourcePackage);
3272 }
3273 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3274 if (r == null) {
3275 r = new StringBuilder(256);
3276 } else {
3277 r.append(' ');
3278 }
3279 r.append("DUP:");
3280 r.append(p.info.name);
3281 }
3282 } else {
3283 Log.w(TAG, "Permission " + p.info.name + " from package "
3284 + p.info.packageName + " ignored: no group "
3285 + p.group);
3286 }
3287 }
3288 if (r != null) {
3289 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 N = pkg.instrumentation.size();
3293 r = null;
3294 for (i=0; i<N; i++) {
3295 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3296 a.info.packageName = pkg.applicationInfo.packageName;
3297 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3298 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3299 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003300 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3302 if (r == null) {
3303 r = new StringBuilder(256);
3304 } else {
3305 r.append(' ');
3306 }
3307 r.append(a.info.name);
3308 }
3309 }
3310 if (r != null) {
3311 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003313
Dianne Hackborn854060af2009-07-09 18:14:31 -07003314 if (pkg.protectedBroadcasts != null) {
3315 N = pkg.protectedBroadcasts.size();
3316 for (i=0; i<N; i++) {
3317 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3318 }
3319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 pkgSetting.setTimeStamp(scanFileTime);
3322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 return pkg;
3325 }
3326
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003327 private void killApplication(String pkgName, int uid) {
3328 // Request the ActivityManager to kill the process(only for existing packages)
3329 // so that we do not end up in a confused state while the user is still using the older
3330 // version of the application while the new one gets installed.
3331 IActivityManager am = ActivityManagerNative.getDefault();
3332 if (am != null) {
3333 try {
3334 am.killApplicationWithUid(pkgName, uid);
3335 } catch (RemoteException e) {
3336 }
3337 }
3338 }
3339
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003340 // The following constants are returned by cachePackageSharedLibsForAbiLI
3341 // to indicate if native shared libraries were found in the package.
3342 // Values are:
3343 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3344 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3345 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3346 // in package (and not installed)
3347 //
3348 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3349 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3350 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003352 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3353 // and automatically copy them to /data/data/<appname>/lib if present.
3354 //
3355 // NOTE: this method may throw an IOException if the library cannot
3356 // be copied to its final destination, e.g. if there isn't enough
3357 // room left on the data partition, or a ZipException if the package
3358 // file is malformed.
3359 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003360 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3361 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003362 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3363 final String apkLib = "lib/";
3364 final int apkLibLen = apkLib.length();
3365 final int cpuAbiLen = cpuAbi.length();
3366 final String libPrefix = "lib";
3367 final int libPrefixLen = libPrefix.length();
3368 final String libSuffix = ".so";
3369 final int libSuffixLen = libSuffix.length();
3370 boolean hasNativeLibraries = false;
3371 boolean installedNativeLibraries = false;
3372
3373 // the minimum length of a valid native shared library of the form
3374 // lib/<something>/lib<name>.so.
3375 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3376
3377 ZipFile zipFile = new ZipFile(scanFile);
3378 Enumeration<ZipEntry> entries =
3379 (Enumeration<ZipEntry>) zipFile.entries();
3380
3381 while (entries.hasMoreElements()) {
3382 ZipEntry entry = entries.nextElement();
3383 // skip directories
3384 if (entry.isDirectory()) {
3385 continue;
3386 }
3387 String entryName = entry.getName();
3388
3389 // check that the entry looks like lib/<something>/lib<name>.so
3390 // here, but don't check the ABI just yet.
3391 //
3392 // - must be sufficiently long
3393 // - must end with libSuffix, i.e. ".so"
3394 // - must start with apkLib, i.e. "lib/"
3395 if (entryName.length() < minEntryLen ||
3396 !entryName.endsWith(libSuffix) ||
3397 !entryName.startsWith(apkLib) ) {
3398 continue;
3399 }
3400
3401 // file name must start with libPrefix, i.e. "lib"
3402 int lastSlash = entryName.lastIndexOf('/');
3403
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003404 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003405 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3406 continue;
3407 }
3408
3409 hasNativeLibraries = true;
3410
3411 // check the cpuAbi now, between lib/ and /lib<name>.so
3412 //
3413 if (lastSlash != apkLibLen + cpuAbiLen ||
3414 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3415 continue;
3416
3417 // extract the library file name, ensure it doesn't contain
3418 // weird characters. we're guaranteed here that it doesn't contain
3419 // a directory separator though.
3420 String libFileName = entryName.substring(lastSlash+1);
3421 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3422 continue;
3423 }
3424
3425 installedNativeLibraries = true;
3426
3427 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3428 File.separator + libFileName;
3429 File sharedLibraryFile = new File(sharedLibraryFilePath);
3430 if (! sharedLibraryFile.exists() ||
3431 sharedLibraryFile.length() != entry.getSize() ||
3432 sharedLibraryFile.lastModified() != entry.getTime()) {
3433 if (Config.LOGD) {
3434 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003436 if (mInstaller == null) {
3437 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003438 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003439 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003440 sharedLibraryFile);
3441 }
3442 }
3443 if (!hasNativeLibraries)
3444 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3445
3446 if (!installedNativeLibraries)
3447 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3448
3449 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3450 }
3451
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003452 // Find the gdbserver executable program in a package at
3453 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3454 //
3455 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3456 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3457 //
3458 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3459 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3460 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3461 final String GDBSERVER = "gdbserver";
3462 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3463
3464 ZipFile zipFile = new ZipFile(scanFile);
3465 Enumeration<ZipEntry> entries =
3466 (Enumeration<ZipEntry>) zipFile.entries();
3467
3468 while (entries.hasMoreElements()) {
3469 ZipEntry entry = entries.nextElement();
3470 // skip directories
3471 if (entry.isDirectory()) {
3472 continue;
3473 }
3474 String entryName = entry.getName();
3475
3476 if (!entryName.equals(apkGdbServerPath)) {
3477 continue;
3478 }
3479
3480 String installGdbServerPath = installGdbServerDir.getPath() +
3481 "/" + GDBSERVER;
3482 File installGdbServerFile = new File(installGdbServerPath);
3483 if (! installGdbServerFile.exists() ||
3484 installGdbServerFile.length() != entry.getSize() ||
3485 installGdbServerFile.lastModified() != entry.getTime()) {
3486 if (Config.LOGD) {
3487 Log.d(TAG, "Caching gdbserver " + entry.getName());
3488 }
3489 if (mInstaller == null) {
3490 installGdbServerDir.mkdir();
3491 }
3492 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3493 installGdbServerFile);
3494 }
3495 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3496 }
3497 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3498 }
3499
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003500 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3501 // and copy them to /data/data/<appname>/lib.
3502 //
3503 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3504 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3505 // one if ro.product.cpu.abi2 is defined.
3506 //
3507 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3508 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003509 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003510 try {
3511 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3512
3513 // some architectures are capable of supporting several CPU ABIs
3514 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3515 // this is indicated by the definition of the ro.product.cpu.abi2
3516 // system property.
3517 //
3518 // only scan the package twice in case of ABI mismatch
3519 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003520 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003521 if (cpuAbi2 != null) {
3522 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003524
3525 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3526 Log.w(TAG,"Native ABI mismatch from package file");
3527 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003529
3530 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3531 cpuAbi = cpuAbi2;
3532 }
3533 }
3534
3535 // for debuggable packages, also extract gdbserver from lib/<abi>
3536 // into /data/data/<appname>/lib too.
3537 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3538 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3539 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3540 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3541 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003544 } catch (ZipException e) {
3545 Log.w(TAG, "Failed to extract data from package file", e);
3546 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003548 Log.w(TAG, "Failed to cache package shared libs", e);
3549 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003551 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 }
3553
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003554 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003556 File binaryDir,
3557 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 InputStream inputStream = zipFile.getInputStream(entry);
3559 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003560 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003562 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 // now need to be left as world readable and owned by the system.
3564 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3565 ! tempFile.setLastModified(entry.getTime()) ||
3566 FileUtils.setPermissions(tempFilePath,
3567 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003568 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003570 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 // Failed to properly write file.
3572 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003573 throw new IOException("Couldn't create cached binary "
3574 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 }
3576 } finally {
3577 inputStream.close();
3578 }
3579 }
3580
3581 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3582 if (chatty && Config.LOGD) Log.d(
3583 TAG, "Removing package " + pkg.applicationInfo.packageName );
3584
3585 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 mPackages.remove(pkg.applicationInfo.packageName);
3589 if (pkg.mPath != null) {
3590 mAppDirs.remove(pkg.mPath);
3591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 PackageSetting ps = (PackageSetting)pkg.mExtras;
3594 if (ps != null && ps.sharedUser != null) {
3595 // XXX don't do this until the data is removed.
3596 if (false) {
3597 ps.sharedUser.packages.remove(ps);
3598 if (ps.sharedUser.packages.size() == 0) {
3599 // Remove.
3600 }
3601 }
3602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 int N = pkg.providers.size();
3605 StringBuilder r = null;
3606 int i;
3607 for (i=0; i<N; i++) {
3608 PackageParser.Provider p = pkg.providers.get(i);
3609 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3610 p.info.name));
3611 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 /* The is another ContentProvider with this authority when
3614 * this app was installed so this authority is null,
3615 * Ignore it as we don't have to unregister the provider.
3616 */
3617 continue;
3618 }
3619 String names[] = p.info.authority.split(";");
3620 for (int j = 0; j < names.length; j++) {
3621 if (mProviders.get(names[j]) == p) {
3622 mProviders.remove(names[j]);
3623 if (chatty && Config.LOGD) Log.d(
3624 TAG, "Unregistered content provider: " + names[j] +
3625 ", className = " + p.info.name +
3626 ", isSyncable = " + p.info.isSyncable);
3627 }
3628 }
3629 if (chatty) {
3630 if (r == null) {
3631 r = new StringBuilder(256);
3632 } else {
3633 r.append(' ');
3634 }
3635 r.append(p.info.name);
3636 }
3637 }
3638 if (r != null) {
3639 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 N = pkg.services.size();
3643 r = null;
3644 for (i=0; i<N; i++) {
3645 PackageParser.Service s = pkg.services.get(i);
3646 mServices.removeService(s);
3647 if (chatty) {
3648 if (r == null) {
3649 r = new StringBuilder(256);
3650 } else {
3651 r.append(' ');
3652 }
3653 r.append(s.info.name);
3654 }
3655 }
3656 if (r != null) {
3657 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 N = pkg.receivers.size();
3661 r = null;
3662 for (i=0; i<N; i++) {
3663 PackageParser.Activity a = pkg.receivers.get(i);
3664 mReceivers.removeActivity(a, "receiver");
3665 if (chatty) {
3666 if (r == null) {
3667 r = new StringBuilder(256);
3668 } else {
3669 r.append(' ');
3670 }
3671 r.append(a.info.name);
3672 }
3673 }
3674 if (r != null) {
3675 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 N = pkg.activities.size();
3679 r = null;
3680 for (i=0; i<N; i++) {
3681 PackageParser.Activity a = pkg.activities.get(i);
3682 mActivities.removeActivity(a, "activity");
3683 if (chatty) {
3684 if (r == null) {
3685 r = new StringBuilder(256);
3686 } else {
3687 r.append(' ');
3688 }
3689 r.append(a.info.name);
3690 }
3691 }
3692 if (r != null) {
3693 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 N = pkg.permissions.size();
3697 r = null;
3698 for (i=0; i<N; i++) {
3699 PackageParser.Permission p = pkg.permissions.get(i);
3700 boolean tree = false;
3701 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3702 if (bp == null) {
3703 tree = true;
3704 bp = mSettings.mPermissionTrees.get(p.info.name);
3705 }
3706 if (bp != null && bp.perm == p) {
3707 if (bp.type != BasePermission.TYPE_BUILTIN) {
3708 if (tree) {
3709 mSettings.mPermissionTrees.remove(p.info.name);
3710 } else {
3711 mSettings.mPermissions.remove(p.info.name);
3712 }
3713 } else {
3714 bp.perm = null;
3715 }
3716 if (chatty) {
3717 if (r == null) {
3718 r = new StringBuilder(256);
3719 } else {
3720 r.append(' ');
3721 }
3722 r.append(p.info.name);
3723 }
3724 }
3725 }
3726 if (r != null) {
3727 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 N = pkg.instrumentation.size();
3731 r = null;
3732 for (i=0; i<N; i++) {
3733 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003734 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 if (chatty) {
3736 if (r == null) {
3737 r = new StringBuilder(256);
3738 } else {
3739 r.append(' ');
3740 }
3741 r.append(a.info.name);
3742 }
3743 }
3744 if (r != null) {
3745 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3746 }
3747 }
3748 }
3749
3750 private static final boolean isPackageFilename(String name) {
3751 return name != null && name.endsWith(".apk");
3752 }
3753
3754 private void updatePermissionsLP() {
3755 // Make sure there are no dangling permission trees.
3756 Iterator<BasePermission> it = mSettings.mPermissionTrees
3757 .values().iterator();
3758 while (it.hasNext()) {
3759 BasePermission bp = it.next();
3760 if (bp.perm == null) {
3761 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3762 + " from package " + bp.sourcePackage);
3763 it.remove();
3764 }
3765 }
3766
3767 // Make sure all dynamic permissions have been assigned to a package,
3768 // and make sure there are no dangling permissions.
3769 it = mSettings.mPermissions.values().iterator();
3770 while (it.hasNext()) {
3771 BasePermission bp = it.next();
3772 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3773 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3774 + bp.name + " pkg=" + bp.sourcePackage
3775 + " info=" + bp.pendingInfo);
3776 if (bp.perm == null && bp.pendingInfo != null) {
3777 BasePermission tree = findPermissionTreeLP(bp.name);
3778 if (tree != null) {
3779 bp.perm = new PackageParser.Permission(tree.perm.owner,
3780 new PermissionInfo(bp.pendingInfo));
3781 bp.perm.info.packageName = tree.perm.info.packageName;
3782 bp.perm.info.name = bp.name;
3783 bp.uid = tree.uid;
3784 }
3785 }
3786 }
3787 if (bp.perm == null) {
3788 Log.w(TAG, "Removing dangling permission: " + bp.name
3789 + " from package " + bp.sourcePackage);
3790 it.remove();
3791 }
3792 }
3793
3794 // Now update the permissions for all packages, in particular
3795 // replace the granted permissions of the system packages.
3796 for (PackageParser.Package pkg : mPackages.values()) {
3797 grantPermissionsLP(pkg, false);
3798 }
3799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3802 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3803 if (ps == null) {
3804 return;
3805 }
3806 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3807 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 if (replace) {
3810 ps.permissionsFixed = false;
3811 if (gp == ps) {
3812 gp.grantedPermissions.clear();
3813 gp.gids = mGlobalGids;
3814 }
3815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 if (gp.gids == null) {
3818 gp.gids = mGlobalGids;
3819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 final int N = pkg.requestedPermissions.size();
3822 for (int i=0; i<N; i++) {
3823 String name = pkg.requestedPermissions.get(i);
3824 BasePermission bp = mSettings.mPermissions.get(name);
3825 PackageParser.Permission p = bp != null ? bp.perm : null;
3826 if (false) {
3827 if (gp != ps) {
3828 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3829 + ": " + p);
3830 }
3831 }
3832 if (p != null) {
3833 final String perm = p.info.name;
3834 boolean allowed;
3835 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3836 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3837 allowed = true;
3838 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3839 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003840 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003842 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003843 == PackageManager.SIGNATURE_MATCH);
3844 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3845 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3846 // For updated system applications, the signatureOrSystem permission
3847 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003848 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3850 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3851 if(sysPs.grantedPermissions.contains(perm)) {
3852 allowed = true;
3853 } else {
3854 allowed = false;
3855 }
3856 } else {
3857 allowed = true;
3858 }
3859 }
3860 }
3861 } else {
3862 allowed = false;
3863 }
3864 if (false) {
3865 if (gp != ps) {
3866 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3867 }
3868 }
3869 if (allowed) {
3870 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3871 && ps.permissionsFixed) {
3872 // If this is an existing, non-system package, then
3873 // we can't add any new permissions to it.
3874 if (!gp.loadedPermissions.contains(perm)) {
3875 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003876 // Except... if this is a permission that was added
3877 // to the platform (note: need to only do this when
3878 // updating the platform).
3879 final int NP = PackageParser.NEW_PERMISSIONS.length;
3880 for (int ip=0; ip<NP; ip++) {
3881 final PackageParser.NewPermissionInfo npi
3882 = PackageParser.NEW_PERMISSIONS[ip];
3883 if (npi.name.equals(perm)
3884 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3885 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003886 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003887 + pkg.packageName);
3888 break;
3889 }
3890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
3892 }
3893 if (allowed) {
3894 if (!gp.grantedPermissions.contains(perm)) {
3895 addedPermission = true;
3896 gp.grantedPermissions.add(perm);
3897 gp.gids = appendInts(gp.gids, bp.gids);
3898 }
3899 } else {
3900 Log.w(TAG, "Not granting permission " + perm
3901 + " to package " + pkg.packageName
3902 + " because it was previously installed without");
3903 }
3904 } else {
3905 Log.w(TAG, "Not granting permission " + perm
3906 + " to package " + pkg.packageName
3907 + " (protectionLevel=" + p.info.protectionLevel
3908 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3909 + ")");
3910 }
3911 } else {
3912 Log.w(TAG, "Unknown permission " + name
3913 + " in package " + pkg.packageName);
3914 }
3915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003918 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3919 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 // This is the first that we have heard about this package, so the
3921 // permissions we have now selected are fixed until explicitly
3922 // changed.
3923 ps.permissionsFixed = true;
3924 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3925 }
3926 }
3927
3928 private final class ActivityIntentResolver
3929 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003930 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003932 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 }
3934
Mihai Preda074edef2009-05-18 17:13:31 +02003935 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003937 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3939 }
3940
Mihai Predaeae850c2009-05-13 10:13:48 +02003941 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3942 ArrayList<PackageParser.Activity> packageActivities) {
3943 if (packageActivities == null) {
3944 return null;
3945 }
3946 mFlags = flags;
3947 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3948 int N = packageActivities.size();
3949 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3950 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003951
3952 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003953 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003954 intentFilters = packageActivities.get(i).intents;
3955 if (intentFilters != null && intentFilters.size() > 0) {
3956 listCut.add(intentFilters);
3957 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003958 }
3959 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3960 }
3961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003963 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 if (SHOW_INFO || Config.LOGV) Log.v(
3965 TAG, " " + type + " " +
3966 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3967 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3968 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003969 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3971 if (SHOW_INFO || Config.LOGV) {
3972 Log.v(TAG, " IntentFilter:");
3973 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3974 }
3975 if (!intent.debugCheck()) {
3976 Log.w(TAG, "==> For Activity " + a.info.name);
3977 }
3978 addFilter(intent);
3979 }
3980 }
3981
3982 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003983 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 if (SHOW_INFO || Config.LOGV) Log.v(
3985 TAG, " " + type + " " +
3986 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3987 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3988 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003989 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3991 if (SHOW_INFO || Config.LOGV) {
3992 Log.v(TAG, " IntentFilter:");
3993 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3994 }
3995 removeFilter(intent);
3996 }
3997 }
3998
3999 @Override
4000 protected boolean allowFilterResult(
4001 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4002 ActivityInfo filterAi = filter.activity.info;
4003 for (int i=dest.size()-1; i>=0; i--) {
4004 ActivityInfo destAi = dest.get(i).activityInfo;
4005 if (destAi.name == filterAi.name
4006 && destAi.packageName == filterAi.packageName) {
4007 return false;
4008 }
4009 }
4010 return true;
4011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 @Override
4014 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4015 int match) {
4016 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4017 return null;
4018 }
4019 final PackageParser.Activity activity = info.activity;
4020 if (mSafeMode && (activity.info.applicationInfo.flags
4021 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4022 return null;
4023 }
4024 final ResolveInfo res = new ResolveInfo();
4025 res.activityInfo = PackageParser.generateActivityInfo(activity,
4026 mFlags);
4027 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4028 res.filter = info;
4029 }
4030 res.priority = info.getPriority();
4031 res.preferredOrder = activity.owner.mPreferredOrder;
4032 //System.out.println("Result: " + res.activityInfo.className +
4033 // " = " + res.priority);
4034 res.match = match;
4035 res.isDefault = info.hasDefault;
4036 res.labelRes = info.labelRes;
4037 res.nonLocalizedLabel = info.nonLocalizedLabel;
4038 res.icon = info.icon;
4039 return res;
4040 }
4041
4042 @Override
4043 protected void sortResults(List<ResolveInfo> results) {
4044 Collections.sort(results, mResolvePrioritySorter);
4045 }
4046
4047 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004048 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004050 out.print(prefix); out.print(
4051 Integer.toHexString(System.identityHashCode(filter.activity)));
4052 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004053 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 }
4055
4056// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4057// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4058// final List<ResolveInfo> retList = Lists.newArrayList();
4059// while (i.hasNext()) {
4060// final ResolveInfo resolveInfo = i.next();
4061// if (isEnabledLP(resolveInfo.activityInfo)) {
4062// retList.add(resolveInfo);
4063// }
4064// }
4065// return retList;
4066// }
4067
4068 // Keys are String (activity class name), values are Activity.
4069 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4070 = new HashMap<ComponentName, PackageParser.Activity>();
4071 private int mFlags;
4072 }
4073
4074 private final class ServiceIntentResolver
4075 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004076 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004078 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 }
4080
Mihai Preda074edef2009-05-18 17:13:31 +02004081 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004083 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4085 }
4086
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004087 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4088 ArrayList<PackageParser.Service> packageServices) {
4089 if (packageServices == null) {
4090 return null;
4091 }
4092 mFlags = flags;
4093 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4094 int N = packageServices.size();
4095 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4096 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4097
4098 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4099 for (int i = 0; i < N; ++i) {
4100 intentFilters = packageServices.get(i).intents;
4101 if (intentFilters != null && intentFilters.size() > 0) {
4102 listCut.add(intentFilters);
4103 }
4104 }
4105 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4106 }
4107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004109 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 if (SHOW_INFO || Config.LOGV) Log.v(
4111 TAG, " " + (s.info.nonLocalizedLabel != null
4112 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4113 if (SHOW_INFO || Config.LOGV) Log.v(
4114 TAG, " Class=" + s.info.name);
4115 int NI = s.intents.size();
4116 int j;
4117 for (j=0; j<NI; j++) {
4118 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4119 if (SHOW_INFO || Config.LOGV) {
4120 Log.v(TAG, " IntentFilter:");
4121 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4122 }
4123 if (!intent.debugCheck()) {
4124 Log.w(TAG, "==> For Service " + s.info.name);
4125 }
4126 addFilter(intent);
4127 }
4128 }
4129
4130 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004131 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 if (SHOW_INFO || Config.LOGV) Log.v(
4133 TAG, " " + (s.info.nonLocalizedLabel != null
4134 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4135 if (SHOW_INFO || Config.LOGV) Log.v(
4136 TAG, " Class=" + s.info.name);
4137 int NI = s.intents.size();
4138 int j;
4139 for (j=0; j<NI; j++) {
4140 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4141 if (SHOW_INFO || Config.LOGV) {
4142 Log.v(TAG, " IntentFilter:");
4143 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4144 }
4145 removeFilter(intent);
4146 }
4147 }
4148
4149 @Override
4150 protected boolean allowFilterResult(
4151 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4152 ServiceInfo filterSi = filter.service.info;
4153 for (int i=dest.size()-1; i>=0; i--) {
4154 ServiceInfo destAi = dest.get(i).serviceInfo;
4155 if (destAi.name == filterSi.name
4156 && destAi.packageName == filterSi.packageName) {
4157 return false;
4158 }
4159 }
4160 return true;
4161 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 @Override
4164 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4165 int match) {
4166 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4167 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4168 return null;
4169 }
4170 final PackageParser.Service service = info.service;
4171 if (mSafeMode && (service.info.applicationInfo.flags
4172 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4173 return null;
4174 }
4175 final ResolveInfo res = new ResolveInfo();
4176 res.serviceInfo = PackageParser.generateServiceInfo(service,
4177 mFlags);
4178 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4179 res.filter = filter;
4180 }
4181 res.priority = info.getPriority();
4182 res.preferredOrder = service.owner.mPreferredOrder;
4183 //System.out.println("Result: " + res.activityInfo.className +
4184 // " = " + res.priority);
4185 res.match = match;
4186 res.isDefault = info.hasDefault;
4187 res.labelRes = info.labelRes;
4188 res.nonLocalizedLabel = info.nonLocalizedLabel;
4189 res.icon = info.icon;
4190 return res;
4191 }
4192
4193 @Override
4194 protected void sortResults(List<ResolveInfo> results) {
4195 Collections.sort(results, mResolvePrioritySorter);
4196 }
4197
4198 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004199 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004201 out.print(prefix); out.print(
4202 Integer.toHexString(System.identityHashCode(filter.service)));
4203 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004204 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 }
4206
4207// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4208// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4209// final List<ResolveInfo> retList = Lists.newArrayList();
4210// while (i.hasNext()) {
4211// final ResolveInfo resolveInfo = (ResolveInfo) i;
4212// if (isEnabledLP(resolveInfo.serviceInfo)) {
4213// retList.add(resolveInfo);
4214// }
4215// }
4216// return retList;
4217// }
4218
4219 // Keys are String (activity class name), values are Activity.
4220 private final HashMap<ComponentName, PackageParser.Service> mServices
4221 = new HashMap<ComponentName, PackageParser.Service>();
4222 private int mFlags;
4223 };
4224
4225 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4226 new Comparator<ResolveInfo>() {
4227 public int compare(ResolveInfo r1, ResolveInfo r2) {
4228 int v1 = r1.priority;
4229 int v2 = r2.priority;
4230 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4231 if (v1 != v2) {
4232 return (v1 > v2) ? -1 : 1;
4233 }
4234 v1 = r1.preferredOrder;
4235 v2 = r2.preferredOrder;
4236 if (v1 != v2) {
4237 return (v1 > v2) ? -1 : 1;
4238 }
4239 if (r1.isDefault != r2.isDefault) {
4240 return r1.isDefault ? -1 : 1;
4241 }
4242 v1 = r1.match;
4243 v2 = r2.match;
4244 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4245 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4246 }
4247 };
4248
4249 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4250 new Comparator<ProviderInfo>() {
4251 public int compare(ProviderInfo p1, ProviderInfo p2) {
4252 final int v1 = p1.initOrder;
4253 final int v2 = p2.initOrder;
4254 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4255 }
4256 };
4257
4258 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4259 IActivityManager am = ActivityManagerNative.getDefault();
4260 if (am != null) {
4261 try {
4262 final Intent intent = new Intent(action,
4263 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4264 if (extras != null) {
4265 intent.putExtras(extras);
4266 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004267 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 am.broadcastIntent(
4269 null, intent,
4270 null, null, 0, null, null, null, false, false);
4271 } catch (RemoteException ex) {
4272 }
4273 }
4274 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004275
4276 public String nextPackageToClean(String lastPackage) {
4277 synchronized (mPackages) {
4278 if (!mMediaMounted) {
4279 // If the external storage is no longer mounted at this point,
4280 // the caller may not have been able to delete all of this
4281 // packages files and can not delete any more. Bail.
4282 return null;
4283 }
4284 if (lastPackage != null) {
4285 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4286 }
4287 return mSettings.mPackagesToBeCleaned.size() > 0
4288 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4289 }
4290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004292 void schedulePackageCleaning(String packageName) {
4293 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4294 }
4295
4296 void startCleaningPackages() {
4297 synchronized (mPackages) {
4298 if (!mMediaMounted) {
4299 return;
4300 }
4301 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4302 return;
4303 }
4304 }
4305 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4306 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4307 IActivityManager am = ActivityManagerNative.getDefault();
4308 if (am != null) {
4309 try {
4310 am.startService(null, intent, null);
4311 } catch (RemoteException e) {
4312 }
4313 }
4314 }
4315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 private final class AppDirObserver extends FileObserver {
4317 public AppDirObserver(String path, int mask, boolean isrom) {
4318 super(path, mask);
4319 mRootDir = path;
4320 mIsRom = isrom;
4321 }
4322
4323 public void onEvent(int event, String path) {
4324 String removedPackage = null;
4325 int removedUid = -1;
4326 String addedPackage = null;
4327 int addedUid = -1;
4328
4329 synchronized (mInstallLock) {
4330 String fullPathStr = null;
4331 File fullPath = null;
4332 if (path != null) {
4333 fullPath = new File(mRootDir, path);
4334 fullPathStr = fullPath.getPath();
4335 }
4336
4337 if (Config.LOGV) Log.v(
4338 TAG, "File " + fullPathStr + " changed: "
4339 + Integer.toHexString(event));
4340
4341 if (!isPackageFilename(path)) {
4342 if (Config.LOGV) Log.v(
4343 TAG, "Ignoring change of non-package file: " + fullPathStr);
4344 return;
4345 }
4346
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004347 // Ignore packages that are being installed or
4348 // have just been installed.
4349 if (ignoreCodePath(fullPathStr)) {
4350 return;
4351 }
4352 PackageParser.Package p = null;
4353 synchronized (mPackages) {
4354 p = mAppDirs.get(fullPathStr);
4355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004357 if (p != null) {
4358 removePackageLI(p, true);
4359 removedPackage = p.applicationInfo.packageName;
4360 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
4362 }
4363
4364 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004366 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4368 PackageParser.PARSE_CHATTY |
4369 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004370 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 if (p != null) {
4372 synchronized (mPackages) {
4373 grantPermissionsLP(p, false);
4374 }
4375 addedPackage = p.applicationInfo.packageName;
4376 addedUid = p.applicationInfo.uid;
4377 }
4378 }
4379 }
4380
4381 synchronized (mPackages) {
4382 mSettings.writeLP();
4383 }
4384 }
4385
4386 if (removedPackage != null) {
4387 Bundle extras = new Bundle(1);
4388 extras.putInt(Intent.EXTRA_UID, removedUid);
4389 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4390 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4391 }
4392 if (addedPackage != null) {
4393 Bundle extras = new Bundle(1);
4394 extras.putInt(Intent.EXTRA_UID, addedUid);
4395 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4396 }
4397 }
4398
4399 private final String mRootDir;
4400 private final boolean mIsRom;
4401 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 /* Called when a downloaded package installation has been confirmed by the user */
4404 public void installPackage(
4405 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004406 installPackage(packageURI, observer, flags, null);
4407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004408
Jacek Surazski65e13172009-04-28 15:26:38 +02004409 /* Called when a downloaded package installation has been confirmed by the user */
4410 public void installPackage(
4411 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4412 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004413 mContext.enforceCallingOrSelfPermission(
4414 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004415
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004416 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004417 msg.obj = new InstallParams(packageURI, observer, flags,
4418 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004419 mHandler.sendMessage(msg);
4420 }
4421
Christopher Tate1bb69062010-02-19 17:02:12 -08004422 public void finishPackageInstall(int token) {
4423 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4424 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4425 mHandler.sendMessage(msg);
4426 }
4427
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004428 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 // Queue up an async operation since the package installation may take a little while.
4430 mHandler.post(new Runnable() {
4431 public void run() {
4432 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004433 // Result object to be returned
4434 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004436 res.uid = -1;
4437 res.pkg = null;
4438 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004439 args.doPreInstall(res.returnCode);
4440 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004441 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004442 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004443 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004444 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004446
4447 // A restore should be performed at this point if (a) the install
4448 // succeeded, (b) the operation is not an update, and (c) the new
4449 // package has a backupAgent defined.
4450 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004451 boolean doRestore = (!update
4452 && res.pkg != null
4453 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004454
4455 // Set up the post-install work request bookkeeping. This will be used
4456 // and cleaned up by the post-install event handling regardless of whether
4457 // there's a restore pass performed. Token values are >= 1.
4458 int token;
4459 if (mNextInstallToken < 0) mNextInstallToken = 1;
4460 token = mNextInstallToken++;
4461
4462 PostInstallData data = new PostInstallData(args, res);
4463 mRunningInstalls.put(token, data);
4464 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4465
4466 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4467 // Pass responsibility to the Backup Manager. It will perform a
4468 // restore if appropriate, then pass responsibility back to the
4469 // Package Manager to run the post-install observer callbacks
4470 // and broadcasts.
4471 IBackupManager bm = IBackupManager.Stub.asInterface(
4472 ServiceManager.getService(Context.BACKUP_SERVICE));
4473 if (bm != null) {
4474 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4475 + " to BM for possible restore");
4476 try {
4477 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4478 } catch (RemoteException e) {
4479 // can't happen; the backup manager is local
4480 } catch (Exception e) {
4481 Log.e(TAG, "Exception trying to enqueue restore", e);
4482 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004483 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004484 } else {
4485 Log.e(TAG, "Backup Manager not found!");
4486 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004489
4490 if (!doRestore) {
4491 // No restore possible, or the Backup Manager was mysteriously not
4492 // available -- just fire the post-install work request directly.
4493 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4494 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4495 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 });
4499 }
4500
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004501 abstract class HandlerParams {
4502 final static int MAX_RETRIES = 4;
4503 int retry = 0;
4504 final void startCopy() {
4505 try {
4506 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4507 retry++;
4508 if (retry > MAX_RETRIES) {
4509 Log.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
4510 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4511 handleServiceError();
4512 return;
4513 } else {
4514 handleStartCopy();
4515 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4516 mHandler.sendEmptyMessage(MCS_UNBIND);
4517 }
4518 } catch (RemoteException e) {
4519 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4520 mHandler.sendEmptyMessage(MCS_RECONNECT);
4521 }
4522 handleReturnCode();
4523 }
4524
4525 final void serviceError() {
4526 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4527 handleServiceError();
4528 handleReturnCode();
4529 }
4530 abstract void handleStartCopy() throws RemoteException;
4531 abstract void handleServiceError();
4532 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004533 }
4534
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004535 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004536 final IPackageInstallObserver observer;
4537 int flags;
4538 final Uri packageURI;
4539 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004540 private InstallArgs mArgs;
4541 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004542 InstallParams(Uri packageURI,
4543 IPackageInstallObserver observer, int flags,
4544 String installerPackageName) {
4545 this.packageURI = packageURI;
4546 this.flags = flags;
4547 this.observer = observer;
4548 this.installerPackageName = installerPackageName;
4549 }
4550
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004551 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004552 int ret = PackageManager.INSTALL_SUCCEEDED;
4553 // Dont need to invoke getInstallLocation for forward locked apps.
4554 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4555 flags &= ~PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004556 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004557 // Remote call to find out default install location
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004558 int loc = mContainerService.getRecommendedInstallLocation(packageURI);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004559 // Use install location to create InstallArgs and temporary
4560 // install location
4561 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4562 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4563 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4564 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4565 } else {
4566 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4567 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4568 // Set the flag to install on external media.
4569 flags |= PackageManager.INSTALL_EXTERNAL;
4570 } else {
4571 // Make sure the flag for installing on external
4572 // media is unset
4573 flags &= ~PackageManager.INSTALL_EXTERNAL;
4574 }
4575 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004576 }
4577 }
4578 // Create the file args now.
4579 mArgs = createInstallArgs(this);
4580 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4581 // Create copy only if we are not in an erroneous state.
4582 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004583 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004584 }
4585 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004586 }
4587
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004588 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004589 void handleReturnCode() {
4590 processPendingInstall(mArgs, mRet);
4591 }
4592
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004593 @Override
4594 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004595 mArgs = createInstallArgs(this);
4596 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004597 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004598 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004599
4600 /*
4601 * Utility class used in movePackage api.
4602 * srcArgs and targetArgs are not set for invalid flags and make
4603 * sure to do null checks when invoking methods on them.
4604 * We probably want to return ErrorPrams for both failed installs
4605 * and moves.
4606 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004607 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004608 final IPackageMoveObserver observer;
4609 final int flags;
4610 final String packageName;
4611 final InstallArgs srcArgs;
4612 final InstallArgs targetArgs;
4613 int mRet;
4614 MoveParams(InstallArgs srcArgs,
4615 IPackageMoveObserver observer,
4616 int flags, String packageName) {
4617 this.srcArgs = srcArgs;
4618 this.observer = observer;
4619 this.flags = flags;
4620 this.packageName = packageName;
4621 if (srcArgs != null) {
4622 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4623 targetArgs = createInstallArgs(packageUri, flags, packageName);
4624 } else {
4625 targetArgs = null;
4626 }
4627 }
4628
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004629 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004630 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004631 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004632 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004633 if (DEBUG_SD_INSTALL) {
4634 StringBuilder builder = new StringBuilder();
4635 if (srcArgs != null) {
4636 builder.append("src: ");
4637 builder.append(srcArgs.getCodePath());
4638 }
4639 if (targetArgs != null) {
4640 builder.append(" target : ");
4641 builder.append(targetArgs.getCodePath());
4642 }
4643 Log.i(TAG, "Posting move MCS_UNBIND for " + builder.toString());
4644 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004645 }
4646
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004647 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004648 void handleReturnCode() {
4649 targetArgs.doPostInstall(mRet);
4650 // TODO invoke pending move
4651 processPendingMove(this, mRet);
4652 }
4653
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004654 @Override
4655 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004656 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004657 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004658 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004659
4660 private InstallArgs createInstallArgs(InstallParams params) {
4661 if (installOnSd(params.flags)) {
4662 return new SdInstallArgs(params);
4663 } else {
4664 return new FileInstallArgs(params);
4665 }
4666 }
4667
4668 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4669 if (installOnSd(flags)) {
4670 return new SdInstallArgs(fullCodePath, fullResourcePath);
4671 } else {
4672 return new FileInstallArgs(fullCodePath, fullResourcePath);
4673 }
4674 }
4675
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004676 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4677 if (installOnSd(flags)) {
4678 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4679 return new SdInstallArgs(packageURI, cid);
4680 } else {
4681 return new FileInstallArgs(packageURI, pkgName);
4682 }
4683 }
4684
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004685 static abstract class InstallArgs {
4686 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004687 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004688 final int flags;
4689 final Uri packageURI;
4690 final String installerPackageName;
4691
4692 InstallArgs(Uri packageURI,
4693 IPackageInstallObserver observer, int flags,
4694 String installerPackageName) {
4695 this.packageURI = packageURI;
4696 this.flags = flags;
4697 this.observer = observer;
4698 this.installerPackageName = installerPackageName;
4699 }
4700
4701 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004702 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004703 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004704 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004705 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004706 abstract String getCodePath();
4707 abstract String getResourcePath();
4708 // Need installer lock especially for dex file removal.
4709 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004710 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004711 }
4712
4713 class FileInstallArgs extends InstallArgs {
4714 File installDir;
4715 String codeFileName;
4716 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004717 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004718
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004719 FileInstallArgs(InstallParams params) {
4720 super(params.packageURI, params.observer,
4721 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004722 }
4723
4724 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4725 super(null, null, 0, null);
4726 File codeFile = new File(fullCodePath);
4727 installDir = codeFile.getParentFile();
4728 codeFileName = fullCodePath;
4729 resourceFileName = fullResourcePath;
4730 }
4731
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004732 FileInstallArgs(Uri packageURI, String pkgName) {
4733 super(packageURI, null, 0, null);
4734 boolean fwdLocked = isFwdLocked(flags);
4735 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4736 String apkName = getNextCodePath(null, pkgName, ".apk");
4737 codeFileName = new File(installDir, apkName + ".apk").getPath();
4738 resourceFileName = getResourcePathFromCodePath();
4739 }
4740
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004741 String getCodePath() {
4742 return codeFileName;
4743 }
4744
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004745 void createCopyFile() {
4746 boolean fwdLocked = isFwdLocked(flags);
4747 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4748 codeFileName = createTempPackageFile(installDir).getPath();
4749 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004750 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004751 }
4752
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004753 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004754 if (temp) {
4755 // Generate temp file name
4756 createCopyFile();
4757 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004758 // Get a ParcelFileDescriptor to write to the output file
4759 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004760 if (!created) {
4761 try {
4762 codeFile.createNewFile();
4763 // Set permissions
4764 if (!setPermissions()) {
4765 // Failed setting permissions.
4766 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4767 }
4768 } catch (IOException e) {
4769 Log.w(TAG, "Failed to create file " + codeFile);
4770 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4771 }
4772 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004773 ParcelFileDescriptor out = null;
4774 try {
4775 out = ParcelFileDescriptor.open(codeFile,
4776 ParcelFileDescriptor.MODE_READ_WRITE);
4777 } catch (FileNotFoundException e) {
4778 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4779 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4780 }
4781 // Copy the resource now
4782 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4783 try {
4784 if (imcs.copyResource(packageURI, out)) {
4785 ret = PackageManager.INSTALL_SUCCEEDED;
4786 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004787 } finally {
4788 try { if (out != null) out.close(); } catch (IOException e) {}
4789 }
4790 return ret;
4791 }
4792
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004793 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004794 if (status != PackageManager.INSTALL_SUCCEEDED) {
4795 cleanUp();
4796 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004797 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004798 }
4799
4800 boolean doRename(int status, final String pkgName, String oldCodePath) {
4801 if (status != PackageManager.INSTALL_SUCCEEDED) {
4802 cleanUp();
4803 return false;
4804 } else {
4805 // Rename based on packageName
4806 File codeFile = new File(getCodePath());
4807 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4808 File desFile = new File(installDir, apkName + ".apk");
4809 if (!codeFile.renameTo(desFile)) {
4810 return false;
4811 }
4812 // Reset paths since the file has been renamed.
4813 codeFileName = desFile.getPath();
4814 resourceFileName = getResourcePathFromCodePath();
4815 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004816 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004817 // Failed setting permissions.
4818 return false;
4819 }
4820 return true;
4821 }
4822 }
4823
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004824 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004825 if (status != PackageManager.INSTALL_SUCCEEDED) {
4826 cleanUp();
4827 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004828 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004829 }
4830
4831 String getResourcePath() {
4832 return resourceFileName;
4833 }
4834
4835 String getResourcePathFromCodePath() {
4836 String codePath = getCodePath();
4837 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4838 String apkNameOnly = getApkName(codePath);
4839 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4840 } else {
4841 return codePath;
4842 }
4843 }
4844
4845 private boolean cleanUp() {
4846 boolean ret = true;
4847 String sourceDir = getCodePath();
4848 String publicSourceDir = getResourcePath();
4849 if (sourceDir != null) {
4850 File sourceFile = new File(sourceDir);
4851 if (!sourceFile.exists()) {
4852 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4853 ret = false;
4854 }
4855 // Delete application's code and resources
4856 sourceFile.delete();
4857 }
4858 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4859 final File publicSourceFile = new File(publicSourceDir);
4860 if (!publicSourceFile.exists()) {
4861 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4862 }
4863 if (publicSourceFile.exists()) {
4864 publicSourceFile.delete();
4865 }
4866 }
4867 return ret;
4868 }
4869
4870 void cleanUpResourcesLI() {
4871 String sourceDir = getCodePath();
4872 if (cleanUp() && mInstaller != null) {
4873 int retCode = mInstaller.rmdex(sourceDir);
4874 if (retCode < 0) {
4875 Log.w(TAG, "Couldn't remove dex file for package: "
4876 + " at location "
4877 + sourceDir + ", retcode=" + retCode);
4878 // we don't consider this to be a failure of the core package deletion
4879 }
4880 }
4881 }
4882
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004884 // TODO Do this in a more elegant way later on. for now just a hack
4885 if (!isFwdLocked(flags)) {
4886 final int filePermissions =
4887 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4888 |FileUtils.S_IROTH;
4889 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4890 if (retCode != 0) {
4891 Log.e(TAG, "Couldn't set new package file permissions for " +
4892 getCodePath()
4893 + ". The return code was: " + retCode);
4894 // TODO Define new internal error
4895 return false;
4896 }
4897 return true;
4898 }
4899 return true;
4900 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004901
4902 boolean doPostDeleteLI(boolean delete) {
4903 cleanUpResourcesLI();
4904 return true;
4905 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 }
4907
4908 class SdInstallArgs extends InstallArgs {
4909 String cid;
4910 String cachePath;
4911 static final String RES_FILE_NAME = "pkg.apk";
4912
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004913 SdInstallArgs(InstallParams params) {
4914 super(params.packageURI, params.observer,
4915 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004916 }
4917
4918 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004920 // Extract cid from fullCodePath
4921 int eidx = fullCodePath.lastIndexOf("/");
4922 String subStr1 = fullCodePath.substring(0, eidx);
4923 int sidx = subStr1.lastIndexOf("/");
4924 cid = subStr1.substring(sidx+1, eidx);
4925 cachePath = subStr1;
4926 }
4927
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004928 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4930 this.cid = cid;
4931 }
4932
4933 SdInstallArgs(Uri packageURI, String cid) {
4934 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004935 this.cid = cid;
4936 }
4937
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004938 void createCopyFile() {
4939 cid = getTempContainerId();
4940 }
4941
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004942 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943 if (temp) {
4944 createCopyFile();
4945 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004946 cachePath = imcs.copyResourceToContainer(
4947 packageURI, cid,
4948 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004949 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4950 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004951 }
4952
4953 @Override
4954 String getCodePath() {
4955 return cachePath + "/" + RES_FILE_NAME;
4956 }
4957
4958 @Override
4959 String getResourcePath() {
4960 return cachePath + "/" + RES_FILE_NAME;
4961 }
4962
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004963 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004964 if (status != PackageManager.INSTALL_SUCCEEDED) {
4965 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004966 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004967 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004968 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004969 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004970 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004971 if (cachePath == null) {
4972 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4973 }
4974 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004975 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004976 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 }
4978
4979 boolean doRename(int status, final String pkgName,
4980 String oldCodePath) {
4981 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004982 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004983 if (PackageHelper.isContainerMounted(cid)) {
4984 // Unmount the container
4985 if (!PackageHelper.unMountSdDir(cid)) {
4986 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004987 return false;
4988 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004990 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
4991 Log.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
4992 return false;
4993 }
4994 if (!PackageHelper.isContainerMounted(newCacheId)) {
4995 Log.w(TAG, "Mounting container " + newCacheId);
4996 newCachePath = PackageHelper.mountSdDir(newCacheId,
4997 getEncryptKey(), Process.SYSTEM_UID);
4998 } else {
4999 newCachePath = PackageHelper.getSdDir(newCacheId);
5000 }
5001 if (newCachePath == null) {
5002 Log.w(TAG, "Failed to get cache path for " + newCacheId);
5003 return false;
5004 }
5005 Log.i(TAG, "Succesfully renamed " + cid +
5006 " at path: " + cachePath + " to " + newCacheId +
5007 " at new path: " + newCachePath);
5008 cid = newCacheId;
5009 cachePath = newCachePath;
5010 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005011 }
5012
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005013 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 if (status != PackageManager.INSTALL_SUCCEEDED) {
5015 cleanUp();
5016 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005017 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005018 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005019 PackageHelper.mountSdDir(cid,
5020 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005021 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005022 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005023 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024 }
5025
5026 private void cleanUp() {
5027 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005028 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005029 }
5030
5031 void cleanUpResourcesLI() {
5032 String sourceFile = getCodePath();
5033 // Remove dex file
5034 if (mInstaller != null) {
5035 int retCode = mInstaller.rmdex(sourceFile.toString());
5036 if (retCode < 0) {
5037 Log.w(TAG, "Couldn't remove dex file for package: "
5038 + " at location "
5039 + sourceFile.toString() + ", retcode=" + retCode);
5040 // we don't consider this to be a failure of the core package deletion
5041 }
5042 }
5043 cleanUp();
5044 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005045
5046 boolean matchContainer(String app) {
5047 if (cid.startsWith(app)) {
5048 return true;
5049 }
5050 return false;
5051 }
5052
5053 String getPackageName() {
5054 int idx = cid.lastIndexOf("-");
5055 if (idx == -1) {
5056 return cid;
5057 }
5058 return cid.substring(0, idx);
5059 }
5060
5061 boolean doPostDeleteLI(boolean delete) {
5062 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005063 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005064 if (mounted) {
5065 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005066 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005067 }
5068 if (ret && delete) {
5069 cleanUpResourcesLI();
5070 }
5071 return ret;
5072 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005073 };
5074
5075 // Utility method used to create code paths based on package name and available index.
5076 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5077 String idxStr = "";
5078 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005079 // Fall back to default value of idx=1 if prefix is not
5080 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005082 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005083 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005084 if (subStr.endsWith(suffix)) {
5085 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005086 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005087 // If oldCodePath already contains prefix find out the
5088 // ending index to either increment or decrement.
5089 int sidx = subStr.lastIndexOf(prefix);
5090 if (sidx != -1) {
5091 subStr = subStr.substring(sidx + prefix.length());
5092 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005093 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5094 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005096 try {
5097 idx = Integer.parseInt(subStr);
5098 if (idx <= 1) {
5099 idx++;
5100 } else {
5101 idx--;
5102 }
5103 } catch(NumberFormatException e) {
5104 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 }
5106 }
5107 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005108 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 return prefix + idxStr;
5110 }
5111
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005112 // Utility method used to ignore ADD/REMOVE events
5113 // by directory observer.
5114 private static boolean ignoreCodePath(String fullPathStr) {
5115 String apkName = getApkName(fullPathStr);
5116 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5117 if (idx != -1 && ((idx+1) < apkName.length())) {
5118 // Make sure the package ends with a numeral
5119 String version = apkName.substring(idx+1);
5120 try {
5121 Integer.parseInt(version);
5122 return true;
5123 } catch (NumberFormatException e) {}
5124 }
5125 return false;
5126 }
5127
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 // Utility method that returns the relative package path with respect
5129 // to the installation directory. Like say for /data/data/com.test-1.apk
5130 // string com.test-1 is returned.
5131 static String getApkName(String codePath) {
5132 if (codePath == null) {
5133 return null;
5134 }
5135 int sidx = codePath.lastIndexOf("/");
5136 int eidx = codePath.lastIndexOf(".");
5137 if (eidx == -1) {
5138 eidx = codePath.length();
5139 } else if (eidx == 0) {
5140 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5141 return null;
5142 }
5143 return codePath.substring(sidx+1, eidx);
5144 }
5145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 class PackageInstalledInfo {
5147 String name;
5148 int uid;
5149 PackageParser.Package pkg;
5150 int returnCode;
5151 PackageRemovedInfo removedInfo;
5152 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 /*
5155 * Install a non-existing package.
5156 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005157 private void installNewPackageLI(PackageParser.Package pkg,
5158 int parseFlags,
5159 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005160 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08005162 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005163 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005164
5165 if (useEncryptedFilesystemForPackage(pkg)) {
5166 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
5167 } else {
5168 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
5169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005170 res.name = pkgName;
5171 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005172 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005174 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 + " without first uninstalling.");
5176 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5177 return;
5178 }
5179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005181 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005182 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005183 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5185 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5186 }
5187 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005188 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005189 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 res);
5191 // delete the partially installed application. the data directory will have to be
5192 // restored if it was already existing
5193 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5194 // remove package from internal structures. Note that we want deletePackageX to
5195 // delete the package data and cache directories that it created in
5196 // scanPackageLocked, unless those directories existed before we even tried to
5197 // install.
5198 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005199 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5201 res.removedInfo);
5202 }
5203 }
5204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005205
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005206 private void replacePackageLI(PackageParser.Package pkg,
5207 int parseFlags,
5208 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005209 String installerPackageName, PackageInstalledInfo res) {
5210
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005211 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005212 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 // First find the old package info and check signatures
5214 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005215 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005216 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005217 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5219 return;
5220 }
5221 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005222 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005223 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005224 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005226 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 }
5228 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005231 PackageParser.Package pkg,
5232 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005233 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 PackageParser.Package newPackage = null;
5235 String pkgName = deletedPackage.packageName;
5236 boolean deletedPkg = true;
5237 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005238
Jacek Surazski65e13172009-04-28 15:26:38 +02005239 String oldInstallerPackageName = null;
5240 synchronized (mPackages) {
5241 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5242 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005243
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005244 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005246 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 res.removedInfo)) {
5248 // If the existing package was'nt successfully deleted
5249 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5250 deletedPkg = false;
5251 } else {
5252 // Successfully deleted the old package. Now proceed with re-installation
5253 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005254 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005256 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5258 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005259 }
5260 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005261 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005262 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 res);
5264 updatedSettings = true;
5265 }
5266 }
5267
5268 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5269 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005270 // were keeping around in case we needed them (see below) can now be deleted.
5271 // This info will be set on the res.removedInfo to clean up later on as post
5272 // install action.
5273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 //update signature on the new package setting
5275 //this should always succeed, since we checked the
5276 //signature earlier.
5277 synchronized(mPackages) {
5278 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5279 parseFlags, true);
5280 }
5281 } else {
5282 // remove package from internal structures. Note that we want deletePackageX to
5283 // delete the package data and cache directories that it created in
5284 // scanPackageLocked, unless those directories existed before we even tried to
5285 // install.
5286 if(updatedSettings) {
5287 deletePackageLI(
5288 pkgName, true,
5289 PackageManager.DONT_DELETE_DATA,
5290 res.removedInfo);
5291 }
5292 // Since we failed to install the new package we need to restore the old
5293 // package that we deleted.
5294 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005295 File restoreFile = new File(deletedPackage.mPath);
5296 if (restoreFile == null) {
5297 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5298 return;
5299 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005300 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5301 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 // Parse old package
5303 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5304 scanPackageLI(restoreFile, parseFlags, scanMode);
5305 synchronized (mPackages) {
5306 grantPermissionsLP(deletedPackage, false);
5307 mSettings.writeLP();
5308 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005309 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5310 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 }
5314 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005317 PackageParser.Package pkg,
5318 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005319 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 PackageParser.Package newPackage = null;
5321 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005322 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 PackageParser.PARSE_IS_SYSTEM;
5324 String packageName = deletedPackage.packageName;
5325 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5326 if (packageName == null) {
5327 Log.w(TAG, "Attempt to delete null packageName.");
5328 return;
5329 }
5330 PackageParser.Package oldPkg;
5331 PackageSetting oldPkgSetting;
5332 synchronized (mPackages) {
5333 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005334 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5336 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005337 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 return;
5339 }
5340 }
5341 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5342 res.removedInfo.removedPackage = packageName;
5343 // Remove existing system package
5344 removePackageLI(oldPkg, true);
5345 synchronized (mPackages) {
5346 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5347 }
5348
5349 // Successfully disabled the old package. Now proceed with re-installation
5350 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5351 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005352 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005354 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5356 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5357 }
5358 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005359 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 updatedSettings = true;
5361 }
5362
5363 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5364 //update signature on the new package setting
5365 //this should always succeed, since we checked the
5366 //signature earlier.
5367 synchronized(mPackages) {
5368 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5369 parseFlags, true);
5370 }
5371 } else {
5372 // Re installation failed. Restore old information
5373 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005374 if (newPackage != null) {
5375 removePackageLI(newPackage, true);
5376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005377 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005378 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005380 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 // Restore the old system information in Settings
5382 synchronized(mPackages) {
5383 if(updatedSettings) {
5384 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005385 mSettings.setInstallerPackageName(packageName,
5386 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 }
5388 mSettings.writeLP();
5389 }
5390 }
5391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005392
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005393 // Utility method used to move dex files during install.
5394 private int moveDexFiles(PackageParser.Package newPackage) {
5395 int retCode;
5396 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5397 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5398 if (retCode != 0) {
5399 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5400 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5401 }
5402 }
5403 return PackageManager.INSTALL_SUCCEEDED;
5404 }
5405
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005406 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005407 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005408 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 synchronized (mPackages) {
5410 //write settings. the installStatus will be incomplete at this stage.
5411 //note that the new package setting would have already been
5412 //added to mPackages. It hasn't been persisted yet.
5413 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5414 mSettings.writeLP();
5415 }
5416
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005417 if ((res.returnCode = moveDexFiles(newPackage))
5418 != PackageManager.INSTALL_SUCCEEDED) {
5419 // Discontinue if moving dex files failed.
5420 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005422 if((res.returnCode = setPermissionsLI(newPackage))
5423 != PackageManager.INSTALL_SUCCEEDED) {
5424 if (mInstaller != null) {
5425 mInstaller.rmdex(newPackage.mScanPath);
5426 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005427 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005429 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 synchronized (mPackages) {
5432 grantPermissionsLP(newPackage, true);
5433 res.name = pkgName;
5434 res.uid = newPackage.applicationInfo.uid;
5435 res.pkg = newPackage;
5436 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005437 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5439 //to update install status
5440 mSettings.writeLP();
5441 }
5442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005443
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005444 private void installPackageLI(InstallArgs args,
5445 boolean newInstall, PackageInstalledInfo res) {
5446 int pFlags = args.flags;
5447 String installerPackageName = args.installerPackageName;
5448 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005449 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005450 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005451 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005452 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5453 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005454 // Result object to be returned
5455 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5456
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005457 // Retrieve PackageSettings and parse package
5458 int parseFlags = PackageParser.PARSE_CHATTY |
5459 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5460 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5461 parseFlags |= mDefParseFlags;
5462 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5463 pp.setSeparateProcesses(mSeparateProcesses);
5464 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5465 null, mMetrics, parseFlags);
5466 if (pkg == null) {
5467 res.returnCode = pp.getParseError();
5468 return;
5469 }
5470 String pkgName = res.name = pkg.packageName;
5471 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5472 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5473 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5474 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005476 }
5477 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5478 res.returnCode = pp.getParseError();
5479 return;
5480 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005481 // Get rid of all references to package scan path via parser.
5482 pp = null;
5483 String oldCodePath = null;
5484 boolean systemApp = false;
5485 synchronized (mPackages) {
5486 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005487 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5488 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005489 if (pkg.mOriginalPackages != null
5490 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005491 && mPackages.containsKey(oldName)) {
5492 // This package is derived from an original package,
5493 // and this device has been updating from that original
5494 // name. We must continue using the original name, so
5495 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005496 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005497 pkgName = pkg.packageName;
5498 replace = true;
5499 } else if (mPackages.containsKey(pkgName)) {
5500 // This package, under its official name, already exists
5501 // on the device; we should replace it.
5502 replace = true;
5503 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005504 }
5505 PackageSetting ps = mSettings.mPackages.get(pkgName);
5506 if (ps != null) {
5507 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5508 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5509 systemApp = (ps.pkg.applicationInfo.flags &
5510 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005511 }
5512 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005514
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005515 if (systemApp && onSd) {
5516 // Disable updates to system apps on sdcard
5517 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5518 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5519 return;
5520 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005521
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005522 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5523 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5524 return;
5525 }
5526 // Set application objects path explicitly after the rename
5527 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005528 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005529 replacePackageLI(pkg, parseFlags, scanMode,
5530 installerPackageName, res);
5531 } else {
5532 installNewPackageLI(pkg, parseFlags, scanMode,
5533 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 }
5535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005536
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005537 private int setPermissionsLI(PackageParser.Package newPackage) {
5538 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 int retCode = 0;
5540 // TODO Gross hack but fix later. Ideally move this to be a post installation
5541 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005542 if ((newPackage.applicationInfo.flags
5543 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5544 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 try {
5546 extractPublicFiles(newPackage, destResourceFile);
5547 } catch (IOException e) {
5548 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5549 " forward-locked app.");
5550 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5551 } finally {
5552 //TODO clean up the extracted public files
5553 }
5554 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005555 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 newPackage.applicationInfo.uid);
5557 } else {
5558 final int filePermissions =
5559 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005560 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 newPackage.applicationInfo.uid);
5562 }
5563 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005564 // The permissions on the resource file was set when it was copied for
5565 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 Log.e(TAG, "Couldn't set new package file permissions for " +
5570 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005572 // TODO Define new internal error
5573 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 }
5575 return PackageManager.INSTALL_SUCCEEDED;
5576 }
5577
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005578 private boolean isForwardLocked(PackageParser.Package pkg) {
5579 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 }
5581
5582 private void extractPublicFiles(PackageParser.Package newPackage,
5583 File publicZipFile) throws IOException {
5584 final ZipOutputStream publicZipOutStream =
5585 new ZipOutputStream(new FileOutputStream(publicZipFile));
5586 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5587
5588 // Copy manifest, resources.arsc and res directory to public zip
5589
5590 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5591 while (privateZipEntries.hasMoreElements()) {
5592 final ZipEntry zipEntry = privateZipEntries.nextElement();
5593 final String zipEntryName = zipEntry.getName();
5594 if ("AndroidManifest.xml".equals(zipEntryName)
5595 || "resources.arsc".equals(zipEntryName)
5596 || zipEntryName.startsWith("res/")) {
5597 try {
5598 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5599 } catch (IOException e) {
5600 try {
5601 publicZipOutStream.close();
5602 throw e;
5603 } finally {
5604 publicZipFile.delete();
5605 }
5606 }
5607 }
5608 }
5609
5610 publicZipOutStream.close();
5611 FileUtils.setPermissions(
5612 publicZipFile.getAbsolutePath(),
5613 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5614 -1, -1);
5615 }
5616
5617 private static void copyZipEntry(ZipEntry zipEntry,
5618 ZipFile inZipFile,
5619 ZipOutputStream outZipStream) throws IOException {
5620 byte[] buffer = new byte[4096];
5621 int num;
5622
5623 ZipEntry newEntry;
5624 if (zipEntry.getMethod() == ZipEntry.STORED) {
5625 // Preserve the STORED method of the input entry.
5626 newEntry = new ZipEntry(zipEntry);
5627 } else {
5628 // Create a new entry so that the compressed len is recomputed.
5629 newEntry = new ZipEntry(zipEntry.getName());
5630 }
5631 outZipStream.putNextEntry(newEntry);
5632
5633 InputStream data = inZipFile.getInputStream(zipEntry);
5634 while ((num = data.read(buffer)) > 0) {
5635 outZipStream.write(buffer, 0, num);
5636 }
5637 outZipStream.flush();
5638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 private void deleteTempPackageFiles() {
5641 FilenameFilter filter = new FilenameFilter() {
5642 public boolean accept(File dir, String name) {
5643 return name.startsWith("vmdl") && name.endsWith(".tmp");
5644 }
5645 };
5646 String tmpFilesList[] = mAppInstallDir.list(filter);
5647 if(tmpFilesList == null) {
5648 return;
5649 }
5650 for(int i = 0; i < tmpFilesList.length; i++) {
5651 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5652 tmpFile.delete();
5653 }
5654 }
5655
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005656 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 File tmpPackageFile;
5658 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005659 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 } catch (IOException e) {
5661 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5662 return null;
5663 }
5664 try {
5665 FileUtils.setPermissions(
5666 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5667 -1, -1);
5668 } catch (IOException e) {
5669 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5670 return null;
5671 }
5672 return tmpPackageFile;
5673 }
5674
5675 public void deletePackage(final String packageName,
5676 final IPackageDeleteObserver observer,
5677 final int flags) {
5678 mContext.enforceCallingOrSelfPermission(
5679 android.Manifest.permission.DELETE_PACKAGES, null);
5680 // Queue up an async operation since the package deletion may take a little while.
5681 mHandler.post(new Runnable() {
5682 public void run() {
5683 mHandler.removeCallbacks(this);
5684 final boolean succeded = deletePackageX(packageName, true, true, flags);
5685 if (observer != null) {
5686 try {
5687 observer.packageDeleted(succeded);
5688 } catch (RemoteException e) {
5689 Log.i(TAG, "Observer no longer exists.");
5690 } //end catch
5691 } //end if
5692 } //end run
5693 });
5694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 /**
5697 * This method is an internal method that could be get invoked either
5698 * to delete an installed package or to clean up a failed installation.
5699 * After deleting an installed package, a broadcast is sent to notify any
5700 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005701 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 * installation wouldn't have sent the initial broadcast either
5703 * The key steps in deleting a package are
5704 * deleting the package information in internal structures like mPackages,
5705 * deleting the packages base directories through installd
5706 * updating mSettings to reflect current status
5707 * persisting settings for later use
5708 * sending a broadcast if necessary
5709 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5711 boolean deleteCodeAndResources, int flags) {
5712 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005713 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005715 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5716 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5717 try {
5718 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
5719 Log.w(TAG, "Not removing package " + packageName + ": has active device admin");
5720 return false;
5721 }
5722 } catch (RemoteException e) {
5723 }
5724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 synchronized (mInstallLock) {
5726 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005730 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5731 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5732
5733 // If the removed package was a system update, the old system packaged
5734 // was re-enabled; we need to broadcast this information
5735 if (systemUpdate) {
5736 Bundle extras = new Bundle(1);
5737 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5738 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5739
5740 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5741 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005744 // Delete the resources here after sending the broadcast to let
5745 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005746 if (info.args != null) {
5747 synchronized (mInstallLock) {
5748 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005749 }
5750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 return res;
5752 }
5753
5754 static class PackageRemovedInfo {
5755 String removedPackage;
5756 int uid = -1;
5757 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005758 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005759 // Clean up resources deleted packages.
5760 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005762 void sendBroadcast(boolean fullRemove, boolean replacing) {
5763 Bundle extras = new Bundle(1);
5764 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5765 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5766 if (replacing) {
5767 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5768 }
5769 if (removedPackage != null) {
5770 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5771 }
5772 if (removedUid >= 0) {
5773 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5774 }
5775 }
5776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 /*
5779 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5780 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005781 * 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 -08005782 * delete a partially installed application.
5783 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005784 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 int flags) {
5786 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005787 if (outInfo != null) {
5788 outInfo.removedPackage = packageName;
5789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 removePackageLI(p, true);
5791 // Retrieve object to delete permissions for shared user later on
5792 PackageSetting deletedPs;
5793 synchronized (mPackages) {
5794 deletedPs = mSettings.mPackages.get(packageName);
5795 }
5796 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005797 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005799 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 if (retCode < 0) {
5801 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5802 + packageName + ", retcode=" + retCode);
5803 // we don't consider this to be a failure of the core package deletion
5804 }
5805 } else {
5806 //for emulator
5807 PackageParser.Package pkg = mPackages.get(packageName);
5808 File dataDir = new File(pkg.applicationInfo.dataDir);
5809 dataDir.delete();
5810 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005811 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005813 if (outInfo != null) {
5814 outInfo.removedUid = mSettings.removePackageLP(packageName);
5815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
5817 }
5818 synchronized (mPackages) {
5819 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5820 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005821 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005823 if (deletedPs != null) {
5824 // remove from preferred activities.
5825 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5826 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5827 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5828 removed.add(pa);
5829 }
5830 }
5831 for (PreferredActivity pa : removed) {
5832 mSettings.mPreferredActivities.removeFilter(pa);
5833 }
5834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005836 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 }
5838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 /*
5841 * Tries to delete system package.
5842 */
5843 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005844 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 ApplicationInfo applicationInfo = p.applicationInfo;
5846 //applicable for non-partially installed applications only
5847 if (applicationInfo == null) {
5848 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5849 return false;
5850 }
5851 PackageSetting ps = null;
5852 // Confirm if the system package has been updated
5853 // An updated system app can be deleted. This will also have to restore
5854 // the system pkg from system partition
5855 synchronized (mPackages) {
5856 ps = mSettings.getDisabledSystemPkg(p.packageName);
5857 }
5858 if (ps == null) {
5859 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5860 return false;
5861 } else {
5862 Log.i(TAG, "Deleting system pkg from data partition");
5863 }
5864 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005865 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005866 boolean deleteCodeAndResources = false;
5867 if (ps.versionCode < p.mVersionCode) {
5868 // Delete code and resources for downgrades
5869 deleteCodeAndResources = true;
5870 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5871 flags &= ~PackageManager.DONT_DELETE_DATA;
5872 }
5873 } else {
5874 // Preserve data by setting flag
5875 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5876 flags |= PackageManager.DONT_DELETE_DATA;
5877 }
5878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5880 if (!ret) {
5881 return false;
5882 }
5883 synchronized (mPackages) {
5884 // Reinstate the old system package
5885 mSettings.enableSystemPackageLP(p.packageName);
5886 }
5887 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005888 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005889 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005890 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 if (newPkg == null) {
5893 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5894 return false;
5895 }
5896 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005897 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 mSettings.writeLP();
5899 }
5900 return true;
5901 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5904 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5905 ApplicationInfo applicationInfo = p.applicationInfo;
5906 if (applicationInfo == null) {
5907 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5908 return false;
5909 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005910 if (outInfo != null) {
5911 outInfo.uid = applicationInfo.uid;
5912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913
5914 // Delete package data from internal structures and also remove data if flag is set
5915 removePackageDataLI(p, outInfo, flags);
5916
5917 // Delete application code and resources
5918 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005919 // TODO can pick up from PackageSettings as well
5920 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005921 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005922 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5923 PackageManager.INSTALL_FORWARD_LOCK : 0;
5924 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005925 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 }
5927 return true;
5928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 /*
5931 * This method handles package deletion in general
5932 */
5933 private boolean deletePackageLI(String packageName,
5934 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5935 if (packageName == null) {
5936 Log.w(TAG, "Attempt to delete null packageName.");
5937 return false;
5938 }
5939 PackageParser.Package p;
5940 boolean dataOnly = false;
5941 synchronized (mPackages) {
5942 p = mPackages.get(packageName);
5943 if (p == null) {
5944 //this retrieves partially installed apps
5945 dataOnly = true;
5946 PackageSetting ps = mSettings.mPackages.get(packageName);
5947 if (ps == null) {
5948 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5949 return false;
5950 }
5951 p = ps.pkg;
5952 }
5953 }
5954 if (p == null) {
5955 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5956 return false;
5957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 if (dataOnly) {
5960 // Delete application data first
5961 removePackageDataLI(p, outInfo, flags);
5962 return true;
5963 }
5964 // At this point the package should have ApplicationInfo associated with it
5965 if (p.applicationInfo == null) {
5966 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5967 return false;
5968 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005969 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5971 Log.i(TAG, "Removing system package:"+p.packageName);
5972 // When an updated system application is deleted we delete the existing resources as well and
5973 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005974 ret = deleteSystemPackageLI(p, flags, outInfo);
5975 } else {
5976 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005977 // Kill application pre-emptively especially for apps on sd.
5978 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005979 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005980 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005981 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 public void clearApplicationUserData(final String packageName,
5985 final IPackageDataObserver observer) {
5986 mContext.enforceCallingOrSelfPermission(
5987 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5988 // Queue up an async operation since the package deletion may take a little while.
5989 mHandler.post(new Runnable() {
5990 public void run() {
5991 mHandler.removeCallbacks(this);
5992 final boolean succeeded;
5993 synchronized (mInstallLock) {
5994 succeeded = clearApplicationUserDataLI(packageName);
5995 }
5996 if (succeeded) {
5997 // invoke DeviceStorageMonitor's update method to clear any notifications
5998 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5999 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6000 if (dsm != null) {
6001 dsm.updateMemory();
6002 }
6003 }
6004 if(observer != null) {
6005 try {
6006 observer.onRemoveCompleted(packageName, succeeded);
6007 } catch (RemoteException e) {
6008 Log.i(TAG, "Observer no longer exists.");
6009 }
6010 } //end if observer
6011 } //end run
6012 });
6013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 private boolean clearApplicationUserDataLI(String packageName) {
6016 if (packageName == null) {
6017 Log.w(TAG, "Attempt to delete null packageName.");
6018 return false;
6019 }
6020 PackageParser.Package p;
6021 boolean dataOnly = false;
6022 synchronized (mPackages) {
6023 p = mPackages.get(packageName);
6024 if(p == null) {
6025 dataOnly = true;
6026 PackageSetting ps = mSettings.mPackages.get(packageName);
6027 if((ps == null) || (ps.pkg == null)) {
6028 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6029 return false;
6030 }
6031 p = ps.pkg;
6032 }
6033 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006034 boolean useEncryptedFSDir = false;
6035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 if(!dataOnly) {
6037 //need to check this only for fully installed applications
6038 if (p == null) {
6039 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6040 return false;
6041 }
6042 final ApplicationInfo applicationInfo = p.applicationInfo;
6043 if (applicationInfo == null) {
6044 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6045 return false;
6046 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006047 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 }
6049 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006050 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 if (retCode < 0) {
6052 Log.w(TAG, "Couldn't remove cache files for package: "
6053 + packageName);
6054 return false;
6055 }
6056 }
6057 return true;
6058 }
6059
6060 public void deleteApplicationCacheFiles(final String packageName,
6061 final IPackageDataObserver observer) {
6062 mContext.enforceCallingOrSelfPermission(
6063 android.Manifest.permission.DELETE_CACHE_FILES, null);
6064 // Queue up an async operation since the package deletion may take a little while.
6065 mHandler.post(new Runnable() {
6066 public void run() {
6067 mHandler.removeCallbacks(this);
6068 final boolean succeded;
6069 synchronized (mInstallLock) {
6070 succeded = deleteApplicationCacheFilesLI(packageName);
6071 }
6072 if(observer != null) {
6073 try {
6074 observer.onRemoveCompleted(packageName, succeded);
6075 } catch (RemoteException e) {
6076 Log.i(TAG, "Observer no longer exists.");
6077 }
6078 } //end if observer
6079 } //end run
6080 });
6081 }
6082
6083 private boolean deleteApplicationCacheFilesLI(String packageName) {
6084 if (packageName == null) {
6085 Log.w(TAG, "Attempt to delete null packageName.");
6086 return false;
6087 }
6088 PackageParser.Package p;
6089 synchronized (mPackages) {
6090 p = mPackages.get(packageName);
6091 }
6092 if (p == null) {
6093 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6094 return false;
6095 }
6096 final ApplicationInfo applicationInfo = p.applicationInfo;
6097 if (applicationInfo == null) {
6098 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6099 return false;
6100 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006101 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006103 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 if (retCode < 0) {
6105 Log.w(TAG, "Couldn't remove cache files for package: "
6106 + packageName);
6107 return false;
6108 }
6109 }
6110 return true;
6111 }
6112
6113 public void getPackageSizeInfo(final String packageName,
6114 final IPackageStatsObserver observer) {
6115 mContext.enforceCallingOrSelfPermission(
6116 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6117 // Queue up an async operation since the package deletion may take a little while.
6118 mHandler.post(new Runnable() {
6119 public void run() {
6120 mHandler.removeCallbacks(this);
6121 PackageStats lStats = new PackageStats(packageName);
6122 final boolean succeded;
6123 synchronized (mInstallLock) {
6124 succeded = getPackageSizeInfoLI(packageName, lStats);
6125 }
6126 if(observer != null) {
6127 try {
6128 observer.onGetStatsCompleted(lStats, succeded);
6129 } catch (RemoteException e) {
6130 Log.i(TAG, "Observer no longer exists.");
6131 }
6132 } //end if observer
6133 } //end run
6134 });
6135 }
6136
6137 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6138 if (packageName == null) {
6139 Log.w(TAG, "Attempt to get size of null packageName.");
6140 return false;
6141 }
6142 PackageParser.Package p;
6143 boolean dataOnly = false;
6144 synchronized (mPackages) {
6145 p = mPackages.get(packageName);
6146 if(p == null) {
6147 dataOnly = true;
6148 PackageSetting ps = mSettings.mPackages.get(packageName);
6149 if((ps == null) || (ps.pkg == null)) {
6150 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6151 return false;
6152 }
6153 p = ps.pkg;
6154 }
6155 }
6156 String publicSrcDir = null;
6157 if(!dataOnly) {
6158 final ApplicationInfo applicationInfo = p.applicationInfo;
6159 if (applicationInfo == null) {
6160 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6161 return false;
6162 }
6163 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6164 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006165 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 if (mInstaller != null) {
6167 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006168 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 if (res < 0) {
6170 return false;
6171 } else {
6172 return true;
6173 }
6174 }
6175 return true;
6176 }
6177
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 public void addPackageToPreferred(String packageName) {
6180 mContext.enforceCallingOrSelfPermission(
6181 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006182 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 }
6184
6185 public void removePackageFromPreferred(String packageName) {
6186 mContext.enforceCallingOrSelfPermission(
6187 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006188 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 }
6190
6191 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006192 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 }
6194
6195 public void addPreferredActivity(IntentFilter filter, int match,
6196 ComponentName[] set, ComponentName activity) {
6197 mContext.enforceCallingOrSelfPermission(
6198 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6199
6200 synchronized (mPackages) {
6201 Log.i(TAG, "Adding preferred activity " + activity + ":");
6202 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6203 mSettings.mPreferredActivities.addFilter(
6204 new PreferredActivity(filter, match, set, activity));
6205 mSettings.writeLP();
6206 }
6207 }
6208
Satish Sampath8dbe6122009-06-02 23:35:54 +01006209 public void replacePreferredActivity(IntentFilter filter, int match,
6210 ComponentName[] set, ComponentName activity) {
6211 mContext.enforceCallingOrSelfPermission(
6212 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6213 if (filter.countActions() != 1) {
6214 throw new IllegalArgumentException(
6215 "replacePreferredActivity expects filter to have only 1 action.");
6216 }
6217 if (filter.countCategories() != 1) {
6218 throw new IllegalArgumentException(
6219 "replacePreferredActivity expects filter to have only 1 category.");
6220 }
6221 if (filter.countDataAuthorities() != 0
6222 || filter.countDataPaths() != 0
6223 || filter.countDataSchemes() != 0
6224 || filter.countDataTypes() != 0) {
6225 throw new IllegalArgumentException(
6226 "replacePreferredActivity expects filter to have no data authorities, " +
6227 "paths, schemes or types.");
6228 }
6229 synchronized (mPackages) {
6230 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6231 String action = filter.getAction(0);
6232 String category = filter.getCategory(0);
6233 while (it.hasNext()) {
6234 PreferredActivity pa = it.next();
6235 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6236 it.remove();
6237 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6238 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6239 }
6240 }
6241 addPreferredActivity(filter, match, set, activity);
6242 }
6243 }
6244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 public void clearPackagePreferredActivities(String packageName) {
6246 mContext.enforceCallingOrSelfPermission(
6247 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6248
6249 synchronized (mPackages) {
6250 if (clearPackagePreferredActivitiesLP(packageName)) {
6251 mSettings.writeLP();
6252 }
6253 }
6254 }
6255
6256 boolean clearPackagePreferredActivitiesLP(String packageName) {
6257 boolean changed = false;
6258 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6259 while (it.hasNext()) {
6260 PreferredActivity pa = it.next();
6261 if (pa.mActivity.getPackageName().equals(packageName)) {
6262 it.remove();
6263 changed = true;
6264 }
6265 }
6266 return changed;
6267 }
6268
6269 public int getPreferredActivities(List<IntentFilter> outFilters,
6270 List<ComponentName> outActivities, String packageName) {
6271
6272 int num = 0;
6273 synchronized (mPackages) {
6274 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6275 while (it.hasNext()) {
6276 PreferredActivity pa = it.next();
6277 if (packageName == null
6278 || pa.mActivity.getPackageName().equals(packageName)) {
6279 if (outFilters != null) {
6280 outFilters.add(new IntentFilter(pa));
6281 }
6282 if (outActivities != null) {
6283 outActivities.add(pa.mActivity);
6284 }
6285 }
6286 }
6287 }
6288
6289 return num;
6290 }
6291
6292 public void setApplicationEnabledSetting(String appPackageName,
6293 int newState, int flags) {
6294 setEnabledSetting(appPackageName, null, newState, flags);
6295 }
6296
6297 public void setComponentEnabledSetting(ComponentName componentName,
6298 int newState, int flags) {
6299 setEnabledSetting(componentName.getPackageName(),
6300 componentName.getClassName(), newState, flags);
6301 }
6302
6303 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006304 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6306 || newState == COMPONENT_ENABLED_STATE_ENABLED
6307 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6308 throw new IllegalArgumentException("Invalid new component state: "
6309 + newState);
6310 }
6311 PackageSetting pkgSetting;
6312 final int uid = Binder.getCallingUid();
6313 final int permission = mContext.checkCallingPermission(
6314 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6315 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006316 boolean sendNow = false;
6317 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006318 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006320 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006322 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006324 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006326 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 }
6328 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006329 "Unknown component: " + packageName
6330 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 }
6332 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6333 throw new SecurityException(
6334 "Permission Denial: attempt to change component state from pid="
6335 + Binder.getCallingPid()
6336 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6337 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006338 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 // We're dealing with an application/package level state change
6340 pkgSetting.enabled = newState;
6341 } else {
6342 // We're dealing with a component level state change
6343 switch (newState) {
6344 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006345 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 break;
6347 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006348 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 break;
6350 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006351 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 break;
6353 default:
6354 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006355 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
6357 }
6358 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006359 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006360 components = mPendingBroadcasts.get(packageName);
6361 boolean newPackage = components == null;
6362 if (newPackage) {
6363 components = new ArrayList<String>();
6364 }
6365 if (!components.contains(componentName)) {
6366 components.add(componentName);
6367 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006368 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6369 sendNow = true;
6370 // Purge entry from pending broadcast list if another one exists already
6371 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006372 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006373 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006374 if (newPackage) {
6375 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006376 }
6377 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6378 // Schedule a message
6379 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6380 }
6381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 long callingId = Binder.clearCallingIdentity();
6385 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006386 if (sendNow) {
6387 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006388 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 } finally {
6391 Binder.restoreCallingIdentity(callingId);
6392 }
6393 }
6394
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006395 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006396 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6397 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6398 + " components=" + componentNames);
6399 Bundle extras = new Bundle(4);
6400 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6401 String nameList[] = new String[componentNames.size()];
6402 componentNames.toArray(nameList);
6403 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006404 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6405 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006406 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006407 }
6408
Jacek Surazski65e13172009-04-28 15:26:38 +02006409 public String getInstallerPackageName(String packageName) {
6410 synchronized (mPackages) {
6411 PackageSetting pkg = mSettings.mPackages.get(packageName);
6412 if (pkg == null) {
6413 throw new IllegalArgumentException("Unknown package: " + packageName);
6414 }
6415 return pkg.installerPackageName;
6416 }
6417 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 public int getApplicationEnabledSetting(String appPackageName) {
6420 synchronized (mPackages) {
6421 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6422 if (pkg == null) {
6423 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6424 }
6425 return pkg.enabled;
6426 }
6427 }
6428
6429 public int getComponentEnabledSetting(ComponentName componentName) {
6430 synchronized (mPackages) {
6431 final String packageNameStr = componentName.getPackageName();
6432 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6433 if (pkg == null) {
6434 throw new IllegalArgumentException("Unknown component: " + componentName);
6435 }
6436 final String classNameStr = componentName.getClassName();
6437 return pkg.currentEnabledStateLP(classNameStr);
6438 }
6439 }
6440
6441 public void enterSafeMode() {
6442 if (!mSystemReady) {
6443 mSafeMode = true;
6444 }
6445 }
6446
6447 public void systemReady() {
6448 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006449
6450 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006451 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006452 mContext.getContentResolver(),
6453 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006454 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006455 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006456 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
6459
6460 public boolean isSafeMode() {
6461 return mSafeMode;
6462 }
6463
6464 public boolean hasSystemUidErrors() {
6465 return mHasSystemUidErrors;
6466 }
6467
6468 static String arrayToString(int[] array) {
6469 StringBuffer buf = new StringBuffer(128);
6470 buf.append('[');
6471 if (array != null) {
6472 for (int i=0; i<array.length; i++) {
6473 if (i > 0) buf.append(", ");
6474 buf.append(array[i]);
6475 }
6476 }
6477 buf.append(']');
6478 return buf.toString();
6479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 @Override
6482 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6483 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6484 != PackageManager.PERMISSION_GRANTED) {
6485 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6486 + Binder.getCallingPid()
6487 + ", uid=" + Binder.getCallingUid()
6488 + " without permission "
6489 + android.Manifest.permission.DUMP);
6490 return;
6491 }
6492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 synchronized (mPackages) {
6494 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006495 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 pw.println(" ");
6497 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006498 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 pw.println(" ");
6500 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006501 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 pw.println(" ");
6503 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006504 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 pw.println("Permissions:");
6507 {
6508 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006509 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6510 pw.print(Integer.toHexString(System.identityHashCode(p)));
6511 pw.println("):");
6512 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6513 pw.print(" uid="); pw.print(p.uid);
6514 pw.print(" gids="); pw.print(arrayToString(p.gids));
6515 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 }
6517 }
6518 pw.println(" ");
6519 pw.println("Packages:");
6520 {
6521 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006522 pw.print(" Package [");
6523 pw.print(ps.realName != null ? ps.realName : ps.name);
6524 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006525 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6526 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006527 if (ps.realName != null) {
6528 pw.print(" compat name="); pw.println(ps.name);
6529 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006530 pw.print(" userId="); pw.print(ps.userId);
6531 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6532 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6533 pw.print(" pkg="); pw.println(ps.pkg);
6534 pw.print(" codePath="); pw.println(ps.codePathString);
6535 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006537 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006538 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006539 pw.print(" supportsScreens=[");
6540 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006541 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006542 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006543 if (!first) pw.print(", ");
6544 first = false;
6545 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006547 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006548 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006549 if (!first) pw.print(", ");
6550 first = false;
6551 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006553 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006554 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006555 if (!first) pw.print(", ");
6556 first = false;
6557 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006559 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006560 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006561 if (!first) pw.print(", ");
6562 first = false;
6563 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006565 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006566 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6567 if (!first) pw.print(", ");
6568 first = false;
6569 pw.print("anyDensity");
6570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006572 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006573 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6574 pw.print(" signatures="); pw.println(ps.signatures);
6575 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6576 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6577 pw.print(" installStatus="); pw.print(ps.installStatus);
6578 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 if (ps.disabledComponents.size() > 0) {
6580 pw.println(" disabledComponents:");
6581 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006582 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 }
6584 }
6585 if (ps.enabledComponents.size() > 0) {
6586 pw.println(" enabledComponents:");
6587 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006588 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006591 if (ps.grantedPermissions.size() > 0) {
6592 pw.println(" grantedPermissions:");
6593 for (String s : ps.grantedPermissions) {
6594 pw.print(" "); pw.println(s);
6595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006597 if (ps.loadedPermissions.size() > 0) {
6598 pw.println(" loadedPermissions:");
6599 for (String s : ps.loadedPermissions) {
6600 pw.print(" "); pw.println(s);
6601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
6603 }
6604 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006605 if (mSettings.mRenamedPackages.size() > 0) {
6606 pw.println(" ");
6607 pw.println("Renamed packages:");
6608 for (HashMap.Entry<String, String> e
6609 : mSettings.mRenamedPackages.entrySet()) {
6610 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6611 pw.println(e.getValue());
6612 }
6613 }
6614 if (mSettings.mDisabledSysPackages.size() > 0) {
6615 pw.println(" ");
6616 pw.println("Hidden system packages:");
6617 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6618 pw.print(" Package [");
6619 pw.print(ps.realName != null ? ps.realName : ps.name);
6620 pw.print("] (");
6621 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6622 pw.println("):");
6623 if (ps.realName != null) {
6624 pw.print(" compat name="); pw.println(ps.name);
6625 }
6626 pw.print(" userId="); pw.println(ps.userId);
6627 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6628 pw.print(" codePath="); pw.println(ps.codePathString);
6629 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6630 }
6631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 pw.println(" ");
6633 pw.println("Shared Users:");
6634 {
6635 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006636 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6637 pw.print(Integer.toHexString(System.identityHashCode(su)));
6638 pw.println("):");
6639 pw.print(" userId="); pw.print(su.userId);
6640 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 pw.println(" grantedPermissions:");
6642 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006643 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 }
6645 pw.println(" loadedPermissions:");
6646 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006647 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 }
6649 }
6650 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 pw.println(" ");
6653 pw.println("Settings parse messages:");
6654 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006655
6656 pw.println(" ");
6657 pw.println("Package warning messages:");
6658 File fname = getSettingsProblemFile();
6659 FileInputStream in;
6660 try {
6661 in = new FileInputStream(fname);
6662 int avail = in.available();
6663 byte[] data = new byte[avail];
6664 in.read(data);
6665 pw.println(new String(data));
6666 } catch (FileNotFoundException e) {
6667 } catch (IOException e) {
6668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006670
6671 synchronized (mProviders) {
6672 pw.println(" ");
6673 pw.println("Registered ContentProviders:");
6674 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006675 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006676 pw.println(p.toString());
6677 }
6678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 }
6680
6681 static final class BasePermission {
6682 final static int TYPE_NORMAL = 0;
6683 final static int TYPE_BUILTIN = 1;
6684 final static int TYPE_DYNAMIC = 2;
6685
6686 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006687 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 final int type;
6689 PackageParser.Permission perm;
6690 PermissionInfo pendingInfo;
6691 int uid;
6692 int[] gids;
6693
6694 BasePermission(String _name, String _sourcePackage, int _type) {
6695 name = _name;
6696 sourcePackage = _sourcePackage;
6697 type = _type;
6698 }
6699 }
6700
6701 static class PackageSignatures {
6702 private Signature[] mSignatures;
6703
6704 PackageSignatures(Signature[] sigs) {
6705 assignSignatures(sigs);
6706 }
6707
6708 PackageSignatures() {
6709 }
6710
6711 void writeXml(XmlSerializer serializer, String tagName,
6712 ArrayList<Signature> pastSignatures) throws IOException {
6713 if (mSignatures == null) {
6714 return;
6715 }
6716 serializer.startTag(null, tagName);
6717 serializer.attribute(null, "count",
6718 Integer.toString(mSignatures.length));
6719 for (int i=0; i<mSignatures.length; i++) {
6720 serializer.startTag(null, "cert");
6721 final Signature sig = mSignatures[i];
6722 final int sigHash = sig.hashCode();
6723 final int numPast = pastSignatures.size();
6724 int j;
6725 for (j=0; j<numPast; j++) {
6726 Signature pastSig = pastSignatures.get(j);
6727 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6728 serializer.attribute(null, "index", Integer.toString(j));
6729 break;
6730 }
6731 }
6732 if (j >= numPast) {
6733 pastSignatures.add(sig);
6734 serializer.attribute(null, "index", Integer.toString(numPast));
6735 serializer.attribute(null, "key", sig.toCharsString());
6736 }
6737 serializer.endTag(null, "cert");
6738 }
6739 serializer.endTag(null, tagName);
6740 }
6741
6742 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6743 throws IOException, XmlPullParserException {
6744 String countStr = parser.getAttributeValue(null, "count");
6745 if (countStr == null) {
6746 reportSettingsProblem(Log.WARN,
6747 "Error in package manager settings: <signatures> has"
6748 + " no count at " + parser.getPositionDescription());
6749 XmlUtils.skipCurrentTag(parser);
6750 }
6751 final int count = Integer.parseInt(countStr);
6752 mSignatures = new Signature[count];
6753 int pos = 0;
6754
6755 int outerDepth = parser.getDepth();
6756 int type;
6757 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6758 && (type != XmlPullParser.END_TAG
6759 || parser.getDepth() > outerDepth)) {
6760 if (type == XmlPullParser.END_TAG
6761 || type == XmlPullParser.TEXT) {
6762 continue;
6763 }
6764
6765 String tagName = parser.getName();
6766 if (tagName.equals("cert")) {
6767 if (pos < count) {
6768 String index = parser.getAttributeValue(null, "index");
6769 if (index != null) {
6770 try {
6771 int idx = Integer.parseInt(index);
6772 String key = parser.getAttributeValue(null, "key");
6773 if (key == null) {
6774 if (idx >= 0 && idx < pastSignatures.size()) {
6775 Signature sig = pastSignatures.get(idx);
6776 if (sig != null) {
6777 mSignatures[pos] = pastSignatures.get(idx);
6778 pos++;
6779 } else {
6780 reportSettingsProblem(Log.WARN,
6781 "Error in package manager settings: <cert> "
6782 + "index " + index + " is not defined at "
6783 + parser.getPositionDescription());
6784 }
6785 } else {
6786 reportSettingsProblem(Log.WARN,
6787 "Error in package manager settings: <cert> "
6788 + "index " + index + " is out of bounds at "
6789 + parser.getPositionDescription());
6790 }
6791 } else {
6792 while (pastSignatures.size() <= idx) {
6793 pastSignatures.add(null);
6794 }
6795 Signature sig = new Signature(key);
6796 pastSignatures.set(idx, sig);
6797 mSignatures[pos] = sig;
6798 pos++;
6799 }
6800 } catch (NumberFormatException e) {
6801 reportSettingsProblem(Log.WARN,
6802 "Error in package manager settings: <cert> "
6803 + "index " + index + " is not a number at "
6804 + parser.getPositionDescription());
6805 }
6806 } else {
6807 reportSettingsProblem(Log.WARN,
6808 "Error in package manager settings: <cert> has"
6809 + " no index at " + parser.getPositionDescription());
6810 }
6811 } else {
6812 reportSettingsProblem(Log.WARN,
6813 "Error in package manager settings: too "
6814 + "many <cert> tags, expected " + count
6815 + " at " + parser.getPositionDescription());
6816 }
6817 } else {
6818 reportSettingsProblem(Log.WARN,
6819 "Unknown element under <cert>: "
6820 + parser.getName());
6821 }
6822 XmlUtils.skipCurrentTag(parser);
6823 }
6824
6825 if (pos < count) {
6826 // Should never happen -- there is an error in the written
6827 // settings -- but if it does we don't want to generate
6828 // a bad array.
6829 Signature[] newSigs = new Signature[pos];
6830 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6831 mSignatures = newSigs;
6832 }
6833 }
6834
6835 /**
6836 * If any of the given 'sigs' is contained in the existing signatures,
6837 * then completely replace the current signatures with the ones in
6838 * 'sigs'. This is used for updating an existing package to a newly
6839 * installed version.
6840 */
6841 boolean updateSignatures(Signature[] sigs, boolean update) {
6842 if (mSignatures == null) {
6843 if (update) {
6844 assignSignatures(sigs);
6845 }
6846 return true;
6847 }
6848 if (sigs == null) {
6849 return false;
6850 }
6851
6852 for (int i=0; i<sigs.length; i++) {
6853 Signature sig = sigs[i];
6854 for (int j=0; j<mSignatures.length; j++) {
6855 if (mSignatures[j].equals(sig)) {
6856 if (update) {
6857 assignSignatures(sigs);
6858 }
6859 return true;
6860 }
6861 }
6862 }
6863 return false;
6864 }
6865
6866 /**
6867 * If any of the given 'sigs' is contained in the existing signatures,
6868 * then add in any new signatures found in 'sigs'. This is used for
6869 * including a new package into an existing shared user id.
6870 */
6871 boolean mergeSignatures(Signature[] sigs, boolean update) {
6872 if (mSignatures == null) {
6873 if (update) {
6874 assignSignatures(sigs);
6875 }
6876 return true;
6877 }
6878 if (sigs == null) {
6879 return false;
6880 }
6881
6882 Signature[] added = null;
6883 int addedCount = 0;
6884 boolean haveMatch = false;
6885 for (int i=0; i<sigs.length; i++) {
6886 Signature sig = sigs[i];
6887 boolean found = false;
6888 for (int j=0; j<mSignatures.length; j++) {
6889 if (mSignatures[j].equals(sig)) {
6890 found = true;
6891 haveMatch = true;
6892 break;
6893 }
6894 }
6895
6896 if (!found) {
6897 if (added == null) {
6898 added = new Signature[sigs.length];
6899 }
6900 added[i] = sig;
6901 addedCount++;
6902 }
6903 }
6904
6905 if (!haveMatch) {
6906 // Nothing matched -- reject the new signatures.
6907 return false;
6908 }
6909 if (added == null) {
6910 // Completely matched -- nothing else to do.
6911 return true;
6912 }
6913
6914 // Add additional signatures in.
6915 if (update) {
6916 Signature[] total = new Signature[addedCount+mSignatures.length];
6917 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6918 int j = mSignatures.length;
6919 for (int i=0; i<added.length; i++) {
6920 if (added[i] != null) {
6921 total[j] = added[i];
6922 j++;
6923 }
6924 }
6925 mSignatures = total;
6926 }
6927 return true;
6928 }
6929
6930 private void assignSignatures(Signature[] sigs) {
6931 if (sigs == null) {
6932 mSignatures = null;
6933 return;
6934 }
6935 mSignatures = new Signature[sigs.length];
6936 for (int i=0; i<sigs.length; i++) {
6937 mSignatures[i] = sigs[i];
6938 }
6939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 @Override
6942 public String toString() {
6943 StringBuffer buf = new StringBuffer(128);
6944 buf.append("PackageSignatures{");
6945 buf.append(Integer.toHexString(System.identityHashCode(this)));
6946 buf.append(" [");
6947 if (mSignatures != null) {
6948 for (int i=0; i<mSignatures.length; i++) {
6949 if (i > 0) buf.append(", ");
6950 buf.append(Integer.toHexString(
6951 System.identityHashCode(mSignatures[i])));
6952 }
6953 }
6954 buf.append("]}");
6955 return buf.toString();
6956 }
6957 }
6958
6959 static class PreferredActivity extends IntentFilter {
6960 final int mMatch;
6961 final String[] mSetPackages;
6962 final String[] mSetClasses;
6963 final String[] mSetComponents;
6964 final ComponentName mActivity;
6965 final String mShortActivity;
6966 String mParseError;
6967
6968 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6969 ComponentName activity) {
6970 super(filter);
6971 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6972 mActivity = activity;
6973 mShortActivity = activity.flattenToShortString();
6974 mParseError = null;
6975 if (set != null) {
6976 final int N = set.length;
6977 String[] myPackages = new String[N];
6978 String[] myClasses = new String[N];
6979 String[] myComponents = new String[N];
6980 for (int i=0; i<N; i++) {
6981 ComponentName cn = set[i];
6982 if (cn == null) {
6983 mSetPackages = null;
6984 mSetClasses = null;
6985 mSetComponents = null;
6986 return;
6987 }
6988 myPackages[i] = cn.getPackageName().intern();
6989 myClasses[i] = cn.getClassName().intern();
6990 myComponents[i] = cn.flattenToShortString().intern();
6991 }
6992 mSetPackages = myPackages;
6993 mSetClasses = myClasses;
6994 mSetComponents = myComponents;
6995 } else {
6996 mSetPackages = null;
6997 mSetClasses = null;
6998 mSetComponents = null;
6999 }
7000 }
7001
7002 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7003 IOException {
7004 mShortActivity = parser.getAttributeValue(null, "name");
7005 mActivity = ComponentName.unflattenFromString(mShortActivity);
7006 if (mActivity == null) {
7007 mParseError = "Bad activity name " + mShortActivity;
7008 }
7009 String matchStr = parser.getAttributeValue(null, "match");
7010 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7011 String setCountStr = parser.getAttributeValue(null, "set");
7012 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7013
7014 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7015 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7016 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7017
7018 int setPos = 0;
7019
7020 int outerDepth = parser.getDepth();
7021 int type;
7022 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7023 && (type != XmlPullParser.END_TAG
7024 || parser.getDepth() > outerDepth)) {
7025 if (type == XmlPullParser.END_TAG
7026 || type == XmlPullParser.TEXT) {
7027 continue;
7028 }
7029
7030 String tagName = parser.getName();
7031 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7032 // + parser.getDepth() + " tag=" + tagName);
7033 if (tagName.equals("set")) {
7034 String name = parser.getAttributeValue(null, "name");
7035 if (name == null) {
7036 if (mParseError == null) {
7037 mParseError = "No name in set tag in preferred activity "
7038 + mShortActivity;
7039 }
7040 } else if (setPos >= setCount) {
7041 if (mParseError == null) {
7042 mParseError = "Too many set tags in preferred activity "
7043 + mShortActivity;
7044 }
7045 } else {
7046 ComponentName cn = ComponentName.unflattenFromString(name);
7047 if (cn == null) {
7048 if (mParseError == null) {
7049 mParseError = "Bad set name " + name + " in preferred activity "
7050 + mShortActivity;
7051 }
7052 } else {
7053 myPackages[setPos] = cn.getPackageName();
7054 myClasses[setPos] = cn.getClassName();
7055 myComponents[setPos] = name;
7056 setPos++;
7057 }
7058 }
7059 XmlUtils.skipCurrentTag(parser);
7060 } else if (tagName.equals("filter")) {
7061 //Log.i(TAG, "Starting to parse filter...");
7062 readFromXml(parser);
7063 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7064 // + parser.getDepth() + " tag=" + parser.getName());
7065 } else {
7066 reportSettingsProblem(Log.WARN,
7067 "Unknown element under <preferred-activities>: "
7068 + parser.getName());
7069 XmlUtils.skipCurrentTag(parser);
7070 }
7071 }
7072
7073 if (setPos != setCount) {
7074 if (mParseError == null) {
7075 mParseError = "Not enough set tags (expected " + setCount
7076 + " but found " + setPos + ") in " + mShortActivity;
7077 }
7078 }
7079
7080 mSetPackages = myPackages;
7081 mSetClasses = myClasses;
7082 mSetComponents = myComponents;
7083 }
7084
7085 public void writeToXml(XmlSerializer serializer) throws IOException {
7086 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7087 serializer.attribute(null, "name", mShortActivity);
7088 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7089 serializer.attribute(null, "set", Integer.toString(NS));
7090 for (int s=0; s<NS; s++) {
7091 serializer.startTag(null, "set");
7092 serializer.attribute(null, "name", mSetComponents[s]);
7093 serializer.endTag(null, "set");
7094 }
7095 serializer.startTag(null, "filter");
7096 super.writeToXml(serializer);
7097 serializer.endTag(null, "filter");
7098 }
7099
7100 boolean sameSet(List<ResolveInfo> query, int priority) {
7101 if (mSetPackages == null) return false;
7102 final int NQ = query.size();
7103 final int NS = mSetPackages.length;
7104 int numMatch = 0;
7105 for (int i=0; i<NQ; i++) {
7106 ResolveInfo ri = query.get(i);
7107 if (ri.priority != priority) continue;
7108 ActivityInfo ai = ri.activityInfo;
7109 boolean good = false;
7110 for (int j=0; j<NS; j++) {
7111 if (mSetPackages[j].equals(ai.packageName)
7112 && mSetClasses[j].equals(ai.name)) {
7113 numMatch++;
7114 good = true;
7115 break;
7116 }
7117 }
7118 if (!good) return false;
7119 }
7120 return numMatch == NS;
7121 }
7122 }
7123
7124 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007125 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 HashSet<String> grantedPermissions = new HashSet<String>();
7128 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007133 setFlags(pkgFlags);
7134 }
7135
7136 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007137 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007138 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
7139 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 }
7141 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 /**
7144 * Settings base class for pending and resolved classes.
7145 */
7146 static class PackageSettingBase extends GrantedPermissions {
7147 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007148 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007149 File codePath;
7150 String codePathString;
7151 File resourcePath;
7152 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 private long timeStamp;
7154 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007155 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007157 boolean uidError;
7158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 PackageSignatures signatures = new PackageSignatures();
7160
7161 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 /* Explicitly disabled components */
7164 HashSet<String> disabledComponents = new HashSet<String>(0);
7165 /* Explicitly enabled components */
7166 HashSet<String> enabledComponents = new HashSet<String>(0);
7167 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7168 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007169
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007170 PackageSettingBase origPackage;
7171
Jacek Surazski65e13172009-04-28 15:26:38 +02007172 /* package name of the app that installed this package */
7173 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007175 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007176 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 super(pkgFlags);
7178 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007179 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007180 init(codePath, resourcePath, pVersionCode);
7181 }
7182
7183 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 this.codePath = codePath;
7185 this.codePathString = codePath.toString();
7186 this.resourcePath = resourcePath;
7187 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007188 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007190
Jacek Surazski65e13172009-04-28 15:26:38 +02007191 public void setInstallerPackageName(String packageName) {
7192 installerPackageName = packageName;
7193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007194
Jacek Surazski65e13172009-04-28 15:26:38 +02007195 String getInstallerPackageName() {
7196 return installerPackageName;
7197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 public void setInstallStatus(int newStatus) {
7200 installStatus = newStatus;
7201 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 public int getInstallStatus() {
7204 return installStatus;
7205 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 public void setTimeStamp(long newStamp) {
7208 if (newStamp != timeStamp) {
7209 timeStamp = newStamp;
7210 timeStampString = Long.toString(newStamp);
7211 }
7212 }
7213
7214 public void setTimeStamp(long newStamp, String newStampStr) {
7215 timeStamp = newStamp;
7216 timeStampString = newStampStr;
7217 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 public long getTimeStamp() {
7220 return timeStamp;
7221 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007223 public String getTimeStampStr() {
7224 return timeStampString;
7225 }
7226
7227 public void copyFrom(PackageSettingBase base) {
7228 grantedPermissions = base.grantedPermissions;
7229 gids = base.gids;
7230 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 timeStamp = base.timeStamp;
7233 timeStampString = base.timeStampString;
7234 signatures = base.signatures;
7235 permissionsFixed = base.permissionsFixed;
7236 disabledComponents = base.disabledComponents;
7237 enabledComponents = base.enabledComponents;
7238 enabled = base.enabled;
7239 installStatus = base.installStatus;
7240 }
7241
7242 void enableComponentLP(String componentClassName) {
7243 disabledComponents.remove(componentClassName);
7244 enabledComponents.add(componentClassName);
7245 }
7246
7247 void disableComponentLP(String componentClassName) {
7248 enabledComponents.remove(componentClassName);
7249 disabledComponents.add(componentClassName);
7250 }
7251
7252 void restoreComponentLP(String componentClassName) {
7253 enabledComponents.remove(componentClassName);
7254 disabledComponents.remove(componentClassName);
7255 }
7256
7257 int currentEnabledStateLP(String componentName) {
7258 if (enabledComponents.contains(componentName)) {
7259 return COMPONENT_ENABLED_STATE_ENABLED;
7260 } else if (disabledComponents.contains(componentName)) {
7261 return COMPONENT_ENABLED_STATE_DISABLED;
7262 } else {
7263 return COMPONENT_ENABLED_STATE_DEFAULT;
7264 }
7265 }
7266 }
7267
7268 /**
7269 * Settings data for a particular package we know about.
7270 */
7271 static final class PackageSetting extends PackageSettingBase {
7272 int userId;
7273 PackageParser.Package pkg;
7274 SharedUserSetting sharedUser;
7275
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007276 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007277 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007278 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007281 @Override
7282 public String toString() {
7283 return "PackageSetting{"
7284 + Integer.toHexString(System.identityHashCode(this))
7285 + " " + name + "/" + userId + "}";
7286 }
7287 }
7288
7289 /**
7290 * Settings data for a particular shared user ID we know about.
7291 */
7292 static final class SharedUserSetting extends GrantedPermissions {
7293 final String name;
7294 int userId;
7295 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7296 final PackageSignatures signatures = new PackageSignatures();
7297
7298 SharedUserSetting(String _name, int _pkgFlags) {
7299 super(_pkgFlags);
7300 name = _name;
7301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 @Override
7304 public String toString() {
7305 return "SharedUserSetting{"
7306 + Integer.toHexString(System.identityHashCode(this))
7307 + " " + name + "/" + userId + "}";
7308 }
7309 }
7310
7311 /**
7312 * Holds information about dynamic settings.
7313 */
7314 private static final class Settings {
7315 private final File mSettingsFilename;
7316 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007317 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007318 private final HashMap<String, PackageSetting> mPackages =
7319 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 // List of replaced system applications
7321 final HashMap<String, PackageSetting> mDisabledSysPackages =
7322 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 // The user's preferred activities associated with particular intent
7325 // filters.
7326 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7327 new IntentResolver<PreferredActivity, PreferredActivity>() {
7328 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007329 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007331 out.print(prefix); out.print(
7332 Integer.toHexString(System.identityHashCode(filter)));
7333 out.print(' ');
7334 out.print(filter.mActivity.flattenToShortString());
7335 out.print(" match=0x");
7336 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007338 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007339 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007340 out.print(prefix); out.print(" ");
7341 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 }
7343 }
7344 }
7345 };
7346 private final HashMap<String, SharedUserSetting> mSharedUsers =
7347 new HashMap<String, SharedUserSetting>();
7348 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7349 private final SparseArray<Object> mOtherUserIds =
7350 new SparseArray<Object>();
7351
7352 // For reading/writing settings file.
7353 private final ArrayList<Signature> mPastSignatures =
7354 new ArrayList<Signature>();
7355
7356 // Mapping from permission names to info about them.
7357 final HashMap<String, BasePermission> mPermissions =
7358 new HashMap<String, BasePermission>();
7359
7360 // Mapping from permission tree names to info about them.
7361 final HashMap<String, BasePermission> mPermissionTrees =
7362 new HashMap<String, BasePermission>();
7363
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007364 // Packages that have been uninstalled and still need their external
7365 // storage data deleted.
7366 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7367
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007368 // Packages that have been renamed since they were first installed.
7369 // Keys are the new names of the packages, values are the original
7370 // names. The packages appear everwhere else under their original
7371 // names.
7372 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007374 private final StringBuilder mReadMessages = new StringBuilder();
7375
7376 private static final class PendingPackage extends PackageSettingBase {
7377 final int sharedId;
7378
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007379 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007380 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007381 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 this.sharedId = sharedId;
7383 }
7384 }
7385 private final ArrayList<PendingPackage> mPendingPackages
7386 = new ArrayList<PendingPackage>();
7387
7388 Settings() {
7389 File dataDir = Environment.getDataDirectory();
7390 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007391 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7392 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007394 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 FileUtils.setPermissions(systemDir.toString(),
7396 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7397 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7398 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007399 FileUtils.setPermissions(systemSecureDir.toString(),
7400 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7401 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7402 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 mSettingsFilename = new File(systemDir, "packages.xml");
7404 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007405 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 }
7407
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007408 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007409 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410 int pkgFlags, boolean create, boolean add) {
7411 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007412 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007413 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 return p;
7415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007416
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007417 PackageSetting peekPackageLP(String name) {
7418 return mPackages.get(name);
7419 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 PackageSetting p = mPackages.get(name);
7421 if (p != null && p.codePath.getPath().equals(codePath)) {
7422 return p;
7423 }
7424 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007425 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 void setInstallStatus(String pkgName, int status) {
7429 PackageSetting p = mPackages.get(pkgName);
7430 if(p != null) {
7431 if(p.getInstallStatus() != status) {
7432 p.setInstallStatus(status);
7433 }
7434 }
7435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007436
Jacek Surazski65e13172009-04-28 15:26:38 +02007437 void setInstallerPackageName(String pkgName,
7438 String installerPkgName) {
7439 PackageSetting p = mPackages.get(pkgName);
7440 if(p != null) {
7441 p.setInstallerPackageName(installerPkgName);
7442 }
7443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007444
Jacek Surazski65e13172009-04-28 15:26:38 +02007445 String getInstallerPackageName(String pkgName) {
7446 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007447 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007448 }
7449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007450 int getInstallStatus(String pkgName) {
7451 PackageSetting p = mPackages.get(pkgName);
7452 if(p != null) {
7453 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 return -1;
7456 }
7457
7458 SharedUserSetting getSharedUserLP(String name,
7459 int pkgFlags, boolean create) {
7460 SharedUserSetting s = mSharedUsers.get(name);
7461 if (s == null) {
7462 if (!create) {
7463 return null;
7464 }
7465 s = new SharedUserSetting(name, pkgFlags);
7466 if (MULTIPLE_APPLICATION_UIDS) {
7467 s.userId = newUserIdLP(s);
7468 } else {
7469 s.userId = FIRST_APPLICATION_UID;
7470 }
7471 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7472 // < 0 means we couldn't assign a userid; fall out and return
7473 // s, which is currently null
7474 if (s.userId >= 0) {
7475 mSharedUsers.put(name, s);
7476 }
7477 }
7478
7479 return s;
7480 }
7481
7482 int disableSystemPackageLP(String name) {
7483 PackageSetting p = mPackages.get(name);
7484 if(p == null) {
7485 Log.w(TAG, "Package:"+name+" is not an installed package");
7486 return -1;
7487 }
7488 PackageSetting dp = mDisabledSysPackages.get(name);
7489 // always make sure the system package code and resource paths dont change
7490 if(dp == null) {
7491 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7492 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7493 }
7494 mDisabledSysPackages.put(name, p);
7495 }
7496 return removePackageLP(name);
7497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 PackageSetting enableSystemPackageLP(String name) {
7500 PackageSetting p = mDisabledSysPackages.get(name);
7501 if(p == null) {
7502 Log.w(TAG, "Package:"+name+" is not disabled");
7503 return null;
7504 }
7505 // Reset flag in ApplicationInfo object
7506 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7507 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7508 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007509 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007510 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 mDisabledSysPackages.remove(name);
7512 return ret;
7513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007514
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007515 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007516 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007517 PackageSetting p = mPackages.get(name);
7518 if (p != null) {
7519 if (p.userId == uid) {
7520 return p;
7521 }
7522 reportSettingsProblem(Log.ERROR,
7523 "Adding duplicate package, keeping first: " + name);
7524 return null;
7525 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007526 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 p.userId = uid;
7528 if (addUserIdLP(uid, p, name)) {
7529 mPackages.put(name, p);
7530 return p;
7531 }
7532 return null;
7533 }
7534
7535 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7536 SharedUserSetting s = mSharedUsers.get(name);
7537 if (s != null) {
7538 if (s.userId == uid) {
7539 return s;
7540 }
7541 reportSettingsProblem(Log.ERROR,
7542 "Adding duplicate shared user, keeping first: " + name);
7543 return null;
7544 }
7545 s = new SharedUserSetting(name, pkgFlags);
7546 s.userId = uid;
7547 if (addUserIdLP(uid, s, name)) {
7548 mSharedUsers.put(name, s);
7549 return s;
7550 }
7551 return null;
7552 }
7553
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007554 // Transfer ownership of permissions from one package to another.
7555 private void transferPermissions(String origPkg, String newPkg) {
7556 // Transfer ownership of permissions to the new package.
7557 for (int i=0; i<2; i++) {
7558 HashMap<String, BasePermission> permissions =
7559 i == 0 ? mPermissionTrees : mPermissions;
7560 for (BasePermission bp : permissions.values()) {
7561 if (origPkg.equals(bp.sourcePackage)) {
7562 if (DEBUG_UPGRADE) Log.v(TAG,
7563 "Moving permission " + bp.name
7564 + " from pkg " + bp.sourcePackage
7565 + " to " + newPkg);
7566 bp.sourcePackage = newPkg;
7567 bp.perm = null;
7568 if (bp.pendingInfo != null) {
7569 bp.sourcePackage = newPkg;
7570 }
7571 bp.uid = 0;
7572 bp.gids = null;
7573 }
7574 }
7575 }
7576 }
7577
7578 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007579 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007580 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 PackageSetting p = mPackages.get(name);
7582 if (p != null) {
7583 if (!p.codePath.equals(codePath)) {
7584 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007585 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007586 // This is an updated system app with versions in both system
7587 // and data partition. Just let the most recent version
7588 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007589 Log.w(TAG, "Trying to update system app code path from " +
7590 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007591 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007592 // Just a change in the code path is not an issue, but
7593 // let's log a message about it.
7594 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007595 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007597 }
7598 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 reportSettingsProblem(Log.WARN,
7600 "Package " + name + " shared user changed from "
7601 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7602 + " to "
7603 + (sharedUser != null ? sharedUser.name : "<nothing>")
7604 + "; replacing with new");
7605 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007606 } else {
7607 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7608 // If what we are scanning is a system package, then
7609 // make it so, regardless of whether it was previously
7610 // installed only in the data partition.
7611 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 }
7614 }
7615 if (p == null) {
7616 // Create a new PackageSettings entry. this can end up here because
7617 // of code path mismatch or user id mismatch of an updated system partition
7618 if (!create) {
7619 return null;
7620 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007621 if (origPackage != null) {
7622 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007623 p = new PackageSetting(origPackage.name, name, codePath,
7624 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007625 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7626 + " is adopting original package " + origPackage.name);
7627 p.copyFrom(origPackage);
7628 p.sharedUser = origPackage.sharedUser;
7629 p.userId = origPackage.userId;
7630 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007631 mRenamedPackages.put(name, origPackage.name);
7632 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007633 // Update new package state.
7634 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007636 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007637 p.setTimeStamp(codePath.lastModified());
7638 p.sharedUser = sharedUser;
7639 if (sharedUser != null) {
7640 p.userId = sharedUser.userId;
7641 } else if (MULTIPLE_APPLICATION_UIDS) {
7642 // Clone the setting here for disabled system packages
7643 PackageSetting dis = mDisabledSysPackages.get(name);
7644 if (dis != null) {
7645 // For disabled packages a new setting is created
7646 // from the existing user id. This still has to be
7647 // added to list of user id's
7648 // Copy signatures from previous setting
7649 if (dis.signatures.mSignatures != null) {
7650 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7651 }
7652 p.userId = dis.userId;
7653 // Clone permissions
7654 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7655 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7656 // Clone component info
7657 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7658 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7659 // Add new setting to list of user ids
7660 addUserIdLP(p.userId, p, name);
7661 } else {
7662 // Assign new user id
7663 p.userId = newUserIdLP(p);
7664 }
7665 } else {
7666 p.userId = FIRST_APPLICATION_UID;
7667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 }
7669 if (p.userId < 0) {
7670 reportSettingsProblem(Log.WARN,
7671 "Package " + name + " could not be assigned a valid uid");
7672 return null;
7673 }
7674 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007675 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007677 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 }
7679 }
7680 return p;
7681 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007682
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007683 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007684 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007685 String codePath = pkg.applicationInfo.sourceDir;
7686 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007687 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007688 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007689 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007690 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007691 p.codePath = new File(codePath);
7692 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007693 }
7694 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007695 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007696 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007697 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007698 p.resourcePath = new File(resourcePath);
7699 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007700 }
7701 // Update version code if needed
7702 if (pkg.mVersionCode != p.versionCode) {
7703 p.versionCode = pkg.mVersionCode;
7704 }
7705 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7706 }
7707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 // Utility method that adds a PackageSetting to mPackages and
7709 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007710 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 SharedUserSetting sharedUser) {
7712 mPackages.put(name, p);
7713 if (sharedUser != null) {
7714 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7715 reportSettingsProblem(Log.ERROR,
7716 "Package " + p.name + " was user "
7717 + p.sharedUser + " but is now " + sharedUser
7718 + "; I am not changing its files so it will probably fail!");
7719 p.sharedUser.packages.remove(p);
7720 } else if (p.userId != sharedUser.userId) {
7721 reportSettingsProblem(Log.ERROR,
7722 "Package " + p.name + " was user id " + p.userId
7723 + " but is now user " + sharedUser
7724 + " with id " + sharedUser.userId
7725 + "; I am not changing its files so it will probably fail!");
7726 }
7727
7728 sharedUser.packages.add(p);
7729 p.sharedUser = sharedUser;
7730 p.userId = sharedUser.userId;
7731 }
7732 }
7733
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007734 /*
7735 * Update the shared user setting when a package using
7736 * specifying the shared user id is removed. The gids
7737 * associated with each permission of the deleted package
7738 * are removed from the shared user's gid list only if its
7739 * not in use by other permissions of packages in the
7740 * shared user setting.
7741 */
7742 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7744 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7745 return;
7746 }
7747 // No sharedUserId
7748 if (deletedPs.sharedUser == null) {
7749 return;
7750 }
7751 SharedUserSetting sus = deletedPs.sharedUser;
7752 // Update permissions
7753 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7754 boolean used = false;
7755 if (!sus.grantedPermissions.contains (eachPerm)) {
7756 continue;
7757 }
7758 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007759 if (pkg.pkg != null &&
7760 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7761 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 used = true;
7763 break;
7764 }
7765 }
7766 if (!used) {
7767 // can safely delete this permission from list
7768 sus.grantedPermissions.remove(eachPerm);
7769 sus.loadedPermissions.remove(eachPerm);
7770 }
7771 }
7772 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007773 int newGids[] = globalGids;
7774 for (String eachPerm : sus.grantedPermissions) {
7775 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007776 if (bp != null) {
7777 newGids = appendInts(newGids, bp.gids);
7778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 }
7780 sus.gids = newGids;
7781 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 private int removePackageLP(String name) {
7784 PackageSetting p = mPackages.get(name);
7785 if (p != null) {
7786 mPackages.remove(name);
7787 if (p.sharedUser != null) {
7788 p.sharedUser.packages.remove(p);
7789 if (p.sharedUser.packages.size() == 0) {
7790 mSharedUsers.remove(p.sharedUser.name);
7791 removeUserIdLP(p.sharedUser.userId);
7792 return p.sharedUser.userId;
7793 }
7794 } else {
7795 removeUserIdLP(p.userId);
7796 return p.userId;
7797 }
7798 }
7799 return -1;
7800 }
7801
7802 private boolean addUserIdLP(int uid, Object obj, Object name) {
7803 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7804 return false;
7805 }
7806
7807 if (uid >= FIRST_APPLICATION_UID) {
7808 int N = mUserIds.size();
7809 final int index = uid - FIRST_APPLICATION_UID;
7810 while (index >= N) {
7811 mUserIds.add(null);
7812 N++;
7813 }
7814 if (mUserIds.get(index) != null) {
7815 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007816 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 + " name=" + name);
7818 return false;
7819 }
7820 mUserIds.set(index, obj);
7821 } else {
7822 if (mOtherUserIds.get(uid) != null) {
7823 reportSettingsProblem(Log.ERROR,
7824 "Adding duplicate shared id: " + uid
7825 + " name=" + name);
7826 return false;
7827 }
7828 mOtherUserIds.put(uid, obj);
7829 }
7830 return true;
7831 }
7832
7833 public Object getUserIdLP(int uid) {
7834 if (uid >= FIRST_APPLICATION_UID) {
7835 int N = mUserIds.size();
7836 final int index = uid - FIRST_APPLICATION_UID;
7837 return index < N ? mUserIds.get(index) : null;
7838 } else {
7839 return mOtherUserIds.get(uid);
7840 }
7841 }
7842
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007843 private Set<String> findPackagesWithFlag(int flag) {
7844 Set<String> ret = new HashSet<String>();
7845 for (PackageSetting ps : mPackages.values()) {
7846 // Has to match atleast all the flag bits set on flag
7847 if ((ps.pkgFlags & flag) == flag) {
7848 ret.add(ps.name);
7849 }
7850 }
7851 return ret;
7852 }
7853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 private void removeUserIdLP(int uid) {
7855 if (uid >= FIRST_APPLICATION_UID) {
7856 int N = mUserIds.size();
7857 final int index = uid - FIRST_APPLICATION_UID;
7858 if (index < N) mUserIds.set(index, null);
7859 } else {
7860 mOtherUserIds.remove(uid);
7861 }
7862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 void writeLP() {
7865 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7866
7867 // Keep the old settings around until we know the new ones have
7868 // been successfully written.
7869 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007870 // Presence of backup settings file indicates that we failed
7871 // to persist settings earlier. So preserve the older
7872 // backup for future reference since the current settings
7873 // might have been corrupted.
7874 if (!mBackupSettingsFilename.exists()) {
7875 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7876 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7877 return;
7878 }
7879 } else {
7880 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007882 }
7883
7884 mPastSignatures.clear();
7885
7886 try {
7887 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7888
7889 //XmlSerializer serializer = XmlUtils.serializerInstance();
7890 XmlSerializer serializer = new FastXmlSerializer();
7891 serializer.setOutput(str, "utf-8");
7892 serializer.startDocument(null, true);
7893 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7894
7895 serializer.startTag(null, "packages");
7896
7897 serializer.startTag(null, "permission-trees");
7898 for (BasePermission bp : mPermissionTrees.values()) {
7899 writePermission(serializer, bp);
7900 }
7901 serializer.endTag(null, "permission-trees");
7902
7903 serializer.startTag(null, "permissions");
7904 for (BasePermission bp : mPermissions.values()) {
7905 writePermission(serializer, bp);
7906 }
7907 serializer.endTag(null, "permissions");
7908
7909 for (PackageSetting pkg : mPackages.values()) {
7910 writePackage(serializer, pkg);
7911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7914 writeDisabledSysPackage(serializer, pkg);
7915 }
7916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 serializer.startTag(null, "preferred-activities");
7918 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7919 serializer.startTag(null, "item");
7920 pa.writeToXml(serializer);
7921 serializer.endTag(null, "item");
7922 }
7923 serializer.endTag(null, "preferred-activities");
7924
7925 for (SharedUserSetting usr : mSharedUsers.values()) {
7926 serializer.startTag(null, "shared-user");
7927 serializer.attribute(null, "name", usr.name);
7928 serializer.attribute(null, "userId",
7929 Integer.toString(usr.userId));
7930 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7931 serializer.startTag(null, "perms");
7932 for (String name : usr.grantedPermissions) {
7933 serializer.startTag(null, "item");
7934 serializer.attribute(null, "name", name);
7935 serializer.endTag(null, "item");
7936 }
7937 serializer.endTag(null, "perms");
7938 serializer.endTag(null, "shared-user");
7939 }
7940
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007941 if (mPackagesToBeCleaned.size() > 0) {
7942 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7943 serializer.startTag(null, "cleaning-package");
7944 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7945 serializer.endTag(null, "cleaning-package");
7946 }
7947 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007948
7949 if (mRenamedPackages.size() > 0) {
7950 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7951 serializer.startTag(null, "renamed-package");
7952 serializer.attribute(null, "new", e.getKey());
7953 serializer.attribute(null, "old", e.getValue());
7954 serializer.endTag(null, "renamed-package");
7955 }
7956 }
7957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 serializer.endTag(null, "packages");
7959
7960 serializer.endDocument();
7961
7962 str.flush();
7963 str.close();
7964
7965 // New settings successfully written, old ones are no longer
7966 // needed.
7967 mBackupSettingsFilename.delete();
7968 FileUtils.setPermissions(mSettingsFilename.toString(),
7969 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7970 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7971 |FileUtils.S_IROTH,
7972 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007973
7974 // Write package list file now, use a JournaledFile.
7975 //
7976 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7977 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7978
7979 str = new FileOutputStream(journal.chooseForWrite());
7980 try {
7981 StringBuilder sb = new StringBuilder();
7982 for (PackageSetting pkg : mPackages.values()) {
7983 ApplicationInfo ai = pkg.pkg.applicationInfo;
7984 String dataPath = ai.dataDir;
7985 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7986
7987 // Avoid any application that has a space in its path
7988 // or that is handled by the system.
7989 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7990 continue;
7991
7992 // we store on each line the following information for now:
7993 //
7994 // pkgName - package name
7995 // userId - application-specific user id
7996 // debugFlag - 0 or 1 if the package is debuggable.
7997 // dataPath - path to package's data path
7998 //
7999 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8000 //
8001 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8002 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8003 // system/core/run-as/run-as.c
8004 //
8005 sb.setLength(0);
8006 sb.append(ai.packageName);
8007 sb.append(" ");
8008 sb.append((int)ai.uid);
8009 sb.append(isDebug ? " 1 " : " 0 ");
8010 sb.append(dataPath);
8011 sb.append("\n");
8012 str.write(sb.toString().getBytes());
8013 }
8014 str.flush();
8015 str.close();
8016 journal.commit();
8017 }
8018 catch (Exception e) {
8019 journal.rollback();
8020 }
8021
8022 FileUtils.setPermissions(mPackageListFilename.toString(),
8023 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8024 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8025 |FileUtils.S_IROTH,
8026 -1, -1);
8027
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008028 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029
8030 } catch(XmlPullParserException e) {
8031 Log.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 -08008032 } catch(java.io.IOException e) {
8033 Log.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 -08008034 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008035 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008036 if (mSettingsFilename.exists()) {
8037 if (!mSettingsFilename.delete()) {
8038 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8039 }
8040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 //Debug.stopMethodTracing();
8042 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008043
8044 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008045 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 serializer.startTag(null, "updated-package");
8047 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008048 if (pkg.realName != null) {
8049 serializer.attribute(null, "realName", pkg.realName);
8050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 serializer.attribute(null, "codePath", pkg.codePathString);
8052 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008053 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8055 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8056 }
8057 if (pkg.sharedUser == null) {
8058 serializer.attribute(null, "userId",
8059 Integer.toString(pkg.userId));
8060 } else {
8061 serializer.attribute(null, "sharedUserId",
8062 Integer.toString(pkg.userId));
8063 }
8064 serializer.startTag(null, "perms");
8065 if (pkg.sharedUser == null) {
8066 // If this is a shared user, the permissions will
8067 // be written there. We still need to write an
8068 // empty permissions list so permissionsFixed will
8069 // be set.
8070 for (final String name : pkg.grantedPermissions) {
8071 BasePermission bp = mPermissions.get(name);
8072 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8073 // We only need to write signature or system permissions but this wont
8074 // match the semantics of grantedPermissions. So write all permissions.
8075 serializer.startTag(null, "item");
8076 serializer.attribute(null, "name", name);
8077 serializer.endTag(null, "item");
8078 }
8079 }
8080 }
8081 serializer.endTag(null, "perms");
8082 serializer.endTag(null, "updated-package");
8083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008084
8085 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008086 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 serializer.startTag(null, "package");
8088 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008089 if (pkg.realName != null) {
8090 serializer.attribute(null, "realName", pkg.realName);
8091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 serializer.attribute(null, "codePath", pkg.codePathString);
8093 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8094 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8095 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008096 serializer.attribute(null, "flags",
8097 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008098 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008099 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008100 if (pkg.sharedUser == null) {
8101 serializer.attribute(null, "userId",
8102 Integer.toString(pkg.userId));
8103 } else {
8104 serializer.attribute(null, "sharedUserId",
8105 Integer.toString(pkg.userId));
8106 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008107 if (pkg.uidError) {
8108 serializer.attribute(null, "uidError", "true");
8109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8111 serializer.attribute(null, "enabled",
8112 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8113 ? "true" : "false");
8114 }
8115 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8116 serializer.attribute(null, "installStatus", "false");
8117 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008118 if (pkg.installerPackageName != null) {
8119 serializer.attribute(null, "installer", pkg.installerPackageName);
8120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008121 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8122 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8123 serializer.startTag(null, "perms");
8124 if (pkg.sharedUser == null) {
8125 // If this is a shared user, the permissions will
8126 // be written there. We still need to write an
8127 // empty permissions list so permissionsFixed will
8128 // be set.
8129 for (final String name : pkg.grantedPermissions) {
8130 serializer.startTag(null, "item");
8131 serializer.attribute(null, "name", name);
8132 serializer.endTag(null, "item");
8133 }
8134 }
8135 serializer.endTag(null, "perms");
8136 }
8137 if (pkg.disabledComponents.size() > 0) {
8138 serializer.startTag(null, "disabled-components");
8139 for (final String name : pkg.disabledComponents) {
8140 serializer.startTag(null, "item");
8141 serializer.attribute(null, "name", name);
8142 serializer.endTag(null, "item");
8143 }
8144 serializer.endTag(null, "disabled-components");
8145 }
8146 if (pkg.enabledComponents.size() > 0) {
8147 serializer.startTag(null, "enabled-components");
8148 for (final String name : pkg.enabledComponents) {
8149 serializer.startTag(null, "item");
8150 serializer.attribute(null, "name", name);
8151 serializer.endTag(null, "item");
8152 }
8153 serializer.endTag(null, "enabled-components");
8154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 serializer.endTag(null, "package");
8157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 void writePermission(XmlSerializer serializer, BasePermission bp)
8160 throws XmlPullParserException, java.io.IOException {
8161 if (bp.type != BasePermission.TYPE_BUILTIN
8162 && bp.sourcePackage != null) {
8163 serializer.startTag(null, "item");
8164 serializer.attribute(null, "name", bp.name);
8165 serializer.attribute(null, "package", bp.sourcePackage);
8166 if (DEBUG_SETTINGS) Log.v(TAG,
8167 "Writing perm: name=" + bp.name + " type=" + bp.type);
8168 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8169 PermissionInfo pi = bp.perm != null ? bp.perm.info
8170 : bp.pendingInfo;
8171 if (pi != null) {
8172 serializer.attribute(null, "type", "dynamic");
8173 if (pi.icon != 0) {
8174 serializer.attribute(null, "icon",
8175 Integer.toString(pi.icon));
8176 }
8177 if (pi.nonLocalizedLabel != null) {
8178 serializer.attribute(null, "label",
8179 pi.nonLocalizedLabel.toString());
8180 }
8181 if (pi.protectionLevel !=
8182 PermissionInfo.PROTECTION_NORMAL) {
8183 serializer.attribute(null, "protection",
8184 Integer.toString(pi.protectionLevel));
8185 }
8186 }
8187 }
8188 serializer.endTag(null, "item");
8189 }
8190 }
8191
8192 String getReadMessagesLP() {
8193 return mReadMessages.toString();
8194 }
8195
Oscar Montemayora8529f62009-11-18 10:14:20 -08008196 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8198 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008199 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 while(its.hasNext()) {
8201 String key = its.next();
8202 PackageSetting ps = mPackages.get(key);
8203 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008204 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008205 }
8206 }
8207 return ret;
8208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008210 boolean readLP() {
8211 FileInputStream str = null;
8212 if (mBackupSettingsFilename.exists()) {
8213 try {
8214 str = new FileInputStream(mBackupSettingsFilename);
8215 mReadMessages.append("Reading from backup settings file\n");
8216 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008217 if (mSettingsFilename.exists()) {
8218 // If both the backup and settings file exist, we
8219 // ignore the settings since it might have been
8220 // corrupted.
8221 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8222 mSettingsFilename.delete();
8223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 } catch (java.io.IOException e) {
8225 // We'll try for the normal settings file.
8226 }
8227 }
8228
8229 mPastSignatures.clear();
8230
8231 try {
8232 if (str == null) {
8233 if (!mSettingsFilename.exists()) {
8234 mReadMessages.append("No settings file found\n");
8235 Log.i(TAG, "No current settings file!");
8236 return false;
8237 }
8238 str = new FileInputStream(mSettingsFilename);
8239 }
8240 XmlPullParser parser = Xml.newPullParser();
8241 parser.setInput(str, null);
8242
8243 int type;
8244 while ((type=parser.next()) != XmlPullParser.START_TAG
8245 && type != XmlPullParser.END_DOCUMENT) {
8246 ;
8247 }
8248
8249 if (type != XmlPullParser.START_TAG) {
8250 mReadMessages.append("No start tag found in settings file\n");
8251 Log.e(TAG, "No start tag found in package manager settings");
8252 return false;
8253 }
8254
8255 int outerDepth = parser.getDepth();
8256 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8257 && (type != XmlPullParser.END_TAG
8258 || parser.getDepth() > outerDepth)) {
8259 if (type == XmlPullParser.END_TAG
8260 || type == XmlPullParser.TEXT) {
8261 continue;
8262 }
8263
8264 String tagName = parser.getName();
8265 if (tagName.equals("package")) {
8266 readPackageLP(parser);
8267 } else if (tagName.equals("permissions")) {
8268 readPermissionsLP(mPermissions, parser);
8269 } else if (tagName.equals("permission-trees")) {
8270 readPermissionsLP(mPermissionTrees, parser);
8271 } else if (tagName.equals("shared-user")) {
8272 readSharedUserLP(parser);
8273 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008274 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 } else if (tagName.equals("preferred-activities")) {
8276 readPreferredActivitiesLP(parser);
8277 } else if(tagName.equals("updated-package")) {
8278 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008279 } else if (tagName.equals("cleaning-package")) {
8280 String name = parser.getAttributeValue(null, "name");
8281 if (name != null) {
8282 mPackagesToBeCleaned.add(name);
8283 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008284 } else if (tagName.equals("renamed-package")) {
8285 String nname = parser.getAttributeValue(null, "new");
8286 String oname = parser.getAttributeValue(null, "old");
8287 if (nname != null && oname != null) {
8288 mRenamedPackages.put(nname, oname);
8289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 } else {
8291 Log.w(TAG, "Unknown element under <packages>: "
8292 + parser.getName());
8293 XmlUtils.skipCurrentTag(parser);
8294 }
8295 }
8296
8297 str.close();
8298
8299 } catch(XmlPullParserException e) {
8300 mReadMessages.append("Error reading: " + e.toString());
8301 Log.e(TAG, "Error reading package manager settings", e);
8302
8303 } catch(java.io.IOException e) {
8304 mReadMessages.append("Error reading: " + e.toString());
8305 Log.e(TAG, "Error reading package manager settings", e);
8306
8307 }
8308
8309 int N = mPendingPackages.size();
8310 for (int i=0; i<N; i++) {
8311 final PendingPackage pp = mPendingPackages.get(i);
8312 Object idObj = getUserIdLP(pp.sharedId);
8313 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008314 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008315 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008316 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 if (p == null) {
8318 Log.w(TAG, "Unable to create application package for "
8319 + pp.name);
8320 continue;
8321 }
8322 p.copyFrom(pp);
8323 } else if (idObj != null) {
8324 String msg = "Bad package setting: package " + pp.name
8325 + " has shared uid " + pp.sharedId
8326 + " that is not a shared uid\n";
8327 mReadMessages.append(msg);
8328 Log.e(TAG, msg);
8329 } else {
8330 String msg = "Bad package setting: package " + pp.name
8331 + " has shared uid " + pp.sharedId
8332 + " that is not defined\n";
8333 mReadMessages.append(msg);
8334 Log.e(TAG, msg);
8335 }
8336 }
8337 mPendingPackages.clear();
8338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 mReadMessages.append("Read completed successfully: "
8340 + mPackages.size() + " packages, "
8341 + mSharedUsers.size() + " shared uids\n");
8342
8343 return true;
8344 }
8345
8346 private int readInt(XmlPullParser parser, String ns, String name,
8347 int defValue) {
8348 String v = parser.getAttributeValue(ns, name);
8349 try {
8350 if (v == null) {
8351 return defValue;
8352 }
8353 return Integer.parseInt(v);
8354 } catch (NumberFormatException e) {
8355 reportSettingsProblem(Log.WARN,
8356 "Error in package manager settings: attribute " +
8357 name + " has bad integer value " + v + " at "
8358 + parser.getPositionDescription());
8359 }
8360 return defValue;
8361 }
8362
8363 private void readPermissionsLP(HashMap<String, BasePermission> out,
8364 XmlPullParser parser)
8365 throws IOException, XmlPullParserException {
8366 int outerDepth = parser.getDepth();
8367 int type;
8368 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8369 && (type != XmlPullParser.END_TAG
8370 || parser.getDepth() > outerDepth)) {
8371 if (type == XmlPullParser.END_TAG
8372 || type == XmlPullParser.TEXT) {
8373 continue;
8374 }
8375
8376 String tagName = parser.getName();
8377 if (tagName.equals("item")) {
8378 String name = parser.getAttributeValue(null, "name");
8379 String sourcePackage = parser.getAttributeValue(null, "package");
8380 String ptype = parser.getAttributeValue(null, "type");
8381 if (name != null && sourcePackage != null) {
8382 boolean dynamic = "dynamic".equals(ptype);
8383 BasePermission bp = new BasePermission(name, sourcePackage,
8384 dynamic
8385 ? BasePermission.TYPE_DYNAMIC
8386 : BasePermission.TYPE_NORMAL);
8387 if (dynamic) {
8388 PermissionInfo pi = new PermissionInfo();
8389 pi.packageName = sourcePackage.intern();
8390 pi.name = name.intern();
8391 pi.icon = readInt(parser, null, "icon", 0);
8392 pi.nonLocalizedLabel = parser.getAttributeValue(
8393 null, "label");
8394 pi.protectionLevel = readInt(parser, null, "protection",
8395 PermissionInfo.PROTECTION_NORMAL);
8396 bp.pendingInfo = pi;
8397 }
8398 out.put(bp.name, bp);
8399 } else {
8400 reportSettingsProblem(Log.WARN,
8401 "Error in package manager settings: permissions has"
8402 + " no name at " + parser.getPositionDescription());
8403 }
8404 } else {
8405 reportSettingsProblem(Log.WARN,
8406 "Unknown element reading permissions: "
8407 + parser.getName() + " at "
8408 + parser.getPositionDescription());
8409 }
8410 XmlUtils.skipCurrentTag(parser);
8411 }
8412 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008415 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008417 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 String codePathStr = parser.getAttributeValue(null, "codePath");
8419 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008420 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008421 resourcePathStr = codePathStr;
8422 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008423 String version = parser.getAttributeValue(null, "version");
8424 int versionCode = 0;
8425 if (version != null) {
8426 try {
8427 versionCode = Integer.parseInt(version);
8428 } catch (NumberFormatException e) {
8429 }
8430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 int pkgFlags = 0;
8433 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008434 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008435 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008436 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008437 String timeStampStr = parser.getAttributeValue(null, "ts");
8438 if (timeStampStr != null) {
8439 try {
8440 long timeStamp = Long.parseLong(timeStampStr);
8441 ps.setTimeStamp(timeStamp, timeStampStr);
8442 } catch (NumberFormatException e) {
8443 }
8444 }
8445 String idStr = parser.getAttributeValue(null, "userId");
8446 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8447 if(ps.userId <= 0) {
8448 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8449 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8450 }
8451 int outerDepth = parser.getDepth();
8452 int type;
8453 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8454 && (type != XmlPullParser.END_TAG
8455 || parser.getDepth() > outerDepth)) {
8456 if (type == XmlPullParser.END_TAG
8457 || type == XmlPullParser.TEXT) {
8458 continue;
8459 }
8460
8461 String tagName = parser.getName();
8462 if (tagName.equals("perms")) {
8463 readGrantedPermissionsLP(parser,
8464 ps.grantedPermissions);
8465 } else {
8466 reportSettingsProblem(Log.WARN,
8467 "Unknown element under <updated-package>: "
8468 + parser.getName());
8469 XmlUtils.skipCurrentTag(parser);
8470 }
8471 }
8472 mDisabledSysPackages.put(name, ps);
8473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 private void readPackageLP(XmlPullParser parser)
8476 throws XmlPullParserException, IOException {
8477 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008478 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 String idStr = null;
8480 String sharedIdStr = null;
8481 String codePathStr = null;
8482 String resourcePathStr = null;
8483 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008484 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008485 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 int pkgFlags = 0;
8487 String timeStampStr;
8488 long timeStamp = 0;
8489 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008490 String version = null;
8491 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008492 try {
8493 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008494 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008496 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8498 codePathStr = parser.getAttributeValue(null, "codePath");
8499 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008500 version = parser.getAttributeValue(null, "version");
8501 if (version != null) {
8502 try {
8503 versionCode = Integer.parseInt(version);
8504 } catch (NumberFormatException e) {
8505 }
8506 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008507 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008508
8509 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008510 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008511 try {
8512 pkgFlags = Integer.parseInt(systemStr);
8513 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514 }
8515 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008516 // For backward compatibility
8517 systemStr = parser.getAttributeValue(null, "system");
8518 if (systemStr != null) {
8519 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8520 } else {
8521 // Old settings that don't specify system... just treat
8522 // them as system, good enough.
8523 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 }
8526 timeStampStr = parser.getAttributeValue(null, "ts");
8527 if (timeStampStr != null) {
8528 try {
8529 timeStamp = Long.parseLong(timeStampStr);
8530 } catch (NumberFormatException e) {
8531 }
8532 }
8533 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8534 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8535 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8536 if (resourcePathStr == null) {
8537 resourcePathStr = codePathStr;
8538 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008539 if (realName != null) {
8540 realName = realName.intern();
8541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 if (name == null) {
8543 reportSettingsProblem(Log.WARN,
8544 "Error in package manager settings: <package> has no name at "
8545 + parser.getPositionDescription());
8546 } else if (codePathStr == null) {
8547 reportSettingsProblem(Log.WARN,
8548 "Error in package manager settings: <package> has no codePath at "
8549 + parser.getPositionDescription());
8550 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008551 packageSetting = addPackageLP(name.intern(), realName,
8552 new File(codePathStr), new File(resourcePathStr),
8553 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8555 + ": userId=" + userId + " pkg=" + packageSetting);
8556 if (packageSetting == null) {
8557 reportSettingsProblem(Log.ERROR,
8558 "Failure adding uid " + userId
8559 + " while parsing settings at "
8560 + parser.getPositionDescription());
8561 } else {
8562 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8563 }
8564 } else if (sharedIdStr != null) {
8565 userId = sharedIdStr != null
8566 ? Integer.parseInt(sharedIdStr) : 0;
8567 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008568 packageSetting = new PendingPackage(name.intern(), realName,
8569 new File(codePathStr), new File(resourcePathStr),
8570 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8572 mPendingPackages.add((PendingPackage) packageSetting);
8573 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8574 + ": sharedUserId=" + userId + " pkg="
8575 + packageSetting);
8576 } else {
8577 reportSettingsProblem(Log.WARN,
8578 "Error in package manager settings: package "
8579 + name + " has bad sharedId " + sharedIdStr
8580 + " at " + parser.getPositionDescription());
8581 }
8582 } else {
8583 reportSettingsProblem(Log.WARN,
8584 "Error in package manager settings: package "
8585 + name + " has bad userId " + idStr + " at "
8586 + parser.getPositionDescription());
8587 }
8588 } catch (NumberFormatException e) {
8589 reportSettingsProblem(Log.WARN,
8590 "Error in package manager settings: package "
8591 + name + " has bad userId " + idStr + " at "
8592 + parser.getPositionDescription());
8593 }
8594 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008595 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008596 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 final String enabledStr = parser.getAttributeValue(null, "enabled");
8598 if (enabledStr != null) {
8599 if (enabledStr.equalsIgnoreCase("true")) {
8600 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8601 } else if (enabledStr.equalsIgnoreCase("false")) {
8602 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8603 } else if (enabledStr.equalsIgnoreCase("default")) {
8604 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8605 } else {
8606 reportSettingsProblem(Log.WARN,
8607 "Error in package manager settings: package "
8608 + name + " has bad enabled value: " + idStr
8609 + " at " + parser.getPositionDescription());
8610 }
8611 } else {
8612 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8613 }
8614 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8615 if (installStatusStr != null) {
8616 if (installStatusStr.equalsIgnoreCase("false")) {
8617 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8618 } else {
8619 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8620 }
8621 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 int outerDepth = parser.getDepth();
8624 int type;
8625 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8626 && (type != XmlPullParser.END_TAG
8627 || parser.getDepth() > outerDepth)) {
8628 if (type == XmlPullParser.END_TAG
8629 || type == XmlPullParser.TEXT) {
8630 continue;
8631 }
8632
8633 String tagName = parser.getName();
8634 if (tagName.equals("disabled-components")) {
8635 readDisabledComponentsLP(packageSetting, parser);
8636 } else if (tagName.equals("enabled-components")) {
8637 readEnabledComponentsLP(packageSetting, parser);
8638 } else if (tagName.equals("sigs")) {
8639 packageSetting.signatures.readXml(parser, mPastSignatures);
8640 } else if (tagName.equals("perms")) {
8641 readGrantedPermissionsLP(parser,
8642 packageSetting.loadedPermissions);
8643 packageSetting.permissionsFixed = true;
8644 } else {
8645 reportSettingsProblem(Log.WARN,
8646 "Unknown element under <package>: "
8647 + parser.getName());
8648 XmlUtils.skipCurrentTag(parser);
8649 }
8650 }
8651 } else {
8652 XmlUtils.skipCurrentTag(parser);
8653 }
8654 }
8655
8656 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8657 XmlPullParser parser)
8658 throws IOException, XmlPullParserException {
8659 int outerDepth = parser.getDepth();
8660 int type;
8661 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8662 && (type != XmlPullParser.END_TAG
8663 || parser.getDepth() > outerDepth)) {
8664 if (type == XmlPullParser.END_TAG
8665 || type == XmlPullParser.TEXT) {
8666 continue;
8667 }
8668
8669 String tagName = parser.getName();
8670 if (tagName.equals("item")) {
8671 String name = parser.getAttributeValue(null, "name");
8672 if (name != null) {
8673 packageSetting.disabledComponents.add(name.intern());
8674 } else {
8675 reportSettingsProblem(Log.WARN,
8676 "Error in package manager settings: <disabled-components> has"
8677 + " no name at " + parser.getPositionDescription());
8678 }
8679 } else {
8680 reportSettingsProblem(Log.WARN,
8681 "Unknown element under <disabled-components>: "
8682 + parser.getName());
8683 }
8684 XmlUtils.skipCurrentTag(parser);
8685 }
8686 }
8687
8688 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8689 XmlPullParser parser)
8690 throws IOException, XmlPullParserException {
8691 int outerDepth = parser.getDepth();
8692 int type;
8693 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8694 && (type != XmlPullParser.END_TAG
8695 || parser.getDepth() > outerDepth)) {
8696 if (type == XmlPullParser.END_TAG
8697 || type == XmlPullParser.TEXT) {
8698 continue;
8699 }
8700
8701 String tagName = parser.getName();
8702 if (tagName.equals("item")) {
8703 String name = parser.getAttributeValue(null, "name");
8704 if (name != null) {
8705 packageSetting.enabledComponents.add(name.intern());
8706 } else {
8707 reportSettingsProblem(Log.WARN,
8708 "Error in package manager settings: <enabled-components> has"
8709 + " no name at " + parser.getPositionDescription());
8710 }
8711 } else {
8712 reportSettingsProblem(Log.WARN,
8713 "Unknown element under <enabled-components>: "
8714 + parser.getName());
8715 }
8716 XmlUtils.skipCurrentTag(parser);
8717 }
8718 }
8719
8720 private void readSharedUserLP(XmlPullParser parser)
8721 throws XmlPullParserException, IOException {
8722 String name = null;
8723 String idStr = null;
8724 int pkgFlags = 0;
8725 SharedUserSetting su = null;
8726 try {
8727 name = parser.getAttributeValue(null, "name");
8728 idStr = parser.getAttributeValue(null, "userId");
8729 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8730 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8731 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8732 }
8733 if (name == null) {
8734 reportSettingsProblem(Log.WARN,
8735 "Error in package manager settings: <shared-user> has no name at "
8736 + parser.getPositionDescription());
8737 } else if (userId == 0) {
8738 reportSettingsProblem(Log.WARN,
8739 "Error in package manager settings: shared-user "
8740 + name + " has bad userId " + idStr + " at "
8741 + parser.getPositionDescription());
8742 } else {
8743 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8744 reportSettingsProblem(Log.ERROR,
8745 "Occurred while parsing settings at "
8746 + parser.getPositionDescription());
8747 }
8748 }
8749 } catch (NumberFormatException e) {
8750 reportSettingsProblem(Log.WARN,
8751 "Error in package manager settings: package "
8752 + name + " has bad userId " + idStr + " at "
8753 + parser.getPositionDescription());
8754 };
8755
8756 if (su != null) {
8757 int outerDepth = parser.getDepth();
8758 int type;
8759 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8760 && (type != XmlPullParser.END_TAG
8761 || parser.getDepth() > outerDepth)) {
8762 if (type == XmlPullParser.END_TAG
8763 || type == XmlPullParser.TEXT) {
8764 continue;
8765 }
8766
8767 String tagName = parser.getName();
8768 if (tagName.equals("sigs")) {
8769 su.signatures.readXml(parser, mPastSignatures);
8770 } else if (tagName.equals("perms")) {
8771 readGrantedPermissionsLP(parser, su.loadedPermissions);
8772 } else {
8773 reportSettingsProblem(Log.WARN,
8774 "Unknown element under <shared-user>: "
8775 + parser.getName());
8776 XmlUtils.skipCurrentTag(parser);
8777 }
8778 }
8779
8780 } else {
8781 XmlUtils.skipCurrentTag(parser);
8782 }
8783 }
8784
8785 private void readGrantedPermissionsLP(XmlPullParser parser,
8786 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8787 int outerDepth = parser.getDepth();
8788 int type;
8789 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8790 && (type != XmlPullParser.END_TAG
8791 || parser.getDepth() > outerDepth)) {
8792 if (type == XmlPullParser.END_TAG
8793 || type == XmlPullParser.TEXT) {
8794 continue;
8795 }
8796
8797 String tagName = parser.getName();
8798 if (tagName.equals("item")) {
8799 String name = parser.getAttributeValue(null, "name");
8800 if (name != null) {
8801 outPerms.add(name.intern());
8802 } else {
8803 reportSettingsProblem(Log.WARN,
8804 "Error in package manager settings: <perms> has"
8805 + " no name at " + parser.getPositionDescription());
8806 }
8807 } else {
8808 reportSettingsProblem(Log.WARN,
8809 "Unknown element under <perms>: "
8810 + parser.getName());
8811 }
8812 XmlUtils.skipCurrentTag(parser);
8813 }
8814 }
8815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 private void readPreferredActivitiesLP(XmlPullParser parser)
8817 throws XmlPullParserException, IOException {
8818 int outerDepth = parser.getDepth();
8819 int type;
8820 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8821 && (type != XmlPullParser.END_TAG
8822 || parser.getDepth() > outerDepth)) {
8823 if (type == XmlPullParser.END_TAG
8824 || type == XmlPullParser.TEXT) {
8825 continue;
8826 }
8827
8828 String tagName = parser.getName();
8829 if (tagName.equals("item")) {
8830 PreferredActivity pa = new PreferredActivity(parser);
8831 if (pa.mParseError == null) {
8832 mPreferredActivities.addFilter(pa);
8833 } else {
8834 reportSettingsProblem(Log.WARN,
8835 "Error in package manager settings: <preferred-activity> "
8836 + pa.mParseError + " at "
8837 + parser.getPositionDescription());
8838 }
8839 } else {
8840 reportSettingsProblem(Log.WARN,
8841 "Unknown element under <preferred-activities>: "
8842 + parser.getName());
8843 XmlUtils.skipCurrentTag(parser);
8844 }
8845 }
8846 }
8847
8848 // Returns -1 if we could not find an available UserId to assign
8849 private int newUserIdLP(Object obj) {
8850 // Let's be stupidly inefficient for now...
8851 final int N = mUserIds.size();
8852 for (int i=0; i<N; i++) {
8853 if (mUserIds.get(i) == null) {
8854 mUserIds.set(i, obj);
8855 return FIRST_APPLICATION_UID + i;
8856 }
8857 }
8858
8859 // None left?
8860 if (N >= MAX_APPLICATION_UIDS) {
8861 return -1;
8862 }
8863
8864 mUserIds.add(obj);
8865 return FIRST_APPLICATION_UID + N;
8866 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 public PackageSetting getDisabledSystemPkg(String name) {
8869 synchronized(mPackages) {
8870 PackageSetting ps = mDisabledSysPackages.get(name);
8871 return ps;
8872 }
8873 }
8874
8875 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8876 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8877 if (Config.LOGV) {
8878 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8879 + " componentName = " + componentInfo.name);
8880 Log.v(TAG, "enabledComponents: "
8881 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8882 Log.v(TAG, "disabledComponents: "
8883 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8884 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008885 if (packageSettings == null) {
8886 if (false) {
8887 Log.w(TAG, "WAITING FOR DEBUGGER");
8888 Debug.waitForDebugger();
8889 Log.i(TAG, "We will crash!");
8890 }
8891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8893 || ((componentInfo.enabled
8894 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8895 || (componentInfo.applicationInfo.enabled
8896 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8897 && !packageSettings.disabledComponents.contains(componentInfo.name))
8898 || packageSettings.enabledComponents.contains(componentInfo.name));
8899 }
8900 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008901
8902 // ------- apps on sdcard specific code -------
8903 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008904 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008905 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008906 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008907 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008908
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008909 private String getEncryptKey() {
8910 try {
8911 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8912 if (sdEncKey == null) {
8913 sdEncKey = SystemKeyStore.getInstance().
8914 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8915 if (sdEncKey == null) {
8916 Log.e(TAG, "Failed to create encryption keys");
8917 return null;
8918 }
8919 }
8920 return sdEncKey;
8921 } catch (NoSuchAlgorithmException nsae) {
8922 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8923 return null;
8924 }
8925 }
8926
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008927 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008928 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008929 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008930 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008931 if (list != null) {
8932 int idx = 0;
8933 int idList[] = new int[MAX_CONTAINERS];
8934 boolean neverFound = true;
8935 for (String name : list) {
8936 // Ignore null entries
8937 if (name == null) {
8938 continue;
8939 }
8940 int sidx = name.indexOf(prefix);
8941 if (sidx == -1) {
8942 // Not a temp file. just ignore
8943 continue;
8944 }
8945 String subStr = name.substring(sidx + prefix.length());
8946 idList[idx] = -1;
8947 if (subStr != null) {
8948 try {
8949 int cid = Integer.parseInt(subStr);
8950 idList[idx++] = cid;
8951 neverFound = false;
8952 } catch (NumberFormatException e) {
8953 }
8954 }
8955 }
8956 if (!neverFound) {
8957 // Sort idList
8958 Arrays.sort(idList);
8959 for (int j = 1; j <= idList.length; j++) {
8960 if (idList[j-1] != j) {
8961 tmpIdx = j;
8962 break;
8963 }
8964 }
8965 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008966 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008967 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008968 }
8969
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08008970 /*
8971 * Return true if PackageManager does have packages to be updated.
8972 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008973 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008974 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008975 synchronized (mPackages) {
8976 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8977 mediaStatus+", mMediaMounted=" + mMediaMounted);
8978 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008979 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008980 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008981 mMediaMounted = mediaStatus;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008982 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8983 ret = appList != null && appList.size() > 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008984 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008985 // Queue up an async operation since the package installation may take a little while.
8986 mHandler.post(new Runnable() {
8987 public void run() {
8988 mHandler.removeCallbacks(this);
8989 updateExternalMediaStatusInner(mediaStatus, ret);
8990 }
8991 });
8992 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008993 }
8994
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008995 private void updateExternalMediaStatusInner(boolean mediaStatus,
8996 boolean sendUpdateBroadcast) {
8997 // If we are up here that means there are packages to be
8998 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008999 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009000 if (list == null || list.length == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009001 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009002 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08009003
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009004 int uidList[] = new int[list.length];
9005 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009006 HashSet<String> removeCids = new HashSet<String>();
9007 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9008 /*HashMap<String, String> cidPathMap = new HashMap<String, String>();
9009 // Don't hold any locks when getting cache paths
9010 for (String cid : list) {
9011 String cpath = PackageHelper.getSdDir(cid);
9012 if (cpath == null) {
9013 removeCids.add(cid);
9014 } else {
9015 cidPathMap.put(cid, cpath);
9016 }
9017 }*/
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009018 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009019 for (String cid : list) {
9020 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009021 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9022 boolean failed = true;
9023 try {
9024 String pkgName = args.getPackageName();
9025 if (pkgName == null) {
9026 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009027 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009028 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9029 PackageSetting ps = mSettings.mPackages.get(pkgName);
9030 if (ps != null && ps.codePathString != null &&
9031 (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
9032 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9033 " corresponds to pkg : " + pkgName +
9034 " at code path: " + ps.codePathString);
9035 // We do have a valid package installed on sdcard
9036 processCids.put(args, ps.codePathString);
9037 failed = false;
9038 int uid = ps.userId;
9039 if (uid != -1) {
9040 uidList[num++] = uid;
9041 }
9042 }
9043 } finally {
9044 if (failed) {
9045 // Stale container on sdcard. Just delete
9046 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9047 removeCids.add(cid);
9048 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009049 }
9050 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009051 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009052 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009053 int uidArr[] = null;
9054 if (num > 0) {
9055 // Sort uid list
9056 Arrays.sort(uidList, 0, num);
9057 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009058 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009059 uidArr[0] = uidList[0];
9060 int di = 0;
9061 for (int i = 1; i < num; i++) {
9062 if (uidList[i-1] != uidList[i]) {
9063 uidArr[di++] = uidList[i];
9064 }
9065 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009066 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009067 // Process packages with valid entries.
9068 if (mediaStatus) {
9069 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9070 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9071 startCleaningPackages();
9072 } else {
9073 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9074 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9075 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009076 }
9077
9078 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9079 ArrayList<String> pkgList, int uidArr[]) {
9080 int size = pkgList.size();
9081 if (size > 0) {
9082 // Send broadcasts here
9083 Bundle extras = new Bundle();
9084 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9085 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009086 if (uidArr != null) {
9087 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9088 }
9089 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9090 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009091 sendPackageBroadcast(action, null, extras);
9092 }
9093 }
9094
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009095 /*
9096 * Look at potentially valid container ids from processCids
9097 * If package information doesn't match the one on record
9098 * or package scanning fails, the cid is added to list of
9099 * removeCids and cleaned up. Since cleaning up containers
9100 * involves destroying them, we do not want any parse
9101 * references to such stale containers. So force gc's
9102 * to avoid unnecessary crashes.
9103 */
9104 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9105 int uidArr[], boolean sendUpdateBroadcast,
9106 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009107 ArrayList<String> pkgList = new ArrayList<String>();
9108 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009109 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009110 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009111 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009112 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9113 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009114 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009115 try {
9116 // Make sure there are no container errors first.
9117 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9118 != PackageManager.INSTALL_SUCCEEDED) {
9119 Log.e(TAG, "Failed to mount cid : " + args.cid +
9120 " when installing from sdcard");
9121 continue;
9122 }
9123 // Check code path here.
9124 if (codePath == null || !codePath.equals(args.getCodePath())) {
9125 Log.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
9126 " does not match one in settings " + codePath);
9127 continue;
9128 }
9129 // Parse package
9130 int parseFlags = PackageParser.PARSE_CHATTY |
9131 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9132 PackageParser pp = new PackageParser(codePath);
9133 pp.setSeparateProcesses(mSeparateProcesses);
9134 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9135 codePath, mMetrics, parseFlags);
9136 pp = null;
9137 doGc = true;
9138 // Check for parse errors
9139 if (pkg == null) {
9140 Log.e(TAG, "Parse error when installing install pkg : "
9141 + args.cid + " from " + args.cachePath);
9142 continue;
9143 }
9144 setApplicationInfoPaths(pkg, codePath, codePath);
9145 synchronized (mInstallLock) {
9146 // Scan the package
9147 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9148 synchronized (mPackages) {
9149 // Grant permissions
9150 grantPermissionsLP(pkg, false);
9151 // Persist settings
9152 mSettings.writeLP();
9153 retCode = PackageManager.INSTALL_SUCCEEDED;
9154 pkgList.add(pkg.packageName);
9155 // Post process args
9156 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9157 }
9158 } else {
9159 Log.i(TAG, "Failed to install pkg: " +
9160 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009161 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009162 }
9163
9164 } finally {
9165 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9166 // Don't destroy container here. Wait till gc clears things up.
9167 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009168 }
9169 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009170 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009171 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009172 if (sendUpdateBroadcast) {
9173 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9174 }
9175 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009176 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009177 }
9178 // Delete any stale containers if needed.
9179 if (removeCids != null) {
9180 for (String cid : removeCids) {
9181 Log.i(TAG, "Destroying stale container : " + cid);
9182 PackageHelper.destroySdDir(cid);
9183 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009184 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009185 }
9186
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009187 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9188 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009189 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009190 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009191 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009192 Set<SdInstallArgs> keys = processCids.keySet();
9193 for (SdInstallArgs args : keys) {
9194 String cid = args.cid;
9195 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009196 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009197 // Delete package internally
9198 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9199 synchronized (mInstallLock) {
9200 boolean res = deletePackageLI(pkgName, false,
9201 PackageManager.DONT_DELETE_DATA, outInfo);
9202 if (res) {
9203 pkgList.add(pkgName);
9204 } else {
9205 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009206 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009207 }
9208 }
9209 }
9210 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009211 if (sendUpdateBroadcast) {
9212 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009213 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009214 // Force gc
9215 Runtime.getRuntime().gc();
9216 // Just unmount all valid containers.
9217 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009218 synchronized (mInstallLock) {
9219 args.doPostDeleteLI(false);
9220 }
9221 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009222 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009223
9224 public void movePackage(final String packageName,
9225 final IPackageMoveObserver observer, final int flags) {
9226 if (packageName == null) {
9227 return;
9228 }
9229 mContext.enforceCallingOrSelfPermission(
9230 android.Manifest.permission.MOVE_PACKAGE, null);
9231 int returnCode = PackageManager.MOVE_SUCCEEDED;
9232 int currFlags = 0;
9233 int newFlags = 0;
9234 synchronized (mPackages) {
9235 PackageParser.Package pkg = mPackages.get(packageName);
9236 if (pkg == null) {
9237 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9238 }
9239 // Disable moving fwd locked apps and system packages
9240 if (pkg.applicationInfo != null &&
9241 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9242 Log.w(TAG, "Cannot move system application");
9243 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9244 } else if (pkg.applicationInfo != null &&
9245 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9246 Log.w(TAG, "Cannot move forward locked app.");
9247 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9248 } else {
9249 // Find install location first
9250 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9251 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9252 Log.w(TAG, "Ambigous flags specified for move location.");
9253 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9254 } else {
9255 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9256 PackageManager.INSTALL_EXTERNAL : 0;
9257 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9258 PackageManager.INSTALL_EXTERNAL : 0;
9259 if (newFlags == currFlags) {
9260 Log.w(TAG, "No move required. Trying to move to same location");
9261 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9262 }
9263 }
9264 }
9265 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9266 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9267 } else {
9268 Message msg = mHandler.obtainMessage(INIT_COPY);
9269 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9270 pkg.applicationInfo.publicSourceDir);
9271 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9272 packageName);
9273 msg.obj = mp;
9274 mHandler.sendMessage(msg);
9275 }
9276 }
9277 }
9278
9279 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9280 // Queue up an async operation since the package deletion may take a little while.
9281 mHandler.post(new Runnable() {
9282 public void run() {
9283 mHandler.removeCallbacks(this);
9284 int returnCode = currentStatus;
9285 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9286 if (moveSucceeded) {
9287 int uid = -1;
9288 synchronized (mPackages) {
9289 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9290 }
9291 ArrayList<String> pkgList = new ArrayList<String>();
9292 pkgList.add(mp.packageName);
9293 int uidArr[] = new int[] { uid };
9294 // Send resources unavailable broadcast
9295 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9296
9297 // Update package code and resource paths
9298 synchronized (mPackages) {
9299 PackageParser.Package pkg = mPackages.get(mp.packageName);
9300 if (pkg != null) {
9301 String oldCodePath = pkg.mPath;
9302 String newCodePath = mp.targetArgs.getCodePath();
9303 String newResPath = mp.targetArgs.getResourcePath();
9304 pkg.mPath = newCodePath;
9305 // Move dex files around
9306 if (moveDexFiles(pkg)
9307 != PackageManager.INSTALL_SUCCEEDED) {
9308 // Moving of dex files failed. Set
9309 // error code and abort move.
9310 pkg.mPath = pkg.mScanPath;
9311 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9312 moveSucceeded = false;
9313 } else {
9314 pkg.mScanPath = newCodePath;
9315 pkg.applicationInfo.sourceDir = newCodePath;
9316 pkg.applicationInfo.publicSourceDir = newResPath;
9317 PackageSetting ps = (PackageSetting) pkg.mExtras;
9318 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9319 ps.codePathString = ps.codePath.getPath();
9320 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9321 ps.resourcePathString = ps.resourcePath.getPath();
9322 // Set the application info flag correctly.
9323 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9324 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9325 } else {
9326 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9327 }
9328 ps.setFlags(pkg.applicationInfo.flags);
9329 mAppDirs.remove(oldCodePath);
9330 mAppDirs.put(newCodePath, pkg);
9331 // Persist settings
9332 mSettings.writeLP();
9333 }
9334 }
9335 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009336 // Send resources available broadcast
9337 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009338 }
9339 if (!moveSucceeded){
9340 // Clean up failed installation
9341 if (mp.targetArgs != null) {
9342 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009343 returnCode);
9344 }
9345 } else {
9346 // Force a gc to clear things up.
9347 Runtime.getRuntime().gc();
9348 // Delete older code
9349 synchronized (mInstallLock) {
9350 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009351 }
9352 }
9353 IPackageMoveObserver observer = mp.observer;
9354 if (observer != null) {
9355 try {
9356 observer.packageMoved(mp.packageName, returnCode);
9357 } catch (RemoteException e) {
9358 Log.i(TAG, "Observer no longer exists.");
9359 }
9360 }
9361 }
9362 });
9363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364}