blob: b41a7d9d8bbc97250bf3f826330af393393a402e [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);
2375 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2376 // This package has been renamed to its original name. Let's
2377 // use that.
2378 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2379 }
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.
2648 pkg.mOriginalPackage = null;
2649 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) {
2730 if (pkg.mOriginalPackage != null) {
2731 Log.w(TAG, "WAITING FOR DEBUGGER");
2732 Debug.waitForDebugger();
2733 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2734 + pkg.mOriginalPackage);
2735 }
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 Hackbornb858dfd2010-02-02 10:49:14 -08002741 if (pkg.mOriginalPackage != 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);
2745 if (pkg.mOriginalPackage.equals(renamed)) {
2746 // 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
2758 } else if ((origPackage
2759 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2760 // We do have the package already installed under its
2761 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002762 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002763 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002764 origPackage = null;
2765 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002766 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002767 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2768 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2769 + " to " + pkg.packageName + ": old uid "
2770 + origPackage.sharedUser.name
2771 + " differs from " + pkg.mSharedUserId);
2772 origPackage = null;
2773 }
2774 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002775 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2776 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002777 }
2778 }
2779 }
2780
2781 if (mTransferedPackages.contains(pkg.packageName)) {
2782 Log.w(TAG, "Package " + pkg.packageName
2783 + " was transferred to another, but its .apk remains");
2784 }
2785
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002786 // Just create the setting, don't add it yet. For already existing packages
2787 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002788 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 destResourceFile, pkg.applicationInfo.flags, true, false);
2790 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002791 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2793 return null;
2794 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002795
2796 if (pkgSetting.origPackage != null) {
2797 // If we are first transitioning from an original package,
2798 // fix up the new package's name now. We need to do this after
2799 // looking up the package under its new name, so getPackageLP
2800 // can take care of fiddling things correctly.
2801 pkg.setPackageName(origPackage.name);
2802
2803 // File a report about this.
2804 String msg = "New package " + pkgSetting.realName
2805 + " renamed to replace old package " + pkgSetting.name;
2806 reportSettingsProblem(Log.WARN, msg);
2807
2808 // Make a note of it.
2809 mTransferedPackages.add(origPackage.name);
2810
2811 // No longer need to retain this.
2812 pkgSetting.origPackage = null;
2813 }
2814
2815 if (realName != null) {
2816 // Make a note of it.
2817 mTransferedPackages.add(pkg.packageName);
2818 }
2819
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002820 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 pkg.applicationInfo.uid = pkgSetting.userId;
2825 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002826
2827 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2829 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2830 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2831 return null;
2832 }
2833 // The signature has changed, but this package is in the system
2834 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002835 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 // However... if this package is part of a shared user, but it
2837 // doesn't match the signature of the shared user, let's fail.
2838 // What this means is that you can't change the signatures
2839 // associated with an overall shared user, which doesn't seem all
2840 // that unreasonable.
2841 if (pkgSetting.sharedUser != null) {
2842 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2843 pkg.mSignatures, false)) {
2844 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2845 return null;
2846 }
2847 }
2848 removeExisting = true;
2849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002850
The Android Open Source Project10592532009-03-18 17:39:46 -07002851 // Verify that this new package doesn't have any content providers
2852 // that conflict with existing packages. Only do this if the
2853 // package isn't already installed, since we don't want to break
2854 // things that are installed.
2855 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2856 int N = pkg.providers.size();
2857 int i;
2858 for (i=0; i<N; i++) {
2859 PackageParser.Provider p = pkg.providers.get(i);
2860 String names[] = p.info.authority.split(";");
2861 for (int j = 0; j < names.length; j++) {
2862 if (mProviders.containsKey(names[j])) {
2863 PackageParser.Provider other = mProviders.get(names[j]);
2864 Log.w(TAG, "Can't install because provider name " + names[j] +
2865 " (in package " + pkg.applicationInfo.packageName +
2866 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002867 + ((other != null && other.getComponentName() != null)
2868 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002869 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2870 return null;
2871 }
2872 }
2873 }
2874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 }
2876
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 final String pkgName = pkg.packageName;
2878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002880 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002882 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 if (ret != 0) {
2884 String msg = "System package " + pkg.packageName
2885 + " could not have data directory erased after signature change.";
2886 reportSettingsProblem(Log.WARN, msg);
2887 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2888 return null;
2889 }
2890 }
2891 Log.w(TAG, "System package " + pkg.packageName
2892 + " signature changed: existing data removed.");
2893 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002895
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002896 if (pkg.mAdoptPermissions != null) {
2897 // This package wants to adopt ownership of permissions from
2898 // another package.
2899 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2900 String origName = pkg.mAdoptPermissions.get(i);
2901 PackageSetting orig = mSettings.peekPackageLP(origName);
2902 if (orig != null) {
2903 if (verifyPackageUpdate(orig, pkg)) {
2904 Log.i(TAG, "Adopting permissions from "
2905 + origName + " to " + pkg.packageName);
2906 mSettings.transferPermissions(origName, pkg.packageName);
2907 }
2908 }
2909 }
2910 }
2911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 long scanFileTime = scanFile.lastModified();
2913 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2914 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2915 pkg.applicationInfo.processName = fixProcessName(
2916 pkg.applicationInfo.packageName,
2917 pkg.applicationInfo.processName,
2918 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919
2920 File dataPath;
2921 if (mPlatformPackage == pkg) {
2922 // The system package is special.
2923 dataPath = new File (Environment.getDataDirectory(), "system");
2924 pkg.applicationInfo.dataDir = dataPath.getPath();
2925 } else {
2926 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002927 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2928 if (useEncryptedFSDir) {
2929 dataPath = new File(mSecureAppDataDir, pkgName);
2930 } else {
2931 dataPath = new File(mAppDataDir, pkgName);
2932 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002933
2934 boolean uidError = false;
2935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 if (dataPath.exists()) {
2937 mOutPermissions[1] = 0;
2938 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2939 if (mOutPermissions[1] == pkg.applicationInfo.uid
2940 || !Process.supportsProcesses()) {
2941 pkg.applicationInfo.dataDir = dataPath.getPath();
2942 } else {
2943 boolean recovered = false;
2944 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2945 // If this is a system app, we can at least delete its
2946 // current data so the application will still work.
2947 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002948 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002949 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 // Old data gone!
2951 String msg = "System package " + pkg.packageName
2952 + " has changed from uid: "
2953 + mOutPermissions[1] + " to "
2954 + pkg.applicationInfo.uid + "; old data erased";
2955 reportSettingsProblem(Log.WARN, msg);
2956 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002959 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 pkg.applicationInfo.uid);
2961 if (ret == -1) {
2962 // Ack should not happen!
2963 msg = "System package " + pkg.packageName
2964 + " could not have data directory re-created after delete.";
2965 reportSettingsProblem(Log.WARN, msg);
2966 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2967 return null;
2968 }
2969 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 if (!recovered) {
2972 mHasSystemUidErrors = true;
2973 }
2974 }
2975 if (!recovered) {
2976 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2977 + pkg.applicationInfo.uid + "/fs_"
2978 + mOutPermissions[1];
2979 String msg = "Package " + pkg.packageName
2980 + " has mismatched uid: "
2981 + mOutPermissions[1] + " on disk, "
2982 + pkg.applicationInfo.uid + " in settings";
2983 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002984 mSettings.mReadMessages.append(msg);
2985 mSettings.mReadMessages.append('\n');
2986 uidError = true;
2987 if (!pkgSetting.uidError) {
2988 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 }
2991 }
2992 }
2993 pkg.applicationInfo.dataDir = dataPath.getPath();
2994 } else {
2995 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2996 Log.v(TAG, "Want this data dir: " + dataPath);
2997 //invoke installer to do the actual installation
2998 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002999 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 pkg.applicationInfo.uid);
3001 if(ret < 0) {
3002 // Error from installer
3003 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3004 return null;
3005 }
3006 } else {
3007 dataPath.mkdirs();
3008 if (dataPath.exists()) {
3009 FileUtils.setPermissions(
3010 dataPath.toString(),
3011 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3012 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3013 }
3014 }
3015 if (dataPath.exists()) {
3016 pkg.applicationInfo.dataDir = dataPath.getPath();
3017 } else {
3018 Log.w(TAG, "Unable to create data directory: " + dataPath);
3019 pkg.applicationInfo.dataDir = null;
3020 }
3021 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003022
3023 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 }
3025
3026 // Perform shared library installation and dex validation and
3027 // optimization, if this is not a system app.
3028 if (mInstaller != null) {
3029 String path = scanFile.getPath();
3030 if (scanFileNewer) {
3031 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07003032 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
3033 if (err != PackageManager.INSTALL_SUCCEEDED) {
3034 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 return null;
3036 }
3037 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003038 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003039
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003040 if ((scanMode&SCAN_NO_DEX) == 0) {
3041 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3043 return null;
3044 }
3045 }
3046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 if (mFactoryTest && pkg.requestedPermissions.contains(
3049 android.Manifest.permission.FACTORY_TEST)) {
3050 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3051 }
3052
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003053 // Request the ActivityManager to kill the process(only for existing packages)
3054 // so that we do not end up in a confused state while the user is still using the older
3055 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003056 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003057 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003058 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003059 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003062 // We don't expect installation to fail beyond this point,
3063 if ((scanMode&SCAN_MONITOR) != 0) {
3064 mAppDirs.put(pkg.mPath, pkg);
3065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003067 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003069 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003070 // Make sure we don't accidentally delete its data.
3071 mSettings.mPackagesToBeCleaned.remove(pkgName);
3072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 int N = pkg.providers.size();
3074 StringBuilder r = null;
3075 int i;
3076 for (i=0; i<N; i++) {
3077 PackageParser.Provider p = pkg.providers.get(i);
3078 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3079 p.info.processName, pkg.applicationInfo.uid);
3080 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3081 p.info.name), p);
3082 p.syncable = p.info.isSyncable;
3083 String names[] = p.info.authority.split(";");
3084 p.info.authority = null;
3085 for (int j = 0; j < names.length; j++) {
3086 if (j == 1 && p.syncable) {
3087 // We only want the first authority for a provider to possibly be
3088 // syncable, so if we already added this provider using a different
3089 // authority clear the syncable flag. We copy the provider before
3090 // changing it because the mProviders object contains a reference
3091 // to a provider that we don't want to change.
3092 // Only do this for the second authority since the resulting provider
3093 // object can be the same for all future authorities for this provider.
3094 p = new PackageParser.Provider(p);
3095 p.syncable = false;
3096 }
3097 if (!mProviders.containsKey(names[j])) {
3098 mProviders.put(names[j], p);
3099 if (p.info.authority == null) {
3100 p.info.authority = names[j];
3101 } else {
3102 p.info.authority = p.info.authority + ";" + names[j];
3103 }
3104 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3105 Log.d(TAG, "Registered content provider: " + names[j] +
3106 ", className = " + p.info.name +
3107 ", isSyncable = " + p.info.isSyncable);
3108 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07003109 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 Log.w(TAG, "Skipping provider name " + names[j] +
3111 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07003112 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003113 + ((other != null && other.getComponentName() != null)
3114 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116 }
3117 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3118 if (r == null) {
3119 r = new StringBuilder(256);
3120 } else {
3121 r.append(' ');
3122 }
3123 r.append(p.info.name);
3124 }
3125 }
3126 if (r != null) {
3127 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 N = pkg.services.size();
3131 r = null;
3132 for (i=0; i<N; i++) {
3133 PackageParser.Service s = pkg.services.get(i);
3134 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3135 s.info.processName, pkg.applicationInfo.uid);
3136 mServices.addService(s);
3137 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3138 if (r == null) {
3139 r = new StringBuilder(256);
3140 } else {
3141 r.append(' ');
3142 }
3143 r.append(s.info.name);
3144 }
3145 }
3146 if (r != null) {
3147 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3148 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 N = pkg.receivers.size();
3151 r = null;
3152 for (i=0; i<N; i++) {
3153 PackageParser.Activity a = pkg.receivers.get(i);
3154 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3155 a.info.processName, pkg.applicationInfo.uid);
3156 mReceivers.addActivity(a, "receiver");
3157 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3158 if (r == null) {
3159 r = new StringBuilder(256);
3160 } else {
3161 r.append(' ');
3162 }
3163 r.append(a.info.name);
3164 }
3165 }
3166 if (r != null) {
3167 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3168 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 N = pkg.activities.size();
3171 r = null;
3172 for (i=0; i<N; i++) {
3173 PackageParser.Activity a = pkg.activities.get(i);
3174 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3175 a.info.processName, pkg.applicationInfo.uid);
3176 mActivities.addActivity(a, "activity");
3177 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3178 if (r == null) {
3179 r = new StringBuilder(256);
3180 } else {
3181 r.append(' ');
3182 }
3183 r.append(a.info.name);
3184 }
3185 }
3186 if (r != null) {
3187 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 N = pkg.permissionGroups.size();
3191 r = null;
3192 for (i=0; i<N; i++) {
3193 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3194 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3195 if (cur == null) {
3196 mPermissionGroups.put(pg.info.name, pg);
3197 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3198 if (r == null) {
3199 r = new StringBuilder(256);
3200 } else {
3201 r.append(' ');
3202 }
3203 r.append(pg.info.name);
3204 }
3205 } else {
3206 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3207 + pg.info.packageName + " ignored: original from "
3208 + cur.info.packageName);
3209 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3210 if (r == null) {
3211 r = new StringBuilder(256);
3212 } else {
3213 r.append(' ');
3214 }
3215 r.append("DUP:");
3216 r.append(pg.info.name);
3217 }
3218 }
3219 }
3220 if (r != null) {
3221 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 N = pkg.permissions.size();
3225 r = null;
3226 for (i=0; i<N; i++) {
3227 PackageParser.Permission p = pkg.permissions.get(i);
3228 HashMap<String, BasePermission> permissionMap =
3229 p.tree ? mSettings.mPermissionTrees
3230 : mSettings.mPermissions;
3231 p.group = mPermissionGroups.get(p.info.group);
3232 if (p.info.group == null || p.group != null) {
3233 BasePermission bp = permissionMap.get(p.info.name);
3234 if (bp == null) {
3235 bp = new BasePermission(p.info.name, p.info.packageName,
3236 BasePermission.TYPE_NORMAL);
3237 permissionMap.put(p.info.name, bp);
3238 }
3239 if (bp.perm == null) {
3240 if (bp.sourcePackage == null
3241 || bp.sourcePackage.equals(p.info.packageName)) {
3242 BasePermission tree = findPermissionTreeLP(p.info.name);
3243 if (tree == null
3244 || tree.sourcePackage.equals(p.info.packageName)) {
3245 bp.perm = p;
3246 bp.uid = pkg.applicationInfo.uid;
3247 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3248 if (r == null) {
3249 r = new StringBuilder(256);
3250 } else {
3251 r.append(' ');
3252 }
3253 r.append(p.info.name);
3254 }
3255 } else {
3256 Log.w(TAG, "Permission " + p.info.name + " from package "
3257 + p.info.packageName + " ignored: base tree "
3258 + tree.name + " is from package "
3259 + tree.sourcePackage);
3260 }
3261 } else {
3262 Log.w(TAG, "Permission " + p.info.name + " from package "
3263 + p.info.packageName + " ignored: original from "
3264 + bp.sourcePackage);
3265 }
3266 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3267 if (r == null) {
3268 r = new StringBuilder(256);
3269 } else {
3270 r.append(' ');
3271 }
3272 r.append("DUP:");
3273 r.append(p.info.name);
3274 }
3275 } else {
3276 Log.w(TAG, "Permission " + p.info.name + " from package "
3277 + p.info.packageName + " ignored: no group "
3278 + p.group);
3279 }
3280 }
3281 if (r != null) {
3282 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 N = pkg.instrumentation.size();
3286 r = null;
3287 for (i=0; i<N; i++) {
3288 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3289 a.info.packageName = pkg.applicationInfo.packageName;
3290 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3291 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3292 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003293 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3295 if (r == null) {
3296 r = new StringBuilder(256);
3297 } else {
3298 r.append(' ');
3299 }
3300 r.append(a.info.name);
3301 }
3302 }
3303 if (r != null) {
3304 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003306
Dianne Hackborn854060af2009-07-09 18:14:31 -07003307 if (pkg.protectedBroadcasts != null) {
3308 N = pkg.protectedBroadcasts.size();
3309 for (i=0; i<N; i++) {
3310 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3311 }
3312 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 pkgSetting.setTimeStamp(scanFileTime);
3315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 return pkg;
3318 }
3319
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003320 private void killApplication(String pkgName, int uid) {
3321 // Request the ActivityManager to kill the process(only for existing packages)
3322 // so that we do not end up in a confused state while the user is still using the older
3323 // version of the application while the new one gets installed.
3324 IActivityManager am = ActivityManagerNative.getDefault();
3325 if (am != null) {
3326 try {
3327 am.killApplicationWithUid(pkgName, uid);
3328 } catch (RemoteException e) {
3329 }
3330 }
3331 }
3332
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003333 // The following constants are returned by cachePackageSharedLibsForAbiLI
3334 // to indicate if native shared libraries were found in the package.
3335 // Values are:
3336 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3337 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3338 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3339 // in package (and not installed)
3340 //
3341 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3342 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3343 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003345 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3346 // and automatically copy them to /data/data/<appname>/lib if present.
3347 //
3348 // NOTE: this method may throw an IOException if the library cannot
3349 // be copied to its final destination, e.g. if there isn't enough
3350 // room left on the data partition, or a ZipException if the package
3351 // file is malformed.
3352 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003353 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3354 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003355 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3356 final String apkLib = "lib/";
3357 final int apkLibLen = apkLib.length();
3358 final int cpuAbiLen = cpuAbi.length();
3359 final String libPrefix = "lib";
3360 final int libPrefixLen = libPrefix.length();
3361 final String libSuffix = ".so";
3362 final int libSuffixLen = libSuffix.length();
3363 boolean hasNativeLibraries = false;
3364 boolean installedNativeLibraries = false;
3365
3366 // the minimum length of a valid native shared library of the form
3367 // lib/<something>/lib<name>.so.
3368 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3369
3370 ZipFile zipFile = new ZipFile(scanFile);
3371 Enumeration<ZipEntry> entries =
3372 (Enumeration<ZipEntry>) zipFile.entries();
3373
3374 while (entries.hasMoreElements()) {
3375 ZipEntry entry = entries.nextElement();
3376 // skip directories
3377 if (entry.isDirectory()) {
3378 continue;
3379 }
3380 String entryName = entry.getName();
3381
3382 // check that the entry looks like lib/<something>/lib<name>.so
3383 // here, but don't check the ABI just yet.
3384 //
3385 // - must be sufficiently long
3386 // - must end with libSuffix, i.e. ".so"
3387 // - must start with apkLib, i.e. "lib/"
3388 if (entryName.length() < minEntryLen ||
3389 !entryName.endsWith(libSuffix) ||
3390 !entryName.startsWith(apkLib) ) {
3391 continue;
3392 }
3393
3394 // file name must start with libPrefix, i.e. "lib"
3395 int lastSlash = entryName.lastIndexOf('/');
3396
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003397 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003398 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3399 continue;
3400 }
3401
3402 hasNativeLibraries = true;
3403
3404 // check the cpuAbi now, between lib/ and /lib<name>.so
3405 //
3406 if (lastSlash != apkLibLen + cpuAbiLen ||
3407 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3408 continue;
3409
3410 // extract the library file name, ensure it doesn't contain
3411 // weird characters. we're guaranteed here that it doesn't contain
3412 // a directory separator though.
3413 String libFileName = entryName.substring(lastSlash+1);
3414 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3415 continue;
3416 }
3417
3418 installedNativeLibraries = true;
3419
3420 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3421 File.separator + libFileName;
3422 File sharedLibraryFile = new File(sharedLibraryFilePath);
3423 if (! sharedLibraryFile.exists() ||
3424 sharedLibraryFile.length() != entry.getSize() ||
3425 sharedLibraryFile.lastModified() != entry.getTime()) {
3426 if (Config.LOGD) {
3427 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003429 if (mInstaller == null) {
3430 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003431 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003432 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003433 sharedLibraryFile);
3434 }
3435 }
3436 if (!hasNativeLibraries)
3437 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3438
3439 if (!installedNativeLibraries)
3440 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3441
3442 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3443 }
3444
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003445 // Find the gdbserver executable program in a package at
3446 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3447 //
3448 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3449 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3450 //
3451 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3452 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3453 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3454 final String GDBSERVER = "gdbserver";
3455 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3456
3457 ZipFile zipFile = new ZipFile(scanFile);
3458 Enumeration<ZipEntry> entries =
3459 (Enumeration<ZipEntry>) zipFile.entries();
3460
3461 while (entries.hasMoreElements()) {
3462 ZipEntry entry = entries.nextElement();
3463 // skip directories
3464 if (entry.isDirectory()) {
3465 continue;
3466 }
3467 String entryName = entry.getName();
3468
3469 if (!entryName.equals(apkGdbServerPath)) {
3470 continue;
3471 }
3472
3473 String installGdbServerPath = installGdbServerDir.getPath() +
3474 "/" + GDBSERVER;
3475 File installGdbServerFile = new File(installGdbServerPath);
3476 if (! installGdbServerFile.exists() ||
3477 installGdbServerFile.length() != entry.getSize() ||
3478 installGdbServerFile.lastModified() != entry.getTime()) {
3479 if (Config.LOGD) {
3480 Log.d(TAG, "Caching gdbserver " + entry.getName());
3481 }
3482 if (mInstaller == null) {
3483 installGdbServerDir.mkdir();
3484 }
3485 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3486 installGdbServerFile);
3487 }
3488 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3489 }
3490 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3491 }
3492
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003493 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3494 // and copy them to /data/data/<appname>/lib.
3495 //
3496 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3497 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3498 // one if ro.product.cpu.abi2 is defined.
3499 //
3500 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3501 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003502 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003503 try {
3504 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3505
3506 // some architectures are capable of supporting several CPU ABIs
3507 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3508 // this is indicated by the definition of the ro.product.cpu.abi2
3509 // system property.
3510 //
3511 // only scan the package twice in case of ABI mismatch
3512 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003513 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003514 if (cpuAbi2 != null) {
3515 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003517
3518 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3519 Log.w(TAG,"Native ABI mismatch from package file");
3520 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003522
3523 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3524 cpuAbi = cpuAbi2;
3525 }
3526 }
3527
3528 // for debuggable packages, also extract gdbserver from lib/<abi>
3529 // into /data/data/<appname>/lib too.
3530 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3531 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3532 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3533 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3534 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003537 } catch (ZipException e) {
3538 Log.w(TAG, "Failed to extract data from package file", e);
3539 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003541 Log.w(TAG, "Failed to cache package shared libs", e);
3542 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003544 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
3546
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003547 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003549 File binaryDir,
3550 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 InputStream inputStream = zipFile.getInputStream(entry);
3552 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003553 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003555 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 // now need to be left as world readable and owned by the system.
3557 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3558 ! tempFile.setLastModified(entry.getTime()) ||
3559 FileUtils.setPermissions(tempFilePath,
3560 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003561 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003563 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 // Failed to properly write file.
3565 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003566 throw new IOException("Couldn't create cached binary "
3567 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569 } finally {
3570 inputStream.close();
3571 }
3572 }
3573
3574 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3575 if (chatty && Config.LOGD) Log.d(
3576 TAG, "Removing package " + pkg.applicationInfo.packageName );
3577
3578 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 mPackages.remove(pkg.applicationInfo.packageName);
3582 if (pkg.mPath != null) {
3583 mAppDirs.remove(pkg.mPath);
3584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 PackageSetting ps = (PackageSetting)pkg.mExtras;
3587 if (ps != null && ps.sharedUser != null) {
3588 // XXX don't do this until the data is removed.
3589 if (false) {
3590 ps.sharedUser.packages.remove(ps);
3591 if (ps.sharedUser.packages.size() == 0) {
3592 // Remove.
3593 }
3594 }
3595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 int N = pkg.providers.size();
3598 StringBuilder r = null;
3599 int i;
3600 for (i=0; i<N; i++) {
3601 PackageParser.Provider p = pkg.providers.get(i);
3602 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3603 p.info.name));
3604 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 /* The is another ContentProvider with this authority when
3607 * this app was installed so this authority is null,
3608 * Ignore it as we don't have to unregister the provider.
3609 */
3610 continue;
3611 }
3612 String names[] = p.info.authority.split(";");
3613 for (int j = 0; j < names.length; j++) {
3614 if (mProviders.get(names[j]) == p) {
3615 mProviders.remove(names[j]);
3616 if (chatty && Config.LOGD) Log.d(
3617 TAG, "Unregistered content provider: " + names[j] +
3618 ", className = " + p.info.name +
3619 ", isSyncable = " + p.info.isSyncable);
3620 }
3621 }
3622 if (chatty) {
3623 if (r == null) {
3624 r = new StringBuilder(256);
3625 } else {
3626 r.append(' ');
3627 }
3628 r.append(p.info.name);
3629 }
3630 }
3631 if (r != null) {
3632 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 N = pkg.services.size();
3636 r = null;
3637 for (i=0; i<N; i++) {
3638 PackageParser.Service s = pkg.services.get(i);
3639 mServices.removeService(s);
3640 if (chatty) {
3641 if (r == null) {
3642 r = new StringBuilder(256);
3643 } else {
3644 r.append(' ');
3645 }
3646 r.append(s.info.name);
3647 }
3648 }
3649 if (r != null) {
3650 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3651 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 N = pkg.receivers.size();
3654 r = null;
3655 for (i=0; i<N; i++) {
3656 PackageParser.Activity a = pkg.receivers.get(i);
3657 mReceivers.removeActivity(a, "receiver");
3658 if (chatty) {
3659 if (r == null) {
3660 r = new StringBuilder(256);
3661 } else {
3662 r.append(' ');
3663 }
3664 r.append(a.info.name);
3665 }
3666 }
3667 if (r != null) {
3668 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 N = pkg.activities.size();
3672 r = null;
3673 for (i=0; i<N; i++) {
3674 PackageParser.Activity a = pkg.activities.get(i);
3675 mActivities.removeActivity(a, "activity");
3676 if (chatty) {
3677 if (r == null) {
3678 r = new StringBuilder(256);
3679 } else {
3680 r.append(' ');
3681 }
3682 r.append(a.info.name);
3683 }
3684 }
3685 if (r != null) {
3686 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 N = pkg.permissions.size();
3690 r = null;
3691 for (i=0; i<N; i++) {
3692 PackageParser.Permission p = pkg.permissions.get(i);
3693 boolean tree = false;
3694 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3695 if (bp == null) {
3696 tree = true;
3697 bp = mSettings.mPermissionTrees.get(p.info.name);
3698 }
3699 if (bp != null && bp.perm == p) {
3700 if (bp.type != BasePermission.TYPE_BUILTIN) {
3701 if (tree) {
3702 mSettings.mPermissionTrees.remove(p.info.name);
3703 } else {
3704 mSettings.mPermissions.remove(p.info.name);
3705 }
3706 } else {
3707 bp.perm = null;
3708 }
3709 if (chatty) {
3710 if (r == null) {
3711 r = new StringBuilder(256);
3712 } else {
3713 r.append(' ');
3714 }
3715 r.append(p.info.name);
3716 }
3717 }
3718 }
3719 if (r != null) {
3720 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 N = pkg.instrumentation.size();
3724 r = null;
3725 for (i=0; i<N; i++) {
3726 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003727 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 if (chatty) {
3729 if (r == null) {
3730 r = new StringBuilder(256);
3731 } else {
3732 r.append(' ');
3733 }
3734 r.append(a.info.name);
3735 }
3736 }
3737 if (r != null) {
3738 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3739 }
3740 }
3741 }
3742
3743 private static final boolean isPackageFilename(String name) {
3744 return name != null && name.endsWith(".apk");
3745 }
3746
3747 private void updatePermissionsLP() {
3748 // Make sure there are no dangling permission trees.
3749 Iterator<BasePermission> it = mSettings.mPermissionTrees
3750 .values().iterator();
3751 while (it.hasNext()) {
3752 BasePermission bp = it.next();
3753 if (bp.perm == null) {
3754 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3755 + " from package " + bp.sourcePackage);
3756 it.remove();
3757 }
3758 }
3759
3760 // Make sure all dynamic permissions have been assigned to a package,
3761 // and make sure there are no dangling permissions.
3762 it = mSettings.mPermissions.values().iterator();
3763 while (it.hasNext()) {
3764 BasePermission bp = it.next();
3765 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3766 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3767 + bp.name + " pkg=" + bp.sourcePackage
3768 + " info=" + bp.pendingInfo);
3769 if (bp.perm == null && bp.pendingInfo != null) {
3770 BasePermission tree = findPermissionTreeLP(bp.name);
3771 if (tree != null) {
3772 bp.perm = new PackageParser.Permission(tree.perm.owner,
3773 new PermissionInfo(bp.pendingInfo));
3774 bp.perm.info.packageName = tree.perm.info.packageName;
3775 bp.perm.info.name = bp.name;
3776 bp.uid = tree.uid;
3777 }
3778 }
3779 }
3780 if (bp.perm == null) {
3781 Log.w(TAG, "Removing dangling permission: " + bp.name
3782 + " from package " + bp.sourcePackage);
3783 it.remove();
3784 }
3785 }
3786
3787 // Now update the permissions for all packages, in particular
3788 // replace the granted permissions of the system packages.
3789 for (PackageParser.Package pkg : mPackages.values()) {
3790 grantPermissionsLP(pkg, false);
3791 }
3792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3795 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3796 if (ps == null) {
3797 return;
3798 }
3799 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3800 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 if (replace) {
3803 ps.permissionsFixed = false;
3804 if (gp == ps) {
3805 gp.grantedPermissions.clear();
3806 gp.gids = mGlobalGids;
3807 }
3808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 if (gp.gids == null) {
3811 gp.gids = mGlobalGids;
3812 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 final int N = pkg.requestedPermissions.size();
3815 for (int i=0; i<N; i++) {
3816 String name = pkg.requestedPermissions.get(i);
3817 BasePermission bp = mSettings.mPermissions.get(name);
3818 PackageParser.Permission p = bp != null ? bp.perm : null;
3819 if (false) {
3820 if (gp != ps) {
3821 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3822 + ": " + p);
3823 }
3824 }
3825 if (p != null) {
3826 final String perm = p.info.name;
3827 boolean allowed;
3828 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3829 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3830 allowed = true;
3831 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3832 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003833 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003835 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 == PackageManager.SIGNATURE_MATCH);
3837 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3838 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3839 // For updated system applications, the signatureOrSystem permission
3840 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003841 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3843 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3844 if(sysPs.grantedPermissions.contains(perm)) {
3845 allowed = true;
3846 } else {
3847 allowed = false;
3848 }
3849 } else {
3850 allowed = true;
3851 }
3852 }
3853 }
3854 } else {
3855 allowed = false;
3856 }
3857 if (false) {
3858 if (gp != ps) {
3859 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3860 }
3861 }
3862 if (allowed) {
3863 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3864 && ps.permissionsFixed) {
3865 // If this is an existing, non-system package, then
3866 // we can't add any new permissions to it.
3867 if (!gp.loadedPermissions.contains(perm)) {
3868 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003869 // Except... if this is a permission that was added
3870 // to the platform (note: need to only do this when
3871 // updating the platform).
3872 final int NP = PackageParser.NEW_PERMISSIONS.length;
3873 for (int ip=0; ip<NP; ip++) {
3874 final PackageParser.NewPermissionInfo npi
3875 = PackageParser.NEW_PERMISSIONS[ip];
3876 if (npi.name.equals(perm)
3877 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3878 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003879 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003880 + pkg.packageName);
3881 break;
3882 }
3883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 }
3885 }
3886 if (allowed) {
3887 if (!gp.grantedPermissions.contains(perm)) {
3888 addedPermission = true;
3889 gp.grantedPermissions.add(perm);
3890 gp.gids = appendInts(gp.gids, bp.gids);
3891 }
3892 } else {
3893 Log.w(TAG, "Not granting permission " + perm
3894 + " to package " + pkg.packageName
3895 + " because it was previously installed without");
3896 }
3897 } else {
3898 Log.w(TAG, "Not granting permission " + perm
3899 + " to package " + pkg.packageName
3900 + " (protectionLevel=" + p.info.protectionLevel
3901 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3902 + ")");
3903 }
3904 } else {
3905 Log.w(TAG, "Unknown permission " + name
3906 + " in package " + pkg.packageName);
3907 }
3908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003911 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3912 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 // This is the first that we have heard about this package, so the
3914 // permissions we have now selected are fixed until explicitly
3915 // changed.
3916 ps.permissionsFixed = true;
3917 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3918 }
3919 }
3920
3921 private final class ActivityIntentResolver
3922 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003923 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003925 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 }
3927
Mihai Preda074edef2009-05-18 17:13:31 +02003928 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003930 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3932 }
3933
Mihai Predaeae850c2009-05-13 10:13:48 +02003934 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3935 ArrayList<PackageParser.Activity> packageActivities) {
3936 if (packageActivities == null) {
3937 return null;
3938 }
3939 mFlags = flags;
3940 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3941 int N = packageActivities.size();
3942 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3943 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003944
3945 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003946 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003947 intentFilters = packageActivities.get(i).intents;
3948 if (intentFilters != null && intentFilters.size() > 0) {
3949 listCut.add(intentFilters);
3950 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003951 }
3952 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3953 }
3954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003956 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 if (SHOW_INFO || Config.LOGV) Log.v(
3958 TAG, " " + type + " " +
3959 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3960 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3961 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003962 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3964 if (SHOW_INFO || Config.LOGV) {
3965 Log.v(TAG, " IntentFilter:");
3966 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3967 }
3968 if (!intent.debugCheck()) {
3969 Log.w(TAG, "==> For Activity " + a.info.name);
3970 }
3971 addFilter(intent);
3972 }
3973 }
3974
3975 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003976 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 if (SHOW_INFO || Config.LOGV) Log.v(
3978 TAG, " " + type + " " +
3979 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3980 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3981 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003982 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3984 if (SHOW_INFO || Config.LOGV) {
3985 Log.v(TAG, " IntentFilter:");
3986 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3987 }
3988 removeFilter(intent);
3989 }
3990 }
3991
3992 @Override
3993 protected boolean allowFilterResult(
3994 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3995 ActivityInfo filterAi = filter.activity.info;
3996 for (int i=dest.size()-1; i>=0; i--) {
3997 ActivityInfo destAi = dest.get(i).activityInfo;
3998 if (destAi.name == filterAi.name
3999 && destAi.packageName == filterAi.packageName) {
4000 return false;
4001 }
4002 }
4003 return true;
4004 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 @Override
4007 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4008 int match) {
4009 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4010 return null;
4011 }
4012 final PackageParser.Activity activity = info.activity;
4013 if (mSafeMode && (activity.info.applicationInfo.flags
4014 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4015 return null;
4016 }
4017 final ResolveInfo res = new ResolveInfo();
4018 res.activityInfo = PackageParser.generateActivityInfo(activity,
4019 mFlags);
4020 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4021 res.filter = info;
4022 }
4023 res.priority = info.getPriority();
4024 res.preferredOrder = activity.owner.mPreferredOrder;
4025 //System.out.println("Result: " + res.activityInfo.className +
4026 // " = " + res.priority);
4027 res.match = match;
4028 res.isDefault = info.hasDefault;
4029 res.labelRes = info.labelRes;
4030 res.nonLocalizedLabel = info.nonLocalizedLabel;
4031 res.icon = info.icon;
4032 return res;
4033 }
4034
4035 @Override
4036 protected void sortResults(List<ResolveInfo> results) {
4037 Collections.sort(results, mResolvePrioritySorter);
4038 }
4039
4040 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004041 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004043 out.print(prefix); out.print(
4044 Integer.toHexString(System.identityHashCode(filter.activity)));
4045 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004046 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 }
4048
4049// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4050// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4051// final List<ResolveInfo> retList = Lists.newArrayList();
4052// while (i.hasNext()) {
4053// final ResolveInfo resolveInfo = i.next();
4054// if (isEnabledLP(resolveInfo.activityInfo)) {
4055// retList.add(resolveInfo);
4056// }
4057// }
4058// return retList;
4059// }
4060
4061 // Keys are String (activity class name), values are Activity.
4062 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4063 = new HashMap<ComponentName, PackageParser.Activity>();
4064 private int mFlags;
4065 }
4066
4067 private final class ServiceIntentResolver
4068 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004069 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004071 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 }
4073
Mihai Preda074edef2009-05-18 17:13:31 +02004074 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004076 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4078 }
4079
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004080 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4081 ArrayList<PackageParser.Service> packageServices) {
4082 if (packageServices == null) {
4083 return null;
4084 }
4085 mFlags = flags;
4086 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4087 int N = packageServices.size();
4088 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4089 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4090
4091 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4092 for (int i = 0; i < N; ++i) {
4093 intentFilters = packageServices.get(i).intents;
4094 if (intentFilters != null && intentFilters.size() > 0) {
4095 listCut.add(intentFilters);
4096 }
4097 }
4098 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4099 }
4100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004102 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 if (SHOW_INFO || Config.LOGV) Log.v(
4104 TAG, " " + (s.info.nonLocalizedLabel != null
4105 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4106 if (SHOW_INFO || Config.LOGV) Log.v(
4107 TAG, " Class=" + s.info.name);
4108 int NI = s.intents.size();
4109 int j;
4110 for (j=0; j<NI; j++) {
4111 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4112 if (SHOW_INFO || Config.LOGV) {
4113 Log.v(TAG, " IntentFilter:");
4114 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4115 }
4116 if (!intent.debugCheck()) {
4117 Log.w(TAG, "==> For Service " + s.info.name);
4118 }
4119 addFilter(intent);
4120 }
4121 }
4122
4123 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004124 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 if (SHOW_INFO || Config.LOGV) Log.v(
4126 TAG, " " + (s.info.nonLocalizedLabel != null
4127 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4128 if (SHOW_INFO || Config.LOGV) Log.v(
4129 TAG, " Class=" + s.info.name);
4130 int NI = s.intents.size();
4131 int j;
4132 for (j=0; j<NI; j++) {
4133 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4134 if (SHOW_INFO || Config.LOGV) {
4135 Log.v(TAG, " IntentFilter:");
4136 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4137 }
4138 removeFilter(intent);
4139 }
4140 }
4141
4142 @Override
4143 protected boolean allowFilterResult(
4144 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4145 ServiceInfo filterSi = filter.service.info;
4146 for (int i=dest.size()-1; i>=0; i--) {
4147 ServiceInfo destAi = dest.get(i).serviceInfo;
4148 if (destAi.name == filterSi.name
4149 && destAi.packageName == filterSi.packageName) {
4150 return false;
4151 }
4152 }
4153 return true;
4154 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 @Override
4157 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4158 int match) {
4159 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4160 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4161 return null;
4162 }
4163 final PackageParser.Service service = info.service;
4164 if (mSafeMode && (service.info.applicationInfo.flags
4165 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4166 return null;
4167 }
4168 final ResolveInfo res = new ResolveInfo();
4169 res.serviceInfo = PackageParser.generateServiceInfo(service,
4170 mFlags);
4171 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4172 res.filter = filter;
4173 }
4174 res.priority = info.getPriority();
4175 res.preferredOrder = service.owner.mPreferredOrder;
4176 //System.out.println("Result: " + res.activityInfo.className +
4177 // " = " + res.priority);
4178 res.match = match;
4179 res.isDefault = info.hasDefault;
4180 res.labelRes = info.labelRes;
4181 res.nonLocalizedLabel = info.nonLocalizedLabel;
4182 res.icon = info.icon;
4183 return res;
4184 }
4185
4186 @Override
4187 protected void sortResults(List<ResolveInfo> results) {
4188 Collections.sort(results, mResolvePrioritySorter);
4189 }
4190
4191 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004192 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004194 out.print(prefix); out.print(
4195 Integer.toHexString(System.identityHashCode(filter.service)));
4196 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004197 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 }
4199
4200// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4201// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4202// final List<ResolveInfo> retList = Lists.newArrayList();
4203// while (i.hasNext()) {
4204// final ResolveInfo resolveInfo = (ResolveInfo) i;
4205// if (isEnabledLP(resolveInfo.serviceInfo)) {
4206// retList.add(resolveInfo);
4207// }
4208// }
4209// return retList;
4210// }
4211
4212 // Keys are String (activity class name), values are Activity.
4213 private final HashMap<ComponentName, PackageParser.Service> mServices
4214 = new HashMap<ComponentName, PackageParser.Service>();
4215 private int mFlags;
4216 };
4217
4218 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4219 new Comparator<ResolveInfo>() {
4220 public int compare(ResolveInfo r1, ResolveInfo r2) {
4221 int v1 = r1.priority;
4222 int v2 = r2.priority;
4223 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4224 if (v1 != v2) {
4225 return (v1 > v2) ? -1 : 1;
4226 }
4227 v1 = r1.preferredOrder;
4228 v2 = r2.preferredOrder;
4229 if (v1 != v2) {
4230 return (v1 > v2) ? -1 : 1;
4231 }
4232 if (r1.isDefault != r2.isDefault) {
4233 return r1.isDefault ? -1 : 1;
4234 }
4235 v1 = r1.match;
4236 v2 = r2.match;
4237 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4238 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4239 }
4240 };
4241
4242 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4243 new Comparator<ProviderInfo>() {
4244 public int compare(ProviderInfo p1, ProviderInfo p2) {
4245 final int v1 = p1.initOrder;
4246 final int v2 = p2.initOrder;
4247 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4248 }
4249 };
4250
4251 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4252 IActivityManager am = ActivityManagerNative.getDefault();
4253 if (am != null) {
4254 try {
4255 final Intent intent = new Intent(action,
4256 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4257 if (extras != null) {
4258 intent.putExtras(extras);
4259 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004260 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 am.broadcastIntent(
4262 null, intent,
4263 null, null, 0, null, null, null, false, false);
4264 } catch (RemoteException ex) {
4265 }
4266 }
4267 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004268
4269 public String nextPackageToClean(String lastPackage) {
4270 synchronized (mPackages) {
4271 if (!mMediaMounted) {
4272 // If the external storage is no longer mounted at this point,
4273 // the caller may not have been able to delete all of this
4274 // packages files and can not delete any more. Bail.
4275 return null;
4276 }
4277 if (lastPackage != null) {
4278 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4279 }
4280 return mSettings.mPackagesToBeCleaned.size() > 0
4281 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4282 }
4283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004285 void schedulePackageCleaning(String packageName) {
4286 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4287 }
4288
4289 void startCleaningPackages() {
4290 synchronized (mPackages) {
4291 if (!mMediaMounted) {
4292 return;
4293 }
4294 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4295 return;
4296 }
4297 }
4298 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4299 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4300 IActivityManager am = ActivityManagerNative.getDefault();
4301 if (am != null) {
4302 try {
4303 am.startService(null, intent, null);
4304 } catch (RemoteException e) {
4305 }
4306 }
4307 }
4308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 private final class AppDirObserver extends FileObserver {
4310 public AppDirObserver(String path, int mask, boolean isrom) {
4311 super(path, mask);
4312 mRootDir = path;
4313 mIsRom = isrom;
4314 }
4315
4316 public void onEvent(int event, String path) {
4317 String removedPackage = null;
4318 int removedUid = -1;
4319 String addedPackage = null;
4320 int addedUid = -1;
4321
4322 synchronized (mInstallLock) {
4323 String fullPathStr = null;
4324 File fullPath = null;
4325 if (path != null) {
4326 fullPath = new File(mRootDir, path);
4327 fullPathStr = fullPath.getPath();
4328 }
4329
4330 if (Config.LOGV) Log.v(
4331 TAG, "File " + fullPathStr + " changed: "
4332 + Integer.toHexString(event));
4333
4334 if (!isPackageFilename(path)) {
4335 if (Config.LOGV) Log.v(
4336 TAG, "Ignoring change of non-package file: " + fullPathStr);
4337 return;
4338 }
4339
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004340 // Ignore packages that are being installed or
4341 // have just been installed.
4342 if (ignoreCodePath(fullPathStr)) {
4343 return;
4344 }
4345 PackageParser.Package p = null;
4346 synchronized (mPackages) {
4347 p = mAppDirs.get(fullPathStr);
4348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004350 if (p != null) {
4351 removePackageLI(p, true);
4352 removedPackage = p.applicationInfo.packageName;
4353 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004354 }
4355 }
4356
4357 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004359 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4361 PackageParser.PARSE_CHATTY |
4362 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004363 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 if (p != null) {
4365 synchronized (mPackages) {
4366 grantPermissionsLP(p, false);
4367 }
4368 addedPackage = p.applicationInfo.packageName;
4369 addedUid = p.applicationInfo.uid;
4370 }
4371 }
4372 }
4373
4374 synchronized (mPackages) {
4375 mSettings.writeLP();
4376 }
4377 }
4378
4379 if (removedPackage != null) {
4380 Bundle extras = new Bundle(1);
4381 extras.putInt(Intent.EXTRA_UID, removedUid);
4382 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4383 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4384 }
4385 if (addedPackage != null) {
4386 Bundle extras = new Bundle(1);
4387 extras.putInt(Intent.EXTRA_UID, addedUid);
4388 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4389 }
4390 }
4391
4392 private final String mRootDir;
4393 private final boolean mIsRom;
4394 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 /* Called when a downloaded package installation has been confirmed by the user */
4397 public void installPackage(
4398 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004399 installPackage(packageURI, observer, flags, null);
4400 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004401
Jacek Surazski65e13172009-04-28 15:26:38 +02004402 /* Called when a downloaded package installation has been confirmed by the user */
4403 public void installPackage(
4404 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4405 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 mContext.enforceCallingOrSelfPermission(
4407 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004408
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004409 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004410 msg.obj = new InstallParams(packageURI, observer, flags,
4411 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004412 mHandler.sendMessage(msg);
4413 }
4414
Christopher Tate1bb69062010-02-19 17:02:12 -08004415 public void finishPackageInstall(int token) {
4416 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4417 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4418 mHandler.sendMessage(msg);
4419 }
4420
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004421 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 // Queue up an async operation since the package installation may take a little while.
4423 mHandler.post(new Runnable() {
4424 public void run() {
4425 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004426 // Result object to be returned
4427 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004428 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004429 res.uid = -1;
4430 res.pkg = null;
4431 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004432 args.doPreInstall(res.returnCode);
4433 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004434 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004435 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004436 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004437 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004439
4440 // A restore should be performed at this point if (a) the install
4441 // succeeded, (b) the operation is not an update, and (c) the new
4442 // package has a backupAgent defined.
4443 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004444 boolean doRestore = (!update
4445 && res.pkg != null
4446 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004447
4448 // Set up the post-install work request bookkeeping. This will be used
4449 // and cleaned up by the post-install event handling regardless of whether
4450 // there's a restore pass performed. Token values are >= 1.
4451 int token;
4452 if (mNextInstallToken < 0) mNextInstallToken = 1;
4453 token = mNextInstallToken++;
4454
4455 PostInstallData data = new PostInstallData(args, res);
4456 mRunningInstalls.put(token, data);
4457 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4458
4459 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4460 // Pass responsibility to the Backup Manager. It will perform a
4461 // restore if appropriate, then pass responsibility back to the
4462 // Package Manager to run the post-install observer callbacks
4463 // and broadcasts.
4464 IBackupManager bm = IBackupManager.Stub.asInterface(
4465 ServiceManager.getService(Context.BACKUP_SERVICE));
4466 if (bm != null) {
4467 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4468 + " to BM for possible restore");
4469 try {
4470 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4471 } catch (RemoteException e) {
4472 // can't happen; the backup manager is local
4473 } catch (Exception e) {
4474 Log.e(TAG, "Exception trying to enqueue restore", e);
4475 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004476 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004477 } else {
4478 Log.e(TAG, "Backup Manager not found!");
4479 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004482
4483 if (!doRestore) {
4484 // No restore possible, or the Backup Manager was mysteriously not
4485 // available -- just fire the post-install work request directly.
4486 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4487 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4488 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 }
4491 });
4492 }
4493
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004494 abstract class HandlerParams {
4495 final static int MAX_RETRIES = 4;
4496 int retry = 0;
4497 final void startCopy() {
4498 try {
4499 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4500 retry++;
4501 if (retry > MAX_RETRIES) {
4502 Log.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
4503 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4504 handleServiceError();
4505 return;
4506 } else {
4507 handleStartCopy();
4508 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4509 mHandler.sendEmptyMessage(MCS_UNBIND);
4510 }
4511 } catch (RemoteException e) {
4512 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4513 mHandler.sendEmptyMessage(MCS_RECONNECT);
4514 }
4515 handleReturnCode();
4516 }
4517
4518 final void serviceError() {
4519 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4520 handleServiceError();
4521 handleReturnCode();
4522 }
4523 abstract void handleStartCopy() throws RemoteException;
4524 abstract void handleServiceError();
4525 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004526 }
4527
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004528 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004529 final IPackageInstallObserver observer;
4530 int flags;
4531 final Uri packageURI;
4532 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004533 private InstallArgs mArgs;
4534 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004535 InstallParams(Uri packageURI,
4536 IPackageInstallObserver observer, int flags,
4537 String installerPackageName) {
4538 this.packageURI = packageURI;
4539 this.flags = flags;
4540 this.observer = observer;
4541 this.installerPackageName = installerPackageName;
4542 }
4543
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004544 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004545 int ret = PackageManager.INSTALL_SUCCEEDED;
4546 // Dont need to invoke getInstallLocation for forward locked apps.
4547 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4548 flags &= ~PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004549 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004550 // Remote call to find out default install location
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004551 int loc = mContainerService.getRecommendedInstallLocation(packageURI);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004552 // Use install location to create InstallArgs and temporary
4553 // install location
4554 if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
4555 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4556 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4557 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
4558 } else {
4559 if ((flags & PackageManager.INSTALL_EXTERNAL) == 0){
4560 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4561 // Set the flag to install on external media.
4562 flags |= PackageManager.INSTALL_EXTERNAL;
4563 } else {
4564 // Make sure the flag for installing on external
4565 // media is unset
4566 flags &= ~PackageManager.INSTALL_EXTERNAL;
4567 }
4568 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004569 }
4570 }
4571 // Create the file args now.
4572 mArgs = createInstallArgs(this);
4573 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4574 // Create copy only if we are not in an erroneous state.
4575 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004576 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004577 }
4578 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004579 }
4580
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004581 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004582 void handleReturnCode() {
4583 processPendingInstall(mArgs, mRet);
4584 }
4585
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004586 @Override
4587 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004588 mArgs = createInstallArgs(this);
4589 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004590 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004591 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004592
4593 /*
4594 * Utility class used in movePackage api.
4595 * srcArgs and targetArgs are not set for invalid flags and make
4596 * sure to do null checks when invoking methods on them.
4597 * We probably want to return ErrorPrams for both failed installs
4598 * and moves.
4599 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004600 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004601 final IPackageMoveObserver observer;
4602 final int flags;
4603 final String packageName;
4604 final InstallArgs srcArgs;
4605 final InstallArgs targetArgs;
4606 int mRet;
4607 MoveParams(InstallArgs srcArgs,
4608 IPackageMoveObserver observer,
4609 int flags, String packageName) {
4610 this.srcArgs = srcArgs;
4611 this.observer = observer;
4612 this.flags = flags;
4613 this.packageName = packageName;
4614 if (srcArgs != null) {
4615 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
4616 targetArgs = createInstallArgs(packageUri, flags, packageName);
4617 } else {
4618 targetArgs = null;
4619 }
4620 }
4621
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004622 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004623 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004624 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004625 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004626 if (DEBUG_SD_INSTALL) {
4627 StringBuilder builder = new StringBuilder();
4628 if (srcArgs != null) {
4629 builder.append("src: ");
4630 builder.append(srcArgs.getCodePath());
4631 }
4632 if (targetArgs != null) {
4633 builder.append(" target : ");
4634 builder.append(targetArgs.getCodePath());
4635 }
4636 Log.i(TAG, "Posting move MCS_UNBIND for " + builder.toString());
4637 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004638 }
4639
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004640 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004641 void handleReturnCode() {
4642 targetArgs.doPostInstall(mRet);
4643 // TODO invoke pending move
4644 processPendingMove(this, mRet);
4645 }
4646
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004647 @Override
4648 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004649 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004650 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004651 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004652
4653 private InstallArgs createInstallArgs(InstallParams params) {
4654 if (installOnSd(params.flags)) {
4655 return new SdInstallArgs(params);
4656 } else {
4657 return new FileInstallArgs(params);
4658 }
4659 }
4660
4661 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4662 if (installOnSd(flags)) {
4663 return new SdInstallArgs(fullCodePath, fullResourcePath);
4664 } else {
4665 return new FileInstallArgs(fullCodePath, fullResourcePath);
4666 }
4667 }
4668
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004669 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName) {
4670 if (installOnSd(flags)) {
4671 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4672 return new SdInstallArgs(packageURI, cid);
4673 } else {
4674 return new FileInstallArgs(packageURI, pkgName);
4675 }
4676 }
4677
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004678 static abstract class InstallArgs {
4679 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004680 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004681 final int flags;
4682 final Uri packageURI;
4683 final String installerPackageName;
4684
4685 InstallArgs(Uri packageURI,
4686 IPackageInstallObserver observer, int flags,
4687 String installerPackageName) {
4688 this.packageURI = packageURI;
4689 this.flags = flags;
4690 this.observer = observer;
4691 this.installerPackageName = installerPackageName;
4692 }
4693
4694 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004695 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004696 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004697 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004698 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004699 abstract String getCodePath();
4700 abstract String getResourcePath();
4701 // Need installer lock especially for dex file removal.
4702 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004703 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004704 }
4705
4706 class FileInstallArgs extends InstallArgs {
4707 File installDir;
4708 String codeFileName;
4709 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004710 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004711
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004712 FileInstallArgs(InstallParams params) {
4713 super(params.packageURI, params.observer,
4714 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004715 }
4716
4717 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4718 super(null, null, 0, null);
4719 File codeFile = new File(fullCodePath);
4720 installDir = codeFile.getParentFile();
4721 codeFileName = fullCodePath;
4722 resourceFileName = fullResourcePath;
4723 }
4724
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004725 FileInstallArgs(Uri packageURI, String pkgName) {
4726 super(packageURI, null, 0, null);
4727 boolean fwdLocked = isFwdLocked(flags);
4728 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4729 String apkName = getNextCodePath(null, pkgName, ".apk");
4730 codeFileName = new File(installDir, apkName + ".apk").getPath();
4731 resourceFileName = getResourcePathFromCodePath();
4732 }
4733
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004734 String getCodePath() {
4735 return codeFileName;
4736 }
4737
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004738 void createCopyFile() {
4739 boolean fwdLocked = isFwdLocked(flags);
4740 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4741 codeFileName = createTempPackageFile(installDir).getPath();
4742 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004743 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004744 }
4745
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004746 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004747 if (temp) {
4748 // Generate temp file name
4749 createCopyFile();
4750 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004751 // Get a ParcelFileDescriptor to write to the output file
4752 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004753 if (!created) {
4754 try {
4755 codeFile.createNewFile();
4756 // Set permissions
4757 if (!setPermissions()) {
4758 // Failed setting permissions.
4759 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4760 }
4761 } catch (IOException e) {
4762 Log.w(TAG, "Failed to create file " + codeFile);
4763 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4764 }
4765 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004766 ParcelFileDescriptor out = null;
4767 try {
4768 out = ParcelFileDescriptor.open(codeFile,
4769 ParcelFileDescriptor.MODE_READ_WRITE);
4770 } catch (FileNotFoundException e) {
4771 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4772 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4773 }
4774 // Copy the resource now
4775 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4776 try {
4777 if (imcs.copyResource(packageURI, out)) {
4778 ret = PackageManager.INSTALL_SUCCEEDED;
4779 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004780 } finally {
4781 try { if (out != null) out.close(); } catch (IOException e) {}
4782 }
4783 return ret;
4784 }
4785
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004786 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004787 if (status != PackageManager.INSTALL_SUCCEEDED) {
4788 cleanUp();
4789 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004790 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004791 }
4792
4793 boolean doRename(int status, final String pkgName, String oldCodePath) {
4794 if (status != PackageManager.INSTALL_SUCCEEDED) {
4795 cleanUp();
4796 return false;
4797 } else {
4798 // Rename based on packageName
4799 File codeFile = new File(getCodePath());
4800 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4801 File desFile = new File(installDir, apkName + ".apk");
4802 if (!codeFile.renameTo(desFile)) {
4803 return false;
4804 }
4805 // Reset paths since the file has been renamed.
4806 codeFileName = desFile.getPath();
4807 resourceFileName = getResourcePathFromCodePath();
4808 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004809 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004810 // Failed setting permissions.
4811 return false;
4812 }
4813 return true;
4814 }
4815 }
4816
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004817 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004818 if (status != PackageManager.INSTALL_SUCCEEDED) {
4819 cleanUp();
4820 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004821 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004822 }
4823
4824 String getResourcePath() {
4825 return resourceFileName;
4826 }
4827
4828 String getResourcePathFromCodePath() {
4829 String codePath = getCodePath();
4830 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4831 String apkNameOnly = getApkName(codePath);
4832 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4833 } else {
4834 return codePath;
4835 }
4836 }
4837
4838 private boolean cleanUp() {
4839 boolean ret = true;
4840 String sourceDir = getCodePath();
4841 String publicSourceDir = getResourcePath();
4842 if (sourceDir != null) {
4843 File sourceFile = new File(sourceDir);
4844 if (!sourceFile.exists()) {
4845 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4846 ret = false;
4847 }
4848 // Delete application's code and resources
4849 sourceFile.delete();
4850 }
4851 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4852 final File publicSourceFile = new File(publicSourceDir);
4853 if (!publicSourceFile.exists()) {
4854 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4855 }
4856 if (publicSourceFile.exists()) {
4857 publicSourceFile.delete();
4858 }
4859 }
4860 return ret;
4861 }
4862
4863 void cleanUpResourcesLI() {
4864 String sourceDir = getCodePath();
4865 if (cleanUp() && mInstaller != null) {
4866 int retCode = mInstaller.rmdex(sourceDir);
4867 if (retCode < 0) {
4868 Log.w(TAG, "Couldn't remove dex file for package: "
4869 + " at location "
4870 + sourceDir + ", retcode=" + retCode);
4871 // we don't consider this to be a failure of the core package deletion
4872 }
4873 }
4874 }
4875
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004877 // TODO Do this in a more elegant way later on. for now just a hack
4878 if (!isFwdLocked(flags)) {
4879 final int filePermissions =
4880 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4881 |FileUtils.S_IROTH;
4882 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4883 if (retCode != 0) {
4884 Log.e(TAG, "Couldn't set new package file permissions for " +
4885 getCodePath()
4886 + ". The return code was: " + retCode);
4887 // TODO Define new internal error
4888 return false;
4889 }
4890 return true;
4891 }
4892 return true;
4893 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004894
4895 boolean doPostDeleteLI(boolean delete) {
4896 cleanUpResourcesLI();
4897 return true;
4898 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004899 }
4900
4901 class SdInstallArgs extends InstallArgs {
4902 String cid;
4903 String cachePath;
4904 static final String RES_FILE_NAME = "pkg.apk";
4905
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004906 SdInstallArgs(InstallParams params) {
4907 super(params.packageURI, params.observer,
4908 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004909 }
4910
4911 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004912 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004913 // Extract cid from fullCodePath
4914 int eidx = fullCodePath.lastIndexOf("/");
4915 String subStr1 = fullCodePath.substring(0, eidx);
4916 int sidx = subStr1.lastIndexOf("/");
4917 cid = subStr1.substring(sidx+1, eidx);
4918 cachePath = subStr1;
4919 }
4920
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004921 SdInstallArgs(String cid) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004922 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
4923 this.cid = cid;
4924 }
4925
4926 SdInstallArgs(Uri packageURI, String cid) {
4927 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004928 this.cid = cid;
4929 }
4930
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004931 void createCopyFile() {
4932 cid = getTempContainerId();
4933 }
4934
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004935 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004936 if (temp) {
4937 createCopyFile();
4938 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004939 cachePath = imcs.copyResourceToContainer(
4940 packageURI, cid,
4941 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004942 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4943 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004944 }
4945
4946 @Override
4947 String getCodePath() {
4948 return cachePath + "/" + RES_FILE_NAME;
4949 }
4950
4951 @Override
4952 String getResourcePath() {
4953 return cachePath + "/" + RES_FILE_NAME;
4954 }
4955
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004956 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 if (status != PackageManager.INSTALL_SUCCEEDED) {
4958 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004959 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004960 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004961 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004962 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08004963 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004964 if (cachePath == null) {
4965 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4966 }
4967 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004969 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 }
4971
4972 boolean doRename(int status, final String pkgName,
4973 String oldCodePath) {
4974 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004975 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004976 if (PackageHelper.isContainerMounted(cid)) {
4977 // Unmount the container
4978 if (!PackageHelper.unMountSdDir(cid)) {
4979 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004980 return false;
4981 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004983 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
4984 Log.e(TAG, "Failed to rename " + cid + " to " + newCacheId);
4985 return false;
4986 }
4987 if (!PackageHelper.isContainerMounted(newCacheId)) {
4988 Log.w(TAG, "Mounting container " + newCacheId);
4989 newCachePath = PackageHelper.mountSdDir(newCacheId,
4990 getEncryptKey(), Process.SYSTEM_UID);
4991 } else {
4992 newCachePath = PackageHelper.getSdDir(newCacheId);
4993 }
4994 if (newCachePath == null) {
4995 Log.w(TAG, "Failed to get cache path for " + newCacheId);
4996 return false;
4997 }
4998 Log.i(TAG, "Succesfully renamed " + cid +
4999 " at path: " + cachePath + " to " + newCacheId +
5000 " at new path: " + newCachePath);
5001 cid = newCacheId;
5002 cachePath = newCachePath;
5003 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005004 }
5005
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005006 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 if (status != PackageManager.INSTALL_SUCCEEDED) {
5008 cleanUp();
5009 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005010 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005011 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005012 PackageHelper.mountSdDir(cid,
5013 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005014 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005015 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005016 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005017 }
5018
5019 private void cleanUp() {
5020 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005021 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005022 }
5023
5024 void cleanUpResourcesLI() {
5025 String sourceFile = getCodePath();
5026 // Remove dex file
5027 if (mInstaller != null) {
5028 int retCode = mInstaller.rmdex(sourceFile.toString());
5029 if (retCode < 0) {
5030 Log.w(TAG, "Couldn't remove dex file for package: "
5031 + " at location "
5032 + sourceFile.toString() + ", retcode=" + retCode);
5033 // we don't consider this to be a failure of the core package deletion
5034 }
5035 }
5036 cleanUp();
5037 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005038
5039 boolean matchContainer(String app) {
5040 if (cid.startsWith(app)) {
5041 return true;
5042 }
5043 return false;
5044 }
5045
5046 String getPackageName() {
5047 int idx = cid.lastIndexOf("-");
5048 if (idx == -1) {
5049 return cid;
5050 }
5051 return cid.substring(0, idx);
5052 }
5053
5054 boolean doPostDeleteLI(boolean delete) {
5055 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005056 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005057 if (mounted) {
5058 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005059 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005060 }
5061 if (ret && delete) {
5062 cleanUpResourcesLI();
5063 }
5064 return ret;
5065 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005066 };
5067
5068 // Utility method used to create code paths based on package name and available index.
5069 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5070 String idxStr = "";
5071 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005072 // Fall back to default value of idx=1 if prefix is not
5073 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005074 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005075 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005076 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005077 if (subStr.endsWith(suffix)) {
5078 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005080 // If oldCodePath already contains prefix find out the
5081 // ending index to either increment or decrement.
5082 int sidx = subStr.lastIndexOf(prefix);
5083 if (sidx != -1) {
5084 subStr = subStr.substring(sidx + prefix.length());
5085 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005086 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5087 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005088 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005089 try {
5090 idx = Integer.parseInt(subStr);
5091 if (idx <= 1) {
5092 idx++;
5093 } else {
5094 idx--;
5095 }
5096 } catch(NumberFormatException e) {
5097 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 }
5099 }
5100 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005101 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 return prefix + idxStr;
5103 }
5104
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005105 // Utility method used to ignore ADD/REMOVE events
5106 // by directory observer.
5107 private static boolean ignoreCodePath(String fullPathStr) {
5108 String apkName = getApkName(fullPathStr);
5109 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5110 if (idx != -1 && ((idx+1) < apkName.length())) {
5111 // Make sure the package ends with a numeral
5112 String version = apkName.substring(idx+1);
5113 try {
5114 Integer.parseInt(version);
5115 return true;
5116 } catch (NumberFormatException e) {}
5117 }
5118 return false;
5119 }
5120
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 // Utility method that returns the relative package path with respect
5122 // to the installation directory. Like say for /data/data/com.test-1.apk
5123 // string com.test-1 is returned.
5124 static String getApkName(String codePath) {
5125 if (codePath == null) {
5126 return null;
5127 }
5128 int sidx = codePath.lastIndexOf("/");
5129 int eidx = codePath.lastIndexOf(".");
5130 if (eidx == -1) {
5131 eidx = codePath.length();
5132 } else if (eidx == 0) {
5133 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
5134 return null;
5135 }
5136 return codePath.substring(sidx+1, eidx);
5137 }
5138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 class PackageInstalledInfo {
5140 String name;
5141 int uid;
5142 PackageParser.Package pkg;
5143 int returnCode;
5144 PackageRemovedInfo removedInfo;
5145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005147 /*
5148 * Install a non-existing package.
5149 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005150 private void installNewPackageLI(PackageParser.Package pkg,
5151 int parseFlags,
5152 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005153 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08005155 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005156 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005157
5158 if (useEncryptedFilesystemForPackage(pkg)) {
5159 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
5160 } else {
5161 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
5162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 res.name = pkgName;
5164 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005165 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005166 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005167 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 + " without first uninstalling.");
5169 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5170 return;
5171 }
5172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005174 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005176 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005177 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5178 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5179 }
5180 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005181 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005182 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 res);
5184 // delete the partially installed application. the data directory will have to be
5185 // restored if it was already existing
5186 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5187 // remove package from internal structures. Note that we want deletePackageX to
5188 // delete the package data and cache directories that it created in
5189 // scanPackageLocked, unless those directories existed before we even tried to
5190 // install.
5191 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005192 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5194 res.removedInfo);
5195 }
5196 }
5197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005198
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005199 private void replacePackageLI(PackageParser.Package pkg,
5200 int parseFlags,
5201 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005202 String installerPackageName, PackageInstalledInfo res) {
5203
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005204 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005205 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 // First find the old package info and check signatures
5207 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005208 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005209 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005210 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005211 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5212 return;
5213 }
5214 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005215 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005216 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005217 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005219 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 }
5221 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005223 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005224 PackageParser.Package pkg,
5225 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005226 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 PackageParser.Package newPackage = null;
5228 String pkgName = deletedPackage.packageName;
5229 boolean deletedPkg = true;
5230 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005231
Jacek Surazski65e13172009-04-28 15:26:38 +02005232 String oldInstallerPackageName = null;
5233 synchronized (mPackages) {
5234 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5235 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005236
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005237 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005240 res.removedInfo)) {
5241 // If the existing package was'nt successfully deleted
5242 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5243 deletedPkg = false;
5244 } else {
5245 // Successfully deleted the old package. Now proceed with re-installation
5246 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005247 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005249 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5251 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005252 }
5253 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005254 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005255 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 res);
5257 updatedSettings = true;
5258 }
5259 }
5260
5261 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5262 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005263 // were keeping around in case we needed them (see below) can now be deleted.
5264 // This info will be set on the res.removedInfo to clean up later on as post
5265 // install action.
5266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 //update signature on the new package setting
5268 //this should always succeed, since we checked the
5269 //signature earlier.
5270 synchronized(mPackages) {
5271 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
5272 parseFlags, true);
5273 }
5274 } else {
5275 // remove package from internal structures. Note that we want deletePackageX to
5276 // delete the package data and cache directories that it created in
5277 // scanPackageLocked, unless those directories existed before we even tried to
5278 // install.
5279 if(updatedSettings) {
5280 deletePackageLI(
5281 pkgName, true,
5282 PackageManager.DONT_DELETE_DATA,
5283 res.removedInfo);
5284 }
5285 // Since we failed to install the new package we need to restore the old
5286 // package that we deleted.
5287 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005288 File restoreFile = new File(deletedPackage.mPath);
5289 if (restoreFile == null) {
5290 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
5291 return;
5292 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005293 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
5294 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005295 // Parse old package
5296 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
5297 scanPackageLI(restoreFile, parseFlags, scanMode);
5298 synchronized (mPackages) {
5299 grantPermissionsLP(deletedPackage, false);
5300 mSettings.writeLP();
5301 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005302 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5303 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
5304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 }
5306 }
5307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005309 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005310 PackageParser.Package pkg,
5311 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005312 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 PackageParser.Package newPackage = null;
5314 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005315 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 PackageParser.PARSE_IS_SYSTEM;
5317 String packageName = deletedPackage.packageName;
5318 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5319 if (packageName == null) {
5320 Log.w(TAG, "Attempt to delete null packageName.");
5321 return;
5322 }
5323 PackageParser.Package oldPkg;
5324 PackageSetting oldPkgSetting;
5325 synchronized (mPackages) {
5326 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005327 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005328 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5329 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005330 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 return;
5332 }
5333 }
5334 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5335 res.removedInfo.removedPackage = packageName;
5336 // Remove existing system package
5337 removePackageLI(oldPkg, true);
5338 synchronized (mPackages) {
5339 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5340 }
5341
5342 // Successfully disabled the old package. Now proceed with re-installation
5343 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5344 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005345 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005347 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5349 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5350 }
5351 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005352 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 updatedSettings = true;
5354 }
5355
5356 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5357 //update signature on the new package setting
5358 //this should always succeed, since we checked the
5359 //signature earlier.
5360 synchronized(mPackages) {
5361 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5362 parseFlags, true);
5363 }
5364 } else {
5365 // Re installation failed. Restore old information
5366 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005367 if (newPackage != null) {
5368 removePackageLI(newPackage, true);
5369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005371 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005373 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 // Restore the old system information in Settings
5375 synchronized(mPackages) {
5376 if(updatedSettings) {
5377 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005378 mSettings.setInstallerPackageName(packageName,
5379 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005380 }
5381 mSettings.writeLP();
5382 }
5383 }
5384 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005385
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005386 // Utility method used to move dex files during install.
5387 private int moveDexFiles(PackageParser.Package newPackage) {
5388 int retCode;
5389 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5390 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5391 if (retCode != 0) {
5392 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5393 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5394 }
5395 }
5396 return PackageManager.INSTALL_SUCCEEDED;
5397 }
5398
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005399 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005400 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005401 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 synchronized (mPackages) {
5403 //write settings. the installStatus will be incomplete at this stage.
5404 //note that the new package setting would have already been
5405 //added to mPackages. It hasn't been persisted yet.
5406 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5407 mSettings.writeLP();
5408 }
5409
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005410 if ((res.returnCode = moveDexFiles(newPackage))
5411 != PackageManager.INSTALL_SUCCEEDED) {
5412 // Discontinue if moving dex files failed.
5413 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005415 if((res.returnCode = setPermissionsLI(newPackage))
5416 != PackageManager.INSTALL_SUCCEEDED) {
5417 if (mInstaller != null) {
5418 mInstaller.rmdex(newPackage.mScanPath);
5419 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005420 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005422 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 synchronized (mPackages) {
5425 grantPermissionsLP(newPackage, true);
5426 res.name = pkgName;
5427 res.uid = newPackage.applicationInfo.uid;
5428 res.pkg = newPackage;
5429 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005430 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5432 //to update install status
5433 mSettings.writeLP();
5434 }
5435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005436
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005437 private void installPackageLI(InstallArgs args,
5438 boolean newInstall, PackageInstalledInfo res) {
5439 int pFlags = args.flags;
5440 String installerPackageName = args.installerPackageName;
5441 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005442 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005443 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005444 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005445 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5446 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005447 // Result object to be returned
5448 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5449
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005450 // Retrieve PackageSettings and parse package
5451 int parseFlags = PackageParser.PARSE_CHATTY |
5452 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5453 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5454 parseFlags |= mDefParseFlags;
5455 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5456 pp.setSeparateProcesses(mSeparateProcesses);
5457 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5458 null, mMetrics, parseFlags);
5459 if (pkg == null) {
5460 res.returnCode = pp.getParseError();
5461 return;
5462 }
5463 String pkgName = res.name = pkg.packageName;
5464 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5465 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5466 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5467 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005469 }
5470 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5471 res.returnCode = pp.getParseError();
5472 return;
5473 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005474 // Get rid of all references to package scan path via parser.
5475 pp = null;
5476 String oldCodePath = null;
5477 boolean systemApp = false;
5478 synchronized (mPackages) {
5479 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005480 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5481 String oldName = mSettings.mRenamedPackages.get(pkgName);
5482 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5483 && mPackages.containsKey(oldName)) {
5484 // This package is derived from an original package,
5485 // and this device has been updating from that original
5486 // name. We must continue using the original name, so
5487 // rename the new package here.
5488 pkg.setPackageName(pkg.mOriginalPackage);
5489 pkgName = pkg.packageName;
5490 replace = true;
5491 } else if (mPackages.containsKey(pkgName)) {
5492 // This package, under its official name, already exists
5493 // on the device; we should replace it.
5494 replace = true;
5495 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005496 }
5497 PackageSetting ps = mSettings.mPackages.get(pkgName);
5498 if (ps != null) {
5499 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5500 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5501 systemApp = (ps.pkg.applicationInfo.flags &
5502 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005503 }
5504 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005506
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005507 if (systemApp && onSd) {
5508 // Disable updates to system apps on sdcard
5509 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5510 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5511 return;
5512 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005513
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005514 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5515 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5516 return;
5517 }
5518 // Set application objects path explicitly after the rename
5519 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005520 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005521 replacePackageLI(pkg, parseFlags, scanMode,
5522 installerPackageName, res);
5523 } else {
5524 installNewPackageLI(pkg, parseFlags, scanMode,
5525 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 }
5527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005528
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 private int setPermissionsLI(PackageParser.Package newPackage) {
5530 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005531 int retCode = 0;
5532 // TODO Gross hack but fix later. Ideally move this to be a post installation
5533 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005534 if ((newPackage.applicationInfo.flags
5535 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5536 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 try {
5538 extractPublicFiles(newPackage, destResourceFile);
5539 } catch (IOException e) {
5540 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5541 " forward-locked app.");
5542 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5543 } finally {
5544 //TODO clean up the extracted public files
5545 }
5546 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005547 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 newPackage.applicationInfo.uid);
5549 } else {
5550 final int filePermissions =
5551 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005552 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 newPackage.applicationInfo.uid);
5554 }
5555 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005556 // The permissions on the resource file was set when it was copied for
5557 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005561 Log.e(TAG, "Couldn't set new package file permissions for " +
5562 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005564 // TODO Define new internal error
5565 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 }
5567 return PackageManager.INSTALL_SUCCEEDED;
5568 }
5569
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005570 private boolean isForwardLocked(PackageParser.Package pkg) {
5571 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 }
5573
5574 private void extractPublicFiles(PackageParser.Package newPackage,
5575 File publicZipFile) throws IOException {
5576 final ZipOutputStream publicZipOutStream =
5577 new ZipOutputStream(new FileOutputStream(publicZipFile));
5578 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5579
5580 // Copy manifest, resources.arsc and res directory to public zip
5581
5582 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5583 while (privateZipEntries.hasMoreElements()) {
5584 final ZipEntry zipEntry = privateZipEntries.nextElement();
5585 final String zipEntryName = zipEntry.getName();
5586 if ("AndroidManifest.xml".equals(zipEntryName)
5587 || "resources.arsc".equals(zipEntryName)
5588 || zipEntryName.startsWith("res/")) {
5589 try {
5590 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5591 } catch (IOException e) {
5592 try {
5593 publicZipOutStream.close();
5594 throw e;
5595 } finally {
5596 publicZipFile.delete();
5597 }
5598 }
5599 }
5600 }
5601
5602 publicZipOutStream.close();
5603 FileUtils.setPermissions(
5604 publicZipFile.getAbsolutePath(),
5605 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5606 -1, -1);
5607 }
5608
5609 private static void copyZipEntry(ZipEntry zipEntry,
5610 ZipFile inZipFile,
5611 ZipOutputStream outZipStream) throws IOException {
5612 byte[] buffer = new byte[4096];
5613 int num;
5614
5615 ZipEntry newEntry;
5616 if (zipEntry.getMethod() == ZipEntry.STORED) {
5617 // Preserve the STORED method of the input entry.
5618 newEntry = new ZipEntry(zipEntry);
5619 } else {
5620 // Create a new entry so that the compressed len is recomputed.
5621 newEntry = new ZipEntry(zipEntry.getName());
5622 }
5623 outZipStream.putNextEntry(newEntry);
5624
5625 InputStream data = inZipFile.getInputStream(zipEntry);
5626 while ((num = data.read(buffer)) > 0) {
5627 outZipStream.write(buffer, 0, num);
5628 }
5629 outZipStream.flush();
5630 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 private void deleteTempPackageFiles() {
5633 FilenameFilter filter = new FilenameFilter() {
5634 public boolean accept(File dir, String name) {
5635 return name.startsWith("vmdl") && name.endsWith(".tmp");
5636 }
5637 };
5638 String tmpFilesList[] = mAppInstallDir.list(filter);
5639 if(tmpFilesList == null) {
5640 return;
5641 }
5642 for(int i = 0; i < tmpFilesList.length; i++) {
5643 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5644 tmpFile.delete();
5645 }
5646 }
5647
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005648 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 File tmpPackageFile;
5650 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005651 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 } catch (IOException e) {
5653 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5654 return null;
5655 }
5656 try {
5657 FileUtils.setPermissions(
5658 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5659 -1, -1);
5660 } catch (IOException e) {
5661 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5662 return null;
5663 }
5664 return tmpPackageFile;
5665 }
5666
5667 public void deletePackage(final String packageName,
5668 final IPackageDeleteObserver observer,
5669 final int flags) {
5670 mContext.enforceCallingOrSelfPermission(
5671 android.Manifest.permission.DELETE_PACKAGES, null);
5672 // Queue up an async operation since the package deletion may take a little while.
5673 mHandler.post(new Runnable() {
5674 public void run() {
5675 mHandler.removeCallbacks(this);
5676 final boolean succeded = deletePackageX(packageName, true, true, flags);
5677 if (observer != null) {
5678 try {
5679 observer.packageDeleted(succeded);
5680 } catch (RemoteException e) {
5681 Log.i(TAG, "Observer no longer exists.");
5682 } //end catch
5683 } //end if
5684 } //end run
5685 });
5686 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 /**
5689 * This method is an internal method that could be get invoked either
5690 * to delete an installed package or to clean up a failed installation.
5691 * After deleting an installed package, a broadcast is sent to notify any
5692 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005693 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 * installation wouldn't have sent the initial broadcast either
5695 * The key steps in deleting a package are
5696 * deleting the package information in internal structures like mPackages,
5697 * deleting the packages base directories through installd
5698 * updating mSettings to reflect current status
5699 * persisting settings for later use
5700 * sending a broadcast if necessary
5701 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5703 boolean deleteCodeAndResources, int flags) {
5704 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005705 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08005707 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
5708 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
5709 try {
5710 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
5711 Log.w(TAG, "Not removing package " + packageName + ": has active device admin");
5712 return false;
5713 }
5714 } catch (RemoteException e) {
5715 }
5716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 synchronized (mInstallLock) {
5718 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005722 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5723 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5724
5725 // If the removed package was a system update, the old system packaged
5726 // was re-enabled; we need to broadcast this information
5727 if (systemUpdate) {
5728 Bundle extras = new Bundle(1);
5729 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5730 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5731
5732 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5733 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005736 // Delete the resources here after sending the broadcast to let
5737 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005738 if (info.args != null) {
5739 synchronized (mInstallLock) {
5740 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005741 }
5742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 return res;
5744 }
5745
5746 static class PackageRemovedInfo {
5747 String removedPackage;
5748 int uid = -1;
5749 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005750 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005751 // Clean up resources deleted packages.
5752 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 void sendBroadcast(boolean fullRemove, boolean replacing) {
5755 Bundle extras = new Bundle(1);
5756 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5757 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5758 if (replacing) {
5759 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5760 }
5761 if (removedPackage != null) {
5762 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5763 }
5764 if (removedUid >= 0) {
5765 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5766 }
5767 }
5768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 /*
5771 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5772 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005773 * 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 -08005774 * delete a partially installed application.
5775 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005776 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 int flags) {
5778 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005779 if (outInfo != null) {
5780 outInfo.removedPackage = packageName;
5781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 removePackageLI(p, true);
5783 // Retrieve object to delete permissions for shared user later on
5784 PackageSetting deletedPs;
5785 synchronized (mPackages) {
5786 deletedPs = mSettings.mPackages.get(packageName);
5787 }
5788 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005789 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005791 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 if (retCode < 0) {
5793 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5794 + packageName + ", retcode=" + retCode);
5795 // we don't consider this to be a failure of the core package deletion
5796 }
5797 } else {
5798 //for emulator
5799 PackageParser.Package pkg = mPackages.get(packageName);
5800 File dataDir = new File(pkg.applicationInfo.dataDir);
5801 dataDir.delete();
5802 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005803 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005805 if (outInfo != null) {
5806 outInfo.removedUid = mSettings.removePackageLP(packageName);
5807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 }
5809 }
5810 synchronized (mPackages) {
5811 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5812 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005813 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005815 if (deletedPs != null) {
5816 // remove from preferred activities.
5817 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
5818 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
5819 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
5820 removed.add(pa);
5821 }
5822 }
5823 for (PreferredActivity pa : removed) {
5824 mSettings.mPreferredActivities.removeFilter(pa);
5825 }
5826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005828 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 }
5830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 /*
5833 * Tries to delete system package.
5834 */
5835 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005836 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 ApplicationInfo applicationInfo = p.applicationInfo;
5838 //applicable for non-partially installed applications only
5839 if (applicationInfo == null) {
5840 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5841 return false;
5842 }
5843 PackageSetting ps = null;
5844 // Confirm if the system package has been updated
5845 // An updated system app can be deleted. This will also have to restore
5846 // the system pkg from system partition
5847 synchronized (mPackages) {
5848 ps = mSettings.getDisabledSystemPkg(p.packageName);
5849 }
5850 if (ps == null) {
5851 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5852 return false;
5853 } else {
5854 Log.i(TAG, "Deleting system pkg from data partition");
5855 }
5856 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005857 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005858 boolean deleteCodeAndResources = false;
5859 if (ps.versionCode < p.mVersionCode) {
5860 // Delete code and resources for downgrades
5861 deleteCodeAndResources = true;
5862 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5863 flags &= ~PackageManager.DONT_DELETE_DATA;
5864 }
5865 } else {
5866 // Preserve data by setting flag
5867 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5868 flags |= PackageManager.DONT_DELETE_DATA;
5869 }
5870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5872 if (!ret) {
5873 return false;
5874 }
5875 synchronized (mPackages) {
5876 // Reinstate the old system package
5877 mSettings.enableSystemPackageLP(p.packageName);
5878 }
5879 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005880 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005882 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 if (newPkg == null) {
5885 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5886 return false;
5887 }
5888 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005889 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 mSettings.writeLP();
5891 }
5892 return true;
5893 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5896 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5897 ApplicationInfo applicationInfo = p.applicationInfo;
5898 if (applicationInfo == null) {
5899 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5900 return false;
5901 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005902 if (outInfo != null) {
5903 outInfo.uid = applicationInfo.uid;
5904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905
5906 // Delete package data from internal structures and also remove data if flag is set
5907 removePackageDataLI(p, outInfo, flags);
5908
5909 // Delete application code and resources
5910 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005911 // TODO can pick up from PackageSettings as well
5912 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005913 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005914 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5915 PackageManager.INSTALL_FORWARD_LOCK : 0;
5916 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005917 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 }
5919 return true;
5920 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 /*
5923 * This method handles package deletion in general
5924 */
5925 private boolean deletePackageLI(String packageName,
5926 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5927 if (packageName == null) {
5928 Log.w(TAG, "Attempt to delete null packageName.");
5929 return false;
5930 }
5931 PackageParser.Package p;
5932 boolean dataOnly = false;
5933 synchronized (mPackages) {
5934 p = mPackages.get(packageName);
5935 if (p == null) {
5936 //this retrieves partially installed apps
5937 dataOnly = true;
5938 PackageSetting ps = mSettings.mPackages.get(packageName);
5939 if (ps == null) {
5940 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5941 return false;
5942 }
5943 p = ps.pkg;
5944 }
5945 }
5946 if (p == null) {
5947 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5948 return false;
5949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 if (dataOnly) {
5952 // Delete application data first
5953 removePackageDataLI(p, outInfo, flags);
5954 return true;
5955 }
5956 // At this point the package should have ApplicationInfo associated with it
5957 if (p.applicationInfo == null) {
5958 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5959 return false;
5960 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005961 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5963 Log.i(TAG, "Removing system package:"+p.packageName);
5964 // When an updated system application is deleted we delete the existing resources as well and
5965 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005966 ret = deleteSystemPackageLI(p, flags, outInfo);
5967 } else {
5968 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005969 // Kill application pre-emptively especially for apps on sd.
5970 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005971 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005973 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 public void clearApplicationUserData(final String packageName,
5977 final IPackageDataObserver observer) {
5978 mContext.enforceCallingOrSelfPermission(
5979 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5980 // Queue up an async operation since the package deletion may take a little while.
5981 mHandler.post(new Runnable() {
5982 public void run() {
5983 mHandler.removeCallbacks(this);
5984 final boolean succeeded;
5985 synchronized (mInstallLock) {
5986 succeeded = clearApplicationUserDataLI(packageName);
5987 }
5988 if (succeeded) {
5989 // invoke DeviceStorageMonitor's update method to clear any notifications
5990 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5991 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5992 if (dsm != null) {
5993 dsm.updateMemory();
5994 }
5995 }
5996 if(observer != null) {
5997 try {
5998 observer.onRemoveCompleted(packageName, succeeded);
5999 } catch (RemoteException e) {
6000 Log.i(TAG, "Observer no longer exists.");
6001 }
6002 } //end if observer
6003 } //end run
6004 });
6005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 private boolean clearApplicationUserDataLI(String packageName) {
6008 if (packageName == null) {
6009 Log.w(TAG, "Attempt to delete null packageName.");
6010 return false;
6011 }
6012 PackageParser.Package p;
6013 boolean dataOnly = false;
6014 synchronized (mPackages) {
6015 p = mPackages.get(packageName);
6016 if(p == null) {
6017 dataOnly = true;
6018 PackageSetting ps = mSettings.mPackages.get(packageName);
6019 if((ps == null) || (ps.pkg == null)) {
6020 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6021 return false;
6022 }
6023 p = ps.pkg;
6024 }
6025 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006026 boolean useEncryptedFSDir = false;
6027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 if(!dataOnly) {
6029 //need to check this only for fully installed applications
6030 if (p == null) {
6031 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6032 return false;
6033 }
6034 final ApplicationInfo applicationInfo = p.applicationInfo;
6035 if (applicationInfo == null) {
6036 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6037 return false;
6038 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006039 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 }
6041 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006042 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 if (retCode < 0) {
6044 Log.w(TAG, "Couldn't remove cache files for package: "
6045 + packageName);
6046 return false;
6047 }
6048 }
6049 return true;
6050 }
6051
6052 public void deleteApplicationCacheFiles(final String packageName,
6053 final IPackageDataObserver observer) {
6054 mContext.enforceCallingOrSelfPermission(
6055 android.Manifest.permission.DELETE_CACHE_FILES, null);
6056 // Queue up an async operation since the package deletion may take a little while.
6057 mHandler.post(new Runnable() {
6058 public void run() {
6059 mHandler.removeCallbacks(this);
6060 final boolean succeded;
6061 synchronized (mInstallLock) {
6062 succeded = deleteApplicationCacheFilesLI(packageName);
6063 }
6064 if(observer != null) {
6065 try {
6066 observer.onRemoveCompleted(packageName, succeded);
6067 } catch (RemoteException e) {
6068 Log.i(TAG, "Observer no longer exists.");
6069 }
6070 } //end if observer
6071 } //end run
6072 });
6073 }
6074
6075 private boolean deleteApplicationCacheFilesLI(String packageName) {
6076 if (packageName == null) {
6077 Log.w(TAG, "Attempt to delete null packageName.");
6078 return false;
6079 }
6080 PackageParser.Package p;
6081 synchronized (mPackages) {
6082 p = mPackages.get(packageName);
6083 }
6084 if (p == null) {
6085 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6086 return false;
6087 }
6088 final ApplicationInfo applicationInfo = p.applicationInfo;
6089 if (applicationInfo == null) {
6090 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6091 return false;
6092 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006093 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006095 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 if (retCode < 0) {
6097 Log.w(TAG, "Couldn't remove cache files for package: "
6098 + packageName);
6099 return false;
6100 }
6101 }
6102 return true;
6103 }
6104
6105 public void getPackageSizeInfo(final String packageName,
6106 final IPackageStatsObserver observer) {
6107 mContext.enforceCallingOrSelfPermission(
6108 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6109 // Queue up an async operation since the package deletion may take a little while.
6110 mHandler.post(new Runnable() {
6111 public void run() {
6112 mHandler.removeCallbacks(this);
6113 PackageStats lStats = new PackageStats(packageName);
6114 final boolean succeded;
6115 synchronized (mInstallLock) {
6116 succeded = getPackageSizeInfoLI(packageName, lStats);
6117 }
6118 if(observer != null) {
6119 try {
6120 observer.onGetStatsCompleted(lStats, succeded);
6121 } catch (RemoteException e) {
6122 Log.i(TAG, "Observer no longer exists.");
6123 }
6124 } //end if observer
6125 } //end run
6126 });
6127 }
6128
6129 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6130 if (packageName == null) {
6131 Log.w(TAG, "Attempt to get size of null packageName.");
6132 return false;
6133 }
6134 PackageParser.Package p;
6135 boolean dataOnly = false;
6136 synchronized (mPackages) {
6137 p = mPackages.get(packageName);
6138 if(p == null) {
6139 dataOnly = true;
6140 PackageSetting ps = mSettings.mPackages.get(packageName);
6141 if((ps == null) || (ps.pkg == null)) {
6142 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
6143 return false;
6144 }
6145 p = ps.pkg;
6146 }
6147 }
6148 String publicSrcDir = null;
6149 if(!dataOnly) {
6150 final ApplicationInfo applicationInfo = p.applicationInfo;
6151 if (applicationInfo == null) {
6152 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
6153 return false;
6154 }
6155 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6156 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006157 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 if (mInstaller != null) {
6159 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006160 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 if (res < 0) {
6162 return false;
6163 } else {
6164 return true;
6165 }
6166 }
6167 return true;
6168 }
6169
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 public void addPackageToPreferred(String packageName) {
6172 mContext.enforceCallingOrSelfPermission(
6173 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006174 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 }
6176
6177 public void removePackageFromPreferred(String packageName) {
6178 mContext.enforceCallingOrSelfPermission(
6179 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006180 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 }
6182
6183 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006184 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 }
6186
6187 public void addPreferredActivity(IntentFilter filter, int match,
6188 ComponentName[] set, ComponentName activity) {
6189 mContext.enforceCallingOrSelfPermission(
6190 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6191
6192 synchronized (mPackages) {
6193 Log.i(TAG, "Adding preferred activity " + activity + ":");
6194 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6195 mSettings.mPreferredActivities.addFilter(
6196 new PreferredActivity(filter, match, set, activity));
6197 mSettings.writeLP();
6198 }
6199 }
6200
Satish Sampath8dbe6122009-06-02 23:35:54 +01006201 public void replacePreferredActivity(IntentFilter filter, int match,
6202 ComponentName[] set, ComponentName activity) {
6203 mContext.enforceCallingOrSelfPermission(
6204 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6205 if (filter.countActions() != 1) {
6206 throw new IllegalArgumentException(
6207 "replacePreferredActivity expects filter to have only 1 action.");
6208 }
6209 if (filter.countCategories() != 1) {
6210 throw new IllegalArgumentException(
6211 "replacePreferredActivity expects filter to have only 1 category.");
6212 }
6213 if (filter.countDataAuthorities() != 0
6214 || filter.countDataPaths() != 0
6215 || filter.countDataSchemes() != 0
6216 || filter.countDataTypes() != 0) {
6217 throw new IllegalArgumentException(
6218 "replacePreferredActivity expects filter to have no data authorities, " +
6219 "paths, schemes or types.");
6220 }
6221 synchronized (mPackages) {
6222 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6223 String action = filter.getAction(0);
6224 String category = filter.getCategory(0);
6225 while (it.hasNext()) {
6226 PreferredActivity pa = it.next();
6227 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6228 it.remove();
6229 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6230 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6231 }
6232 }
6233 addPreferredActivity(filter, match, set, activity);
6234 }
6235 }
6236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 public void clearPackagePreferredActivities(String packageName) {
6238 mContext.enforceCallingOrSelfPermission(
6239 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6240
6241 synchronized (mPackages) {
6242 if (clearPackagePreferredActivitiesLP(packageName)) {
6243 mSettings.writeLP();
6244 }
6245 }
6246 }
6247
6248 boolean clearPackagePreferredActivitiesLP(String packageName) {
6249 boolean changed = false;
6250 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6251 while (it.hasNext()) {
6252 PreferredActivity pa = it.next();
6253 if (pa.mActivity.getPackageName().equals(packageName)) {
6254 it.remove();
6255 changed = true;
6256 }
6257 }
6258 return changed;
6259 }
6260
6261 public int getPreferredActivities(List<IntentFilter> outFilters,
6262 List<ComponentName> outActivities, String packageName) {
6263
6264 int num = 0;
6265 synchronized (mPackages) {
6266 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6267 while (it.hasNext()) {
6268 PreferredActivity pa = it.next();
6269 if (packageName == null
6270 || pa.mActivity.getPackageName().equals(packageName)) {
6271 if (outFilters != null) {
6272 outFilters.add(new IntentFilter(pa));
6273 }
6274 if (outActivities != null) {
6275 outActivities.add(pa.mActivity);
6276 }
6277 }
6278 }
6279 }
6280
6281 return num;
6282 }
6283
6284 public void setApplicationEnabledSetting(String appPackageName,
6285 int newState, int flags) {
6286 setEnabledSetting(appPackageName, null, newState, flags);
6287 }
6288
6289 public void setComponentEnabledSetting(ComponentName componentName,
6290 int newState, int flags) {
6291 setEnabledSetting(componentName.getPackageName(),
6292 componentName.getClassName(), newState, flags);
6293 }
6294
6295 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006296 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6298 || newState == COMPONENT_ENABLED_STATE_ENABLED
6299 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6300 throw new IllegalArgumentException("Invalid new component state: "
6301 + newState);
6302 }
6303 PackageSetting pkgSetting;
6304 final int uid = Binder.getCallingUid();
6305 final int permission = mContext.checkCallingPermission(
6306 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6307 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006308 boolean sendNow = false;
6309 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006310 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006312 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006314 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006316 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006318 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006321 "Unknown component: " + packageName
6322 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 }
6324 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6325 throw new SecurityException(
6326 "Permission Denial: attempt to change component state from pid="
6327 + Binder.getCallingPid()
6328 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6329 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006330 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 // We're dealing with an application/package level state change
6332 pkgSetting.enabled = newState;
6333 } else {
6334 // We're dealing with a component level state change
6335 switch (newState) {
6336 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006337 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 break;
6339 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006340 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 break;
6342 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006343 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 break;
6345 default:
6346 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006347 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 }
6349 }
6350 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006351 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006352 components = mPendingBroadcasts.get(packageName);
6353 boolean newPackage = components == null;
6354 if (newPackage) {
6355 components = new ArrayList<String>();
6356 }
6357 if (!components.contains(componentName)) {
6358 components.add(componentName);
6359 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006360 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6361 sendNow = true;
6362 // Purge entry from pending broadcast list if another one exists already
6363 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006364 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006365 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006366 if (newPackage) {
6367 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006368 }
6369 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6370 // Schedule a message
6371 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6372 }
6373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 long callingId = Binder.clearCallingIdentity();
6377 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006378 if (sendNow) {
6379 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006380 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 } finally {
6383 Binder.restoreCallingIdentity(callingId);
6384 }
6385 }
6386
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006387 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006388 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6389 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6390 + " components=" + componentNames);
6391 Bundle extras = new Bundle(4);
6392 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6393 String nameList[] = new String[componentNames.size()];
6394 componentNames.toArray(nameList);
6395 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006396 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6397 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006398 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006399 }
6400
Jacek Surazski65e13172009-04-28 15:26:38 +02006401 public String getInstallerPackageName(String packageName) {
6402 synchronized (mPackages) {
6403 PackageSetting pkg = mSettings.mPackages.get(packageName);
6404 if (pkg == null) {
6405 throw new IllegalArgumentException("Unknown package: " + packageName);
6406 }
6407 return pkg.installerPackageName;
6408 }
6409 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 public int getApplicationEnabledSetting(String appPackageName) {
6412 synchronized (mPackages) {
6413 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6414 if (pkg == null) {
6415 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6416 }
6417 return pkg.enabled;
6418 }
6419 }
6420
6421 public int getComponentEnabledSetting(ComponentName componentName) {
6422 synchronized (mPackages) {
6423 final String packageNameStr = componentName.getPackageName();
6424 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6425 if (pkg == null) {
6426 throw new IllegalArgumentException("Unknown component: " + componentName);
6427 }
6428 final String classNameStr = componentName.getClassName();
6429 return pkg.currentEnabledStateLP(classNameStr);
6430 }
6431 }
6432
6433 public void enterSafeMode() {
6434 if (!mSystemReady) {
6435 mSafeMode = true;
6436 }
6437 }
6438
6439 public void systemReady() {
6440 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006441
6442 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006443 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006444 mContext.getContentResolver(),
6445 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006446 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006447 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006448 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 }
6451
6452 public boolean isSafeMode() {
6453 return mSafeMode;
6454 }
6455
6456 public boolean hasSystemUidErrors() {
6457 return mHasSystemUidErrors;
6458 }
6459
6460 static String arrayToString(int[] array) {
6461 StringBuffer buf = new StringBuffer(128);
6462 buf.append('[');
6463 if (array != null) {
6464 for (int i=0; i<array.length; i++) {
6465 if (i > 0) buf.append(", ");
6466 buf.append(array[i]);
6467 }
6468 }
6469 buf.append(']');
6470 return buf.toString();
6471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 @Override
6474 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6475 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6476 != PackageManager.PERMISSION_GRANTED) {
6477 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6478 + Binder.getCallingPid()
6479 + ", uid=" + Binder.getCallingUid()
6480 + " without permission "
6481 + android.Manifest.permission.DUMP);
6482 return;
6483 }
6484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 synchronized (mPackages) {
6486 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006487 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 pw.println(" ");
6489 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006490 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 pw.println(" ");
6492 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006493 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 pw.println(" ");
6495 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006496 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 pw.println("Permissions:");
6499 {
6500 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006501 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6502 pw.print(Integer.toHexString(System.identityHashCode(p)));
6503 pw.println("):");
6504 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6505 pw.print(" uid="); pw.print(p.uid);
6506 pw.print(" gids="); pw.print(arrayToString(p.gids));
6507 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 }
6509 }
6510 pw.println(" ");
6511 pw.println("Packages:");
6512 {
6513 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006514 pw.print(" Package [");
6515 pw.print(ps.realName != null ? ps.realName : ps.name);
6516 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006517 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6518 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006519 if (ps.realName != null) {
6520 pw.print(" compat name="); pw.println(ps.name);
6521 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006522 pw.print(" userId="); pw.print(ps.userId);
6523 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6524 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6525 pw.print(" pkg="); pw.println(ps.pkg);
6526 pw.print(" codePath="); pw.println(ps.codePathString);
6527 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006529 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006530 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006531 pw.print(" supportsScreens=[");
6532 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006533 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006534 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006535 if (!first) pw.print(", ");
6536 first = false;
6537 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006539 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006540 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006541 if (!first) pw.print(", ");
6542 first = false;
6543 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006545 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006546 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006547 if (!first) pw.print(", ");
6548 first = false;
6549 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006551 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006552 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006553 if (!first) pw.print(", ");
6554 first = false;
6555 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006557 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006558 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6559 if (!first) pw.print(", ");
6560 first = false;
6561 pw.print("anyDensity");
6562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006564 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006565 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6566 pw.print(" signatures="); pw.println(ps.signatures);
6567 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6568 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6569 pw.print(" installStatus="); pw.print(ps.installStatus);
6570 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 if (ps.disabledComponents.size() > 0) {
6572 pw.println(" disabledComponents:");
6573 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006574 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 }
6576 }
6577 if (ps.enabledComponents.size() > 0) {
6578 pw.println(" enabledComponents:");
6579 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006580 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006583 if (ps.grantedPermissions.size() > 0) {
6584 pw.println(" grantedPermissions:");
6585 for (String s : ps.grantedPermissions) {
6586 pw.print(" "); pw.println(s);
6587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006589 if (ps.loadedPermissions.size() > 0) {
6590 pw.println(" loadedPermissions:");
6591 for (String s : ps.loadedPermissions) {
6592 pw.print(" "); pw.println(s);
6593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
6595 }
6596 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006597 if (mSettings.mRenamedPackages.size() > 0) {
6598 pw.println(" ");
6599 pw.println("Renamed packages:");
6600 for (HashMap.Entry<String, String> e
6601 : mSettings.mRenamedPackages.entrySet()) {
6602 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6603 pw.println(e.getValue());
6604 }
6605 }
6606 if (mSettings.mDisabledSysPackages.size() > 0) {
6607 pw.println(" ");
6608 pw.println("Hidden system packages:");
6609 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6610 pw.print(" Package [");
6611 pw.print(ps.realName != null ? ps.realName : ps.name);
6612 pw.print("] (");
6613 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6614 pw.println("):");
6615 if (ps.realName != null) {
6616 pw.print(" compat name="); pw.println(ps.name);
6617 }
6618 pw.print(" userId="); pw.println(ps.userId);
6619 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6620 pw.print(" codePath="); pw.println(ps.codePathString);
6621 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6622 }
6623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 pw.println(" ");
6625 pw.println("Shared Users:");
6626 {
6627 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006628 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6629 pw.print(Integer.toHexString(System.identityHashCode(su)));
6630 pw.println("):");
6631 pw.print(" userId="); pw.print(su.userId);
6632 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 pw.println(" grantedPermissions:");
6634 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006635 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006636 }
6637 pw.println(" loadedPermissions:");
6638 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006639 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 }
6641 }
6642 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 pw.println(" ");
6645 pw.println("Settings parse messages:");
6646 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006647
6648 pw.println(" ");
6649 pw.println("Package warning messages:");
6650 File fname = getSettingsProblemFile();
6651 FileInputStream in;
6652 try {
6653 in = new FileInputStream(fname);
6654 int avail = in.available();
6655 byte[] data = new byte[avail];
6656 in.read(data);
6657 pw.println(new String(data));
6658 } catch (FileNotFoundException e) {
6659 } catch (IOException e) {
6660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006662
6663 synchronized (mProviders) {
6664 pw.println(" ");
6665 pw.println("Registered ContentProviders:");
6666 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006667 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006668 pw.println(p.toString());
6669 }
6670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
6672
6673 static final class BasePermission {
6674 final static int TYPE_NORMAL = 0;
6675 final static int TYPE_BUILTIN = 1;
6676 final static int TYPE_DYNAMIC = 2;
6677
6678 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006679 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 final int type;
6681 PackageParser.Permission perm;
6682 PermissionInfo pendingInfo;
6683 int uid;
6684 int[] gids;
6685
6686 BasePermission(String _name, String _sourcePackage, int _type) {
6687 name = _name;
6688 sourcePackage = _sourcePackage;
6689 type = _type;
6690 }
6691 }
6692
6693 static class PackageSignatures {
6694 private Signature[] mSignatures;
6695
6696 PackageSignatures(Signature[] sigs) {
6697 assignSignatures(sigs);
6698 }
6699
6700 PackageSignatures() {
6701 }
6702
6703 void writeXml(XmlSerializer serializer, String tagName,
6704 ArrayList<Signature> pastSignatures) throws IOException {
6705 if (mSignatures == null) {
6706 return;
6707 }
6708 serializer.startTag(null, tagName);
6709 serializer.attribute(null, "count",
6710 Integer.toString(mSignatures.length));
6711 for (int i=0; i<mSignatures.length; i++) {
6712 serializer.startTag(null, "cert");
6713 final Signature sig = mSignatures[i];
6714 final int sigHash = sig.hashCode();
6715 final int numPast = pastSignatures.size();
6716 int j;
6717 for (j=0; j<numPast; j++) {
6718 Signature pastSig = pastSignatures.get(j);
6719 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6720 serializer.attribute(null, "index", Integer.toString(j));
6721 break;
6722 }
6723 }
6724 if (j >= numPast) {
6725 pastSignatures.add(sig);
6726 serializer.attribute(null, "index", Integer.toString(numPast));
6727 serializer.attribute(null, "key", sig.toCharsString());
6728 }
6729 serializer.endTag(null, "cert");
6730 }
6731 serializer.endTag(null, tagName);
6732 }
6733
6734 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6735 throws IOException, XmlPullParserException {
6736 String countStr = parser.getAttributeValue(null, "count");
6737 if (countStr == null) {
6738 reportSettingsProblem(Log.WARN,
6739 "Error in package manager settings: <signatures> has"
6740 + " no count at " + parser.getPositionDescription());
6741 XmlUtils.skipCurrentTag(parser);
6742 }
6743 final int count = Integer.parseInt(countStr);
6744 mSignatures = new Signature[count];
6745 int pos = 0;
6746
6747 int outerDepth = parser.getDepth();
6748 int type;
6749 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6750 && (type != XmlPullParser.END_TAG
6751 || parser.getDepth() > outerDepth)) {
6752 if (type == XmlPullParser.END_TAG
6753 || type == XmlPullParser.TEXT) {
6754 continue;
6755 }
6756
6757 String tagName = parser.getName();
6758 if (tagName.equals("cert")) {
6759 if (pos < count) {
6760 String index = parser.getAttributeValue(null, "index");
6761 if (index != null) {
6762 try {
6763 int idx = Integer.parseInt(index);
6764 String key = parser.getAttributeValue(null, "key");
6765 if (key == null) {
6766 if (idx >= 0 && idx < pastSignatures.size()) {
6767 Signature sig = pastSignatures.get(idx);
6768 if (sig != null) {
6769 mSignatures[pos] = pastSignatures.get(idx);
6770 pos++;
6771 } else {
6772 reportSettingsProblem(Log.WARN,
6773 "Error in package manager settings: <cert> "
6774 + "index " + index + " is not defined at "
6775 + parser.getPositionDescription());
6776 }
6777 } else {
6778 reportSettingsProblem(Log.WARN,
6779 "Error in package manager settings: <cert> "
6780 + "index " + index + " is out of bounds at "
6781 + parser.getPositionDescription());
6782 }
6783 } else {
6784 while (pastSignatures.size() <= idx) {
6785 pastSignatures.add(null);
6786 }
6787 Signature sig = new Signature(key);
6788 pastSignatures.set(idx, sig);
6789 mSignatures[pos] = sig;
6790 pos++;
6791 }
6792 } catch (NumberFormatException e) {
6793 reportSettingsProblem(Log.WARN,
6794 "Error in package manager settings: <cert> "
6795 + "index " + index + " is not a number at "
6796 + parser.getPositionDescription());
6797 }
6798 } else {
6799 reportSettingsProblem(Log.WARN,
6800 "Error in package manager settings: <cert> has"
6801 + " no index at " + parser.getPositionDescription());
6802 }
6803 } else {
6804 reportSettingsProblem(Log.WARN,
6805 "Error in package manager settings: too "
6806 + "many <cert> tags, expected " + count
6807 + " at " + parser.getPositionDescription());
6808 }
6809 } else {
6810 reportSettingsProblem(Log.WARN,
6811 "Unknown element under <cert>: "
6812 + parser.getName());
6813 }
6814 XmlUtils.skipCurrentTag(parser);
6815 }
6816
6817 if (pos < count) {
6818 // Should never happen -- there is an error in the written
6819 // settings -- but if it does we don't want to generate
6820 // a bad array.
6821 Signature[] newSigs = new Signature[pos];
6822 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6823 mSignatures = newSigs;
6824 }
6825 }
6826
6827 /**
6828 * If any of the given 'sigs' is contained in the existing signatures,
6829 * then completely replace the current signatures with the ones in
6830 * 'sigs'. This is used for updating an existing package to a newly
6831 * installed version.
6832 */
6833 boolean updateSignatures(Signature[] sigs, boolean update) {
6834 if (mSignatures == null) {
6835 if (update) {
6836 assignSignatures(sigs);
6837 }
6838 return true;
6839 }
6840 if (sigs == null) {
6841 return false;
6842 }
6843
6844 for (int i=0; i<sigs.length; i++) {
6845 Signature sig = sigs[i];
6846 for (int j=0; j<mSignatures.length; j++) {
6847 if (mSignatures[j].equals(sig)) {
6848 if (update) {
6849 assignSignatures(sigs);
6850 }
6851 return true;
6852 }
6853 }
6854 }
6855 return false;
6856 }
6857
6858 /**
6859 * If any of the given 'sigs' is contained in the existing signatures,
6860 * then add in any new signatures found in 'sigs'. This is used for
6861 * including a new package into an existing shared user id.
6862 */
6863 boolean mergeSignatures(Signature[] sigs, boolean update) {
6864 if (mSignatures == null) {
6865 if (update) {
6866 assignSignatures(sigs);
6867 }
6868 return true;
6869 }
6870 if (sigs == null) {
6871 return false;
6872 }
6873
6874 Signature[] added = null;
6875 int addedCount = 0;
6876 boolean haveMatch = false;
6877 for (int i=0; i<sigs.length; i++) {
6878 Signature sig = sigs[i];
6879 boolean found = false;
6880 for (int j=0; j<mSignatures.length; j++) {
6881 if (mSignatures[j].equals(sig)) {
6882 found = true;
6883 haveMatch = true;
6884 break;
6885 }
6886 }
6887
6888 if (!found) {
6889 if (added == null) {
6890 added = new Signature[sigs.length];
6891 }
6892 added[i] = sig;
6893 addedCount++;
6894 }
6895 }
6896
6897 if (!haveMatch) {
6898 // Nothing matched -- reject the new signatures.
6899 return false;
6900 }
6901 if (added == null) {
6902 // Completely matched -- nothing else to do.
6903 return true;
6904 }
6905
6906 // Add additional signatures in.
6907 if (update) {
6908 Signature[] total = new Signature[addedCount+mSignatures.length];
6909 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6910 int j = mSignatures.length;
6911 for (int i=0; i<added.length; i++) {
6912 if (added[i] != null) {
6913 total[j] = added[i];
6914 j++;
6915 }
6916 }
6917 mSignatures = total;
6918 }
6919 return true;
6920 }
6921
6922 private void assignSignatures(Signature[] sigs) {
6923 if (sigs == null) {
6924 mSignatures = null;
6925 return;
6926 }
6927 mSignatures = new Signature[sigs.length];
6928 for (int i=0; i<sigs.length; i++) {
6929 mSignatures[i] = sigs[i];
6930 }
6931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 @Override
6934 public String toString() {
6935 StringBuffer buf = new StringBuffer(128);
6936 buf.append("PackageSignatures{");
6937 buf.append(Integer.toHexString(System.identityHashCode(this)));
6938 buf.append(" [");
6939 if (mSignatures != null) {
6940 for (int i=0; i<mSignatures.length; i++) {
6941 if (i > 0) buf.append(", ");
6942 buf.append(Integer.toHexString(
6943 System.identityHashCode(mSignatures[i])));
6944 }
6945 }
6946 buf.append("]}");
6947 return buf.toString();
6948 }
6949 }
6950
6951 static class PreferredActivity extends IntentFilter {
6952 final int mMatch;
6953 final String[] mSetPackages;
6954 final String[] mSetClasses;
6955 final String[] mSetComponents;
6956 final ComponentName mActivity;
6957 final String mShortActivity;
6958 String mParseError;
6959
6960 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6961 ComponentName activity) {
6962 super(filter);
6963 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6964 mActivity = activity;
6965 mShortActivity = activity.flattenToShortString();
6966 mParseError = null;
6967 if (set != null) {
6968 final int N = set.length;
6969 String[] myPackages = new String[N];
6970 String[] myClasses = new String[N];
6971 String[] myComponents = new String[N];
6972 for (int i=0; i<N; i++) {
6973 ComponentName cn = set[i];
6974 if (cn == null) {
6975 mSetPackages = null;
6976 mSetClasses = null;
6977 mSetComponents = null;
6978 return;
6979 }
6980 myPackages[i] = cn.getPackageName().intern();
6981 myClasses[i] = cn.getClassName().intern();
6982 myComponents[i] = cn.flattenToShortString().intern();
6983 }
6984 mSetPackages = myPackages;
6985 mSetClasses = myClasses;
6986 mSetComponents = myComponents;
6987 } else {
6988 mSetPackages = null;
6989 mSetClasses = null;
6990 mSetComponents = null;
6991 }
6992 }
6993
6994 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6995 IOException {
6996 mShortActivity = parser.getAttributeValue(null, "name");
6997 mActivity = ComponentName.unflattenFromString(mShortActivity);
6998 if (mActivity == null) {
6999 mParseError = "Bad activity name " + mShortActivity;
7000 }
7001 String matchStr = parser.getAttributeValue(null, "match");
7002 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7003 String setCountStr = parser.getAttributeValue(null, "set");
7004 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7005
7006 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7007 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7008 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7009
7010 int setPos = 0;
7011
7012 int outerDepth = parser.getDepth();
7013 int type;
7014 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7015 && (type != XmlPullParser.END_TAG
7016 || parser.getDepth() > outerDepth)) {
7017 if (type == XmlPullParser.END_TAG
7018 || type == XmlPullParser.TEXT) {
7019 continue;
7020 }
7021
7022 String tagName = parser.getName();
7023 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7024 // + parser.getDepth() + " tag=" + tagName);
7025 if (tagName.equals("set")) {
7026 String name = parser.getAttributeValue(null, "name");
7027 if (name == null) {
7028 if (mParseError == null) {
7029 mParseError = "No name in set tag in preferred activity "
7030 + mShortActivity;
7031 }
7032 } else if (setPos >= setCount) {
7033 if (mParseError == null) {
7034 mParseError = "Too many set tags in preferred activity "
7035 + mShortActivity;
7036 }
7037 } else {
7038 ComponentName cn = ComponentName.unflattenFromString(name);
7039 if (cn == null) {
7040 if (mParseError == null) {
7041 mParseError = "Bad set name " + name + " in preferred activity "
7042 + mShortActivity;
7043 }
7044 } else {
7045 myPackages[setPos] = cn.getPackageName();
7046 myClasses[setPos] = cn.getClassName();
7047 myComponents[setPos] = name;
7048 setPos++;
7049 }
7050 }
7051 XmlUtils.skipCurrentTag(parser);
7052 } else if (tagName.equals("filter")) {
7053 //Log.i(TAG, "Starting to parse filter...");
7054 readFromXml(parser);
7055 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7056 // + parser.getDepth() + " tag=" + parser.getName());
7057 } else {
7058 reportSettingsProblem(Log.WARN,
7059 "Unknown element under <preferred-activities>: "
7060 + parser.getName());
7061 XmlUtils.skipCurrentTag(parser);
7062 }
7063 }
7064
7065 if (setPos != setCount) {
7066 if (mParseError == null) {
7067 mParseError = "Not enough set tags (expected " + setCount
7068 + " but found " + setPos + ") in " + mShortActivity;
7069 }
7070 }
7071
7072 mSetPackages = myPackages;
7073 mSetClasses = myClasses;
7074 mSetComponents = myComponents;
7075 }
7076
7077 public void writeToXml(XmlSerializer serializer) throws IOException {
7078 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7079 serializer.attribute(null, "name", mShortActivity);
7080 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7081 serializer.attribute(null, "set", Integer.toString(NS));
7082 for (int s=0; s<NS; s++) {
7083 serializer.startTag(null, "set");
7084 serializer.attribute(null, "name", mSetComponents[s]);
7085 serializer.endTag(null, "set");
7086 }
7087 serializer.startTag(null, "filter");
7088 super.writeToXml(serializer);
7089 serializer.endTag(null, "filter");
7090 }
7091
7092 boolean sameSet(List<ResolveInfo> query, int priority) {
7093 if (mSetPackages == null) return false;
7094 final int NQ = query.size();
7095 final int NS = mSetPackages.length;
7096 int numMatch = 0;
7097 for (int i=0; i<NQ; i++) {
7098 ResolveInfo ri = query.get(i);
7099 if (ri.priority != priority) continue;
7100 ActivityInfo ai = ri.activityInfo;
7101 boolean good = false;
7102 for (int j=0; j<NS; j++) {
7103 if (mSetPackages[j].equals(ai.packageName)
7104 && mSetClasses[j].equals(ai.name)) {
7105 numMatch++;
7106 good = true;
7107 break;
7108 }
7109 }
7110 if (!good) return false;
7111 }
7112 return numMatch == NS;
7113 }
7114 }
7115
7116 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007117 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 HashSet<String> grantedPermissions = new HashSet<String>();
7120 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007125 setFlags(pkgFlags);
7126 }
7127
7128 void setFlags(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007129 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007130 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
7131 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 }
7133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 /**
7136 * Settings base class for pending and resolved classes.
7137 */
7138 static class PackageSettingBase extends GrantedPermissions {
7139 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007140 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007141 File codePath;
7142 String codePathString;
7143 File resourcePath;
7144 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 private long timeStamp;
7146 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007147 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007148
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007149 boolean uidError;
7150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 PackageSignatures signatures = new PackageSignatures();
7152
7153 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 /* Explicitly disabled components */
7156 HashSet<String> disabledComponents = new HashSet<String>(0);
7157 /* Explicitly enabled components */
7158 HashSet<String> enabledComponents = new HashSet<String>(0);
7159 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7160 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007161
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007162 PackageSettingBase origPackage;
7163
Jacek Surazski65e13172009-04-28 15:26:38 +02007164 /* package name of the app that installed this package */
7165 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007167 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007168 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 super(pkgFlags);
7170 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007171 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007172 init(codePath, resourcePath, pVersionCode);
7173 }
7174
7175 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 this.codePath = codePath;
7177 this.codePathString = codePath.toString();
7178 this.resourcePath = resourcePath;
7179 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007180 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007182
Jacek Surazski65e13172009-04-28 15:26:38 +02007183 public void setInstallerPackageName(String packageName) {
7184 installerPackageName = packageName;
7185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007186
Jacek Surazski65e13172009-04-28 15:26:38 +02007187 String getInstallerPackageName() {
7188 return installerPackageName;
7189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 public void setInstallStatus(int newStatus) {
7192 installStatus = newStatus;
7193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 public int getInstallStatus() {
7196 return installStatus;
7197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 public void setTimeStamp(long newStamp) {
7200 if (newStamp != timeStamp) {
7201 timeStamp = newStamp;
7202 timeStampString = Long.toString(newStamp);
7203 }
7204 }
7205
7206 public void setTimeStamp(long newStamp, String newStampStr) {
7207 timeStamp = newStamp;
7208 timeStampString = newStampStr;
7209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 public long getTimeStamp() {
7212 return timeStamp;
7213 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 public String getTimeStampStr() {
7216 return timeStampString;
7217 }
7218
7219 public void copyFrom(PackageSettingBase base) {
7220 grantedPermissions = base.grantedPermissions;
7221 gids = base.gids;
7222 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 timeStamp = base.timeStamp;
7225 timeStampString = base.timeStampString;
7226 signatures = base.signatures;
7227 permissionsFixed = base.permissionsFixed;
7228 disabledComponents = base.disabledComponents;
7229 enabledComponents = base.enabledComponents;
7230 enabled = base.enabled;
7231 installStatus = base.installStatus;
7232 }
7233
7234 void enableComponentLP(String componentClassName) {
7235 disabledComponents.remove(componentClassName);
7236 enabledComponents.add(componentClassName);
7237 }
7238
7239 void disableComponentLP(String componentClassName) {
7240 enabledComponents.remove(componentClassName);
7241 disabledComponents.add(componentClassName);
7242 }
7243
7244 void restoreComponentLP(String componentClassName) {
7245 enabledComponents.remove(componentClassName);
7246 disabledComponents.remove(componentClassName);
7247 }
7248
7249 int currentEnabledStateLP(String componentName) {
7250 if (enabledComponents.contains(componentName)) {
7251 return COMPONENT_ENABLED_STATE_ENABLED;
7252 } else if (disabledComponents.contains(componentName)) {
7253 return COMPONENT_ENABLED_STATE_DISABLED;
7254 } else {
7255 return COMPONENT_ENABLED_STATE_DEFAULT;
7256 }
7257 }
7258 }
7259
7260 /**
7261 * Settings data for a particular package we know about.
7262 */
7263 static final class PackageSetting extends PackageSettingBase {
7264 int userId;
7265 PackageParser.Package pkg;
7266 SharedUserSetting sharedUser;
7267
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007268 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007269 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007270 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 @Override
7274 public String toString() {
7275 return "PackageSetting{"
7276 + Integer.toHexString(System.identityHashCode(this))
7277 + " " + name + "/" + userId + "}";
7278 }
7279 }
7280
7281 /**
7282 * Settings data for a particular shared user ID we know about.
7283 */
7284 static final class SharedUserSetting extends GrantedPermissions {
7285 final String name;
7286 int userId;
7287 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7288 final PackageSignatures signatures = new PackageSignatures();
7289
7290 SharedUserSetting(String _name, int _pkgFlags) {
7291 super(_pkgFlags);
7292 name = _name;
7293 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 @Override
7296 public String toString() {
7297 return "SharedUserSetting{"
7298 + Integer.toHexString(System.identityHashCode(this))
7299 + " " + name + "/" + userId + "}";
7300 }
7301 }
7302
7303 /**
7304 * Holds information about dynamic settings.
7305 */
7306 private static final class Settings {
7307 private final File mSettingsFilename;
7308 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007309 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 private final HashMap<String, PackageSetting> mPackages =
7311 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007312 // List of replaced system applications
7313 final HashMap<String, PackageSetting> mDisabledSysPackages =
7314 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 // The user's preferred activities associated with particular intent
7317 // filters.
7318 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7319 new IntentResolver<PreferredActivity, PreferredActivity>() {
7320 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007321 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007323 out.print(prefix); out.print(
7324 Integer.toHexString(System.identityHashCode(filter)));
7325 out.print(' ');
7326 out.print(filter.mActivity.flattenToShortString());
7327 out.print(" match=0x");
7328 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007330 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007332 out.print(prefix); out.print(" ");
7333 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 }
7335 }
7336 }
7337 };
7338 private final HashMap<String, SharedUserSetting> mSharedUsers =
7339 new HashMap<String, SharedUserSetting>();
7340 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7341 private final SparseArray<Object> mOtherUserIds =
7342 new SparseArray<Object>();
7343
7344 // For reading/writing settings file.
7345 private final ArrayList<Signature> mPastSignatures =
7346 new ArrayList<Signature>();
7347
7348 // Mapping from permission names to info about them.
7349 final HashMap<String, BasePermission> mPermissions =
7350 new HashMap<String, BasePermission>();
7351
7352 // Mapping from permission tree names to info about them.
7353 final HashMap<String, BasePermission> mPermissionTrees =
7354 new HashMap<String, BasePermission>();
7355
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007356 // Packages that have been uninstalled and still need their external
7357 // storage data deleted.
7358 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7359
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007360 // Packages that have been renamed since they were first installed.
7361 // Keys are the new names of the packages, values are the original
7362 // names. The packages appear everwhere else under their original
7363 // names.
7364 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007366 private final StringBuilder mReadMessages = new StringBuilder();
7367
7368 private static final class PendingPackage extends PackageSettingBase {
7369 final int sharedId;
7370
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007371 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007372 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007373 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007374 this.sharedId = sharedId;
7375 }
7376 }
7377 private final ArrayList<PendingPackage> mPendingPackages
7378 = new ArrayList<PendingPackage>();
7379
7380 Settings() {
7381 File dataDir = Environment.getDataDirectory();
7382 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007383 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7384 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007385 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007386 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 FileUtils.setPermissions(systemDir.toString(),
7388 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7389 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7390 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007391 FileUtils.setPermissions(systemSecureDir.toString(),
7392 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7393 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7394 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 mSettingsFilename = new File(systemDir, "packages.xml");
7396 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007397 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 }
7399
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007400 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007401 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 int pkgFlags, boolean create, boolean add) {
7403 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007404 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007405 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 return p;
7407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007408
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007409 PackageSetting peekPackageLP(String name) {
7410 return mPackages.get(name);
7411 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007412 PackageSetting p = mPackages.get(name);
7413 if (p != null && p.codePath.getPath().equals(codePath)) {
7414 return p;
7415 }
7416 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007417 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 void setInstallStatus(String pkgName, int status) {
7421 PackageSetting p = mPackages.get(pkgName);
7422 if(p != null) {
7423 if(p.getInstallStatus() != status) {
7424 p.setInstallStatus(status);
7425 }
7426 }
7427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007428
Jacek Surazski65e13172009-04-28 15:26:38 +02007429 void setInstallerPackageName(String pkgName,
7430 String installerPkgName) {
7431 PackageSetting p = mPackages.get(pkgName);
7432 if(p != null) {
7433 p.setInstallerPackageName(installerPkgName);
7434 }
7435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007436
Jacek Surazski65e13172009-04-28 15:26:38 +02007437 String getInstallerPackageName(String pkgName) {
7438 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007439 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007440 }
7441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 int getInstallStatus(String pkgName) {
7443 PackageSetting p = mPackages.get(pkgName);
7444 if(p != null) {
7445 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007447 return -1;
7448 }
7449
7450 SharedUserSetting getSharedUserLP(String name,
7451 int pkgFlags, boolean create) {
7452 SharedUserSetting s = mSharedUsers.get(name);
7453 if (s == null) {
7454 if (!create) {
7455 return null;
7456 }
7457 s = new SharedUserSetting(name, pkgFlags);
7458 if (MULTIPLE_APPLICATION_UIDS) {
7459 s.userId = newUserIdLP(s);
7460 } else {
7461 s.userId = FIRST_APPLICATION_UID;
7462 }
7463 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7464 // < 0 means we couldn't assign a userid; fall out and return
7465 // s, which is currently null
7466 if (s.userId >= 0) {
7467 mSharedUsers.put(name, s);
7468 }
7469 }
7470
7471 return s;
7472 }
7473
7474 int disableSystemPackageLP(String name) {
7475 PackageSetting p = mPackages.get(name);
7476 if(p == null) {
7477 Log.w(TAG, "Package:"+name+" is not an installed package");
7478 return -1;
7479 }
7480 PackageSetting dp = mDisabledSysPackages.get(name);
7481 // always make sure the system package code and resource paths dont change
7482 if(dp == null) {
7483 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7484 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7485 }
7486 mDisabledSysPackages.put(name, p);
7487 }
7488 return removePackageLP(name);
7489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007491 PackageSetting enableSystemPackageLP(String name) {
7492 PackageSetting p = mDisabledSysPackages.get(name);
7493 if(p == null) {
7494 Log.w(TAG, "Package:"+name+" is not disabled");
7495 return null;
7496 }
7497 // Reset flag in ApplicationInfo object
7498 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7499 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7500 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007501 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007502 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 mDisabledSysPackages.remove(name);
7504 return ret;
7505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007506
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007507 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007508 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 PackageSetting p = mPackages.get(name);
7510 if (p != null) {
7511 if (p.userId == uid) {
7512 return p;
7513 }
7514 reportSettingsProblem(Log.ERROR,
7515 "Adding duplicate package, keeping first: " + name);
7516 return null;
7517 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007518 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 p.userId = uid;
7520 if (addUserIdLP(uid, p, name)) {
7521 mPackages.put(name, p);
7522 return p;
7523 }
7524 return null;
7525 }
7526
7527 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7528 SharedUserSetting s = mSharedUsers.get(name);
7529 if (s != null) {
7530 if (s.userId == uid) {
7531 return s;
7532 }
7533 reportSettingsProblem(Log.ERROR,
7534 "Adding duplicate shared user, keeping first: " + name);
7535 return null;
7536 }
7537 s = new SharedUserSetting(name, pkgFlags);
7538 s.userId = uid;
7539 if (addUserIdLP(uid, s, name)) {
7540 mSharedUsers.put(name, s);
7541 return s;
7542 }
7543 return null;
7544 }
7545
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007546 // Transfer ownership of permissions from one package to another.
7547 private void transferPermissions(String origPkg, String newPkg) {
7548 // Transfer ownership of permissions to the new package.
7549 for (int i=0; i<2; i++) {
7550 HashMap<String, BasePermission> permissions =
7551 i == 0 ? mPermissionTrees : mPermissions;
7552 for (BasePermission bp : permissions.values()) {
7553 if (origPkg.equals(bp.sourcePackage)) {
7554 if (DEBUG_UPGRADE) Log.v(TAG,
7555 "Moving permission " + bp.name
7556 + " from pkg " + bp.sourcePackage
7557 + " to " + newPkg);
7558 bp.sourcePackage = newPkg;
7559 bp.perm = null;
7560 if (bp.pendingInfo != null) {
7561 bp.sourcePackage = newPkg;
7562 }
7563 bp.uid = 0;
7564 bp.gids = null;
7565 }
7566 }
7567 }
7568 }
7569
7570 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007571 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007572 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 PackageSetting p = mPackages.get(name);
7574 if (p != null) {
7575 if (!p.codePath.equals(codePath)) {
7576 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007577 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007578 // This is an updated system app with versions in both system
7579 // and data partition. Just let the most recent version
7580 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007581 Log.w(TAG, "Trying to update system app code path from " +
7582 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007583 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007584 // Just a change in the code path is not an issue, but
7585 // let's log a message about it.
7586 Log.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007587 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007589 }
7590 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 reportSettingsProblem(Log.WARN,
7592 "Package " + name + " shared user changed from "
7593 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7594 + " to "
7595 + (sharedUser != null ? sharedUser.name : "<nothing>")
7596 + "; replacing with new");
7597 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007598 } else {
7599 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7600 // If what we are scanning is a system package, then
7601 // make it so, regardless of whether it was previously
7602 // installed only in the data partition.
7603 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 }
7606 }
7607 if (p == null) {
7608 // Create a new PackageSettings entry. this can end up here because
7609 // of code path mismatch or user id mismatch of an updated system partition
7610 if (!create) {
7611 return null;
7612 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007613 if (origPackage != null) {
7614 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007615 p = new PackageSetting(origPackage.name, name, codePath,
7616 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007617 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7618 + " is adopting original package " + origPackage.name);
7619 p.copyFrom(origPackage);
7620 p.sharedUser = origPackage.sharedUser;
7621 p.userId = origPackage.userId;
7622 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007623 mRenamedPackages.put(name, origPackage.name);
7624 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007625 // Update new package state.
7626 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007628 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007629 p.setTimeStamp(codePath.lastModified());
7630 p.sharedUser = sharedUser;
7631 if (sharedUser != null) {
7632 p.userId = sharedUser.userId;
7633 } else if (MULTIPLE_APPLICATION_UIDS) {
7634 // Clone the setting here for disabled system packages
7635 PackageSetting dis = mDisabledSysPackages.get(name);
7636 if (dis != null) {
7637 // For disabled packages a new setting is created
7638 // from the existing user id. This still has to be
7639 // added to list of user id's
7640 // Copy signatures from previous setting
7641 if (dis.signatures.mSignatures != null) {
7642 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7643 }
7644 p.userId = dis.userId;
7645 // Clone permissions
7646 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7647 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7648 // Clone component info
7649 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7650 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7651 // Add new setting to list of user ids
7652 addUserIdLP(p.userId, p, name);
7653 } else {
7654 // Assign new user id
7655 p.userId = newUserIdLP(p);
7656 }
7657 } else {
7658 p.userId = FIRST_APPLICATION_UID;
7659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 }
7661 if (p.userId < 0) {
7662 reportSettingsProblem(Log.WARN,
7663 "Package " + name + " could not be assigned a valid uid");
7664 return null;
7665 }
7666 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007667 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007669 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 }
7671 }
7672 return p;
7673 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007674
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007675 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007676 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007677 String codePath = pkg.applicationInfo.sourceDir;
7678 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007679 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007680 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007681 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007682 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007683 p.codePath = new File(codePath);
7684 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007685 }
7686 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007687 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007688 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007689 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007690 p.resourcePath = new File(resourcePath);
7691 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007692 }
7693 // Update version code if needed
7694 if (pkg.mVersionCode != p.versionCode) {
7695 p.versionCode = pkg.mVersionCode;
7696 }
7697 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7698 }
7699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 // Utility method that adds a PackageSetting to mPackages and
7701 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007702 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 SharedUserSetting sharedUser) {
7704 mPackages.put(name, p);
7705 if (sharedUser != null) {
7706 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7707 reportSettingsProblem(Log.ERROR,
7708 "Package " + p.name + " was user "
7709 + p.sharedUser + " but is now " + sharedUser
7710 + "; I am not changing its files so it will probably fail!");
7711 p.sharedUser.packages.remove(p);
7712 } else if (p.userId != sharedUser.userId) {
7713 reportSettingsProblem(Log.ERROR,
7714 "Package " + p.name + " was user id " + p.userId
7715 + " but is now user " + sharedUser
7716 + " with id " + sharedUser.userId
7717 + "; I am not changing its files so it will probably fail!");
7718 }
7719
7720 sharedUser.packages.add(p);
7721 p.sharedUser = sharedUser;
7722 p.userId = sharedUser.userId;
7723 }
7724 }
7725
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007726 /*
7727 * Update the shared user setting when a package using
7728 * specifying the shared user id is removed. The gids
7729 * associated with each permission of the deleted package
7730 * are removed from the shared user's gid list only if its
7731 * not in use by other permissions of packages in the
7732 * shared user setting.
7733 */
7734 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7736 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7737 return;
7738 }
7739 // No sharedUserId
7740 if (deletedPs.sharedUser == null) {
7741 return;
7742 }
7743 SharedUserSetting sus = deletedPs.sharedUser;
7744 // Update permissions
7745 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7746 boolean used = false;
7747 if (!sus.grantedPermissions.contains (eachPerm)) {
7748 continue;
7749 }
7750 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007751 if (pkg.pkg != null &&
7752 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7753 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 used = true;
7755 break;
7756 }
7757 }
7758 if (!used) {
7759 // can safely delete this permission from list
7760 sus.grantedPermissions.remove(eachPerm);
7761 sus.loadedPermissions.remove(eachPerm);
7762 }
7763 }
7764 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007765 int newGids[] = globalGids;
7766 for (String eachPerm : sus.grantedPermissions) {
7767 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007768 if (bp != null) {
7769 newGids = appendInts(newGids, bp.gids);
7770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 }
7772 sus.gids = newGids;
7773 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 private int removePackageLP(String name) {
7776 PackageSetting p = mPackages.get(name);
7777 if (p != null) {
7778 mPackages.remove(name);
7779 if (p.sharedUser != null) {
7780 p.sharedUser.packages.remove(p);
7781 if (p.sharedUser.packages.size() == 0) {
7782 mSharedUsers.remove(p.sharedUser.name);
7783 removeUserIdLP(p.sharedUser.userId);
7784 return p.sharedUser.userId;
7785 }
7786 } else {
7787 removeUserIdLP(p.userId);
7788 return p.userId;
7789 }
7790 }
7791 return -1;
7792 }
7793
7794 private boolean addUserIdLP(int uid, Object obj, Object name) {
7795 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7796 return false;
7797 }
7798
7799 if (uid >= FIRST_APPLICATION_UID) {
7800 int N = mUserIds.size();
7801 final int index = uid - FIRST_APPLICATION_UID;
7802 while (index >= N) {
7803 mUserIds.add(null);
7804 N++;
7805 }
7806 if (mUserIds.get(index) != null) {
7807 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007808 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 + " name=" + name);
7810 return false;
7811 }
7812 mUserIds.set(index, obj);
7813 } else {
7814 if (mOtherUserIds.get(uid) != null) {
7815 reportSettingsProblem(Log.ERROR,
7816 "Adding duplicate shared id: " + uid
7817 + " name=" + name);
7818 return false;
7819 }
7820 mOtherUserIds.put(uid, obj);
7821 }
7822 return true;
7823 }
7824
7825 public Object getUserIdLP(int uid) {
7826 if (uid >= FIRST_APPLICATION_UID) {
7827 int N = mUserIds.size();
7828 final int index = uid - FIRST_APPLICATION_UID;
7829 return index < N ? mUserIds.get(index) : null;
7830 } else {
7831 return mOtherUserIds.get(uid);
7832 }
7833 }
7834
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007835 private Set<String> findPackagesWithFlag(int flag) {
7836 Set<String> ret = new HashSet<String>();
7837 for (PackageSetting ps : mPackages.values()) {
7838 // Has to match atleast all the flag bits set on flag
7839 if ((ps.pkgFlags & flag) == flag) {
7840 ret.add(ps.name);
7841 }
7842 }
7843 return ret;
7844 }
7845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 private void removeUserIdLP(int uid) {
7847 if (uid >= FIRST_APPLICATION_UID) {
7848 int N = mUserIds.size();
7849 final int index = uid - FIRST_APPLICATION_UID;
7850 if (index < N) mUserIds.set(index, null);
7851 } else {
7852 mOtherUserIds.remove(uid);
7853 }
7854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 void writeLP() {
7857 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7858
7859 // Keep the old settings around until we know the new ones have
7860 // been successfully written.
7861 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007862 // Presence of backup settings file indicates that we failed
7863 // to persist settings earlier. So preserve the older
7864 // backup for future reference since the current settings
7865 // might have been corrupted.
7866 if (!mBackupSettingsFilename.exists()) {
7867 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7868 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7869 return;
7870 }
7871 } else {
7872 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 }
7875
7876 mPastSignatures.clear();
7877
7878 try {
7879 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7880
7881 //XmlSerializer serializer = XmlUtils.serializerInstance();
7882 XmlSerializer serializer = new FastXmlSerializer();
7883 serializer.setOutput(str, "utf-8");
7884 serializer.startDocument(null, true);
7885 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7886
7887 serializer.startTag(null, "packages");
7888
7889 serializer.startTag(null, "permission-trees");
7890 for (BasePermission bp : mPermissionTrees.values()) {
7891 writePermission(serializer, bp);
7892 }
7893 serializer.endTag(null, "permission-trees");
7894
7895 serializer.startTag(null, "permissions");
7896 for (BasePermission bp : mPermissions.values()) {
7897 writePermission(serializer, bp);
7898 }
7899 serializer.endTag(null, "permissions");
7900
7901 for (PackageSetting pkg : mPackages.values()) {
7902 writePackage(serializer, pkg);
7903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7906 writeDisabledSysPackage(serializer, pkg);
7907 }
7908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 serializer.startTag(null, "preferred-activities");
7910 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7911 serializer.startTag(null, "item");
7912 pa.writeToXml(serializer);
7913 serializer.endTag(null, "item");
7914 }
7915 serializer.endTag(null, "preferred-activities");
7916
7917 for (SharedUserSetting usr : mSharedUsers.values()) {
7918 serializer.startTag(null, "shared-user");
7919 serializer.attribute(null, "name", usr.name);
7920 serializer.attribute(null, "userId",
7921 Integer.toString(usr.userId));
7922 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7923 serializer.startTag(null, "perms");
7924 for (String name : usr.grantedPermissions) {
7925 serializer.startTag(null, "item");
7926 serializer.attribute(null, "name", name);
7927 serializer.endTag(null, "item");
7928 }
7929 serializer.endTag(null, "perms");
7930 serializer.endTag(null, "shared-user");
7931 }
7932
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007933 if (mPackagesToBeCleaned.size() > 0) {
7934 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7935 serializer.startTag(null, "cleaning-package");
7936 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7937 serializer.endTag(null, "cleaning-package");
7938 }
7939 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007940
7941 if (mRenamedPackages.size() > 0) {
7942 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7943 serializer.startTag(null, "renamed-package");
7944 serializer.attribute(null, "new", e.getKey());
7945 serializer.attribute(null, "old", e.getValue());
7946 serializer.endTag(null, "renamed-package");
7947 }
7948 }
7949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 serializer.endTag(null, "packages");
7951
7952 serializer.endDocument();
7953
7954 str.flush();
7955 str.close();
7956
7957 // New settings successfully written, old ones are no longer
7958 // needed.
7959 mBackupSettingsFilename.delete();
7960 FileUtils.setPermissions(mSettingsFilename.toString(),
7961 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7962 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7963 |FileUtils.S_IROTH,
7964 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007965
7966 // Write package list file now, use a JournaledFile.
7967 //
7968 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7969 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7970
7971 str = new FileOutputStream(journal.chooseForWrite());
7972 try {
7973 StringBuilder sb = new StringBuilder();
7974 for (PackageSetting pkg : mPackages.values()) {
7975 ApplicationInfo ai = pkg.pkg.applicationInfo;
7976 String dataPath = ai.dataDir;
7977 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7978
7979 // Avoid any application that has a space in its path
7980 // or that is handled by the system.
7981 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7982 continue;
7983
7984 // we store on each line the following information for now:
7985 //
7986 // pkgName - package name
7987 // userId - application-specific user id
7988 // debugFlag - 0 or 1 if the package is debuggable.
7989 // dataPath - path to package's data path
7990 //
7991 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7992 //
7993 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7994 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7995 // system/core/run-as/run-as.c
7996 //
7997 sb.setLength(0);
7998 sb.append(ai.packageName);
7999 sb.append(" ");
8000 sb.append((int)ai.uid);
8001 sb.append(isDebug ? " 1 " : " 0 ");
8002 sb.append(dataPath);
8003 sb.append("\n");
8004 str.write(sb.toString().getBytes());
8005 }
8006 str.flush();
8007 str.close();
8008 journal.commit();
8009 }
8010 catch (Exception e) {
8011 journal.rollback();
8012 }
8013
8014 FileUtils.setPermissions(mPackageListFilename.toString(),
8015 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8016 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8017 |FileUtils.S_IROTH,
8018 -1, -1);
8019
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008020 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008021
8022 } catch(XmlPullParserException e) {
8023 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 -08008024 } catch(java.io.IOException e) {
8025 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 -08008026 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008027 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008028 if (mSettingsFilename.exists()) {
8029 if (!mSettingsFilename.delete()) {
8030 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8031 }
8032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 //Debug.stopMethodTracing();
8034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008035
8036 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008037 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 serializer.startTag(null, "updated-package");
8039 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008040 if (pkg.realName != null) {
8041 serializer.attribute(null, "realName", pkg.realName);
8042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 serializer.attribute(null, "codePath", pkg.codePathString);
8044 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008045 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8047 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8048 }
8049 if (pkg.sharedUser == null) {
8050 serializer.attribute(null, "userId",
8051 Integer.toString(pkg.userId));
8052 } else {
8053 serializer.attribute(null, "sharedUserId",
8054 Integer.toString(pkg.userId));
8055 }
8056 serializer.startTag(null, "perms");
8057 if (pkg.sharedUser == null) {
8058 // If this is a shared user, the permissions will
8059 // be written there. We still need to write an
8060 // empty permissions list so permissionsFixed will
8061 // be set.
8062 for (final String name : pkg.grantedPermissions) {
8063 BasePermission bp = mPermissions.get(name);
8064 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
8065 // We only need to write signature or system permissions but this wont
8066 // match the semantics of grantedPermissions. So write all permissions.
8067 serializer.startTag(null, "item");
8068 serializer.attribute(null, "name", name);
8069 serializer.endTag(null, "item");
8070 }
8071 }
8072 }
8073 serializer.endTag(null, "perms");
8074 serializer.endTag(null, "updated-package");
8075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008076
8077 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008078 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008079 serializer.startTag(null, "package");
8080 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008081 if (pkg.realName != null) {
8082 serializer.attribute(null, "realName", pkg.realName);
8083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 serializer.attribute(null, "codePath", pkg.codePathString);
8085 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8086 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8087 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008088 serializer.attribute(null, "flags",
8089 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008091 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 if (pkg.sharedUser == null) {
8093 serializer.attribute(null, "userId",
8094 Integer.toString(pkg.userId));
8095 } else {
8096 serializer.attribute(null, "sharedUserId",
8097 Integer.toString(pkg.userId));
8098 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008099 if (pkg.uidError) {
8100 serializer.attribute(null, "uidError", "true");
8101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8103 serializer.attribute(null, "enabled",
8104 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8105 ? "true" : "false");
8106 }
8107 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8108 serializer.attribute(null, "installStatus", "false");
8109 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008110 if (pkg.installerPackageName != null) {
8111 serializer.attribute(null, "installer", pkg.installerPackageName);
8112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8114 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8115 serializer.startTag(null, "perms");
8116 if (pkg.sharedUser == null) {
8117 // If this is a shared user, the permissions will
8118 // be written there. We still need to write an
8119 // empty permissions list so permissionsFixed will
8120 // be set.
8121 for (final String name : pkg.grantedPermissions) {
8122 serializer.startTag(null, "item");
8123 serializer.attribute(null, "name", name);
8124 serializer.endTag(null, "item");
8125 }
8126 }
8127 serializer.endTag(null, "perms");
8128 }
8129 if (pkg.disabledComponents.size() > 0) {
8130 serializer.startTag(null, "disabled-components");
8131 for (final String name : pkg.disabledComponents) {
8132 serializer.startTag(null, "item");
8133 serializer.attribute(null, "name", name);
8134 serializer.endTag(null, "item");
8135 }
8136 serializer.endTag(null, "disabled-components");
8137 }
8138 if (pkg.enabledComponents.size() > 0) {
8139 serializer.startTag(null, "enabled-components");
8140 for (final String name : pkg.enabledComponents) {
8141 serializer.startTag(null, "item");
8142 serializer.attribute(null, "name", name);
8143 serializer.endTag(null, "item");
8144 }
8145 serializer.endTag(null, "enabled-components");
8146 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 serializer.endTag(null, "package");
8149 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 void writePermission(XmlSerializer serializer, BasePermission bp)
8152 throws XmlPullParserException, java.io.IOException {
8153 if (bp.type != BasePermission.TYPE_BUILTIN
8154 && bp.sourcePackage != null) {
8155 serializer.startTag(null, "item");
8156 serializer.attribute(null, "name", bp.name);
8157 serializer.attribute(null, "package", bp.sourcePackage);
8158 if (DEBUG_SETTINGS) Log.v(TAG,
8159 "Writing perm: name=" + bp.name + " type=" + bp.type);
8160 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8161 PermissionInfo pi = bp.perm != null ? bp.perm.info
8162 : bp.pendingInfo;
8163 if (pi != null) {
8164 serializer.attribute(null, "type", "dynamic");
8165 if (pi.icon != 0) {
8166 serializer.attribute(null, "icon",
8167 Integer.toString(pi.icon));
8168 }
8169 if (pi.nonLocalizedLabel != null) {
8170 serializer.attribute(null, "label",
8171 pi.nonLocalizedLabel.toString());
8172 }
8173 if (pi.protectionLevel !=
8174 PermissionInfo.PROTECTION_NORMAL) {
8175 serializer.attribute(null, "protection",
8176 Integer.toString(pi.protectionLevel));
8177 }
8178 }
8179 }
8180 serializer.endTag(null, "item");
8181 }
8182 }
8183
8184 String getReadMessagesLP() {
8185 return mReadMessages.toString();
8186 }
8187
Oscar Montemayora8529f62009-11-18 10:14:20 -08008188 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8190 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008191 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 while(its.hasNext()) {
8193 String key = its.next();
8194 PackageSetting ps = mPackages.get(key);
8195 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008196 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 }
8198 }
8199 return ret;
8200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008202 boolean readLP() {
8203 FileInputStream str = null;
8204 if (mBackupSettingsFilename.exists()) {
8205 try {
8206 str = new FileInputStream(mBackupSettingsFilename);
8207 mReadMessages.append("Reading from backup settings file\n");
8208 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008209 if (mSettingsFilename.exists()) {
8210 // If both the backup and settings file exist, we
8211 // ignore the settings since it might have been
8212 // corrupted.
8213 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
8214 mSettingsFilename.delete();
8215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008216 } catch (java.io.IOException e) {
8217 // We'll try for the normal settings file.
8218 }
8219 }
8220
8221 mPastSignatures.clear();
8222
8223 try {
8224 if (str == null) {
8225 if (!mSettingsFilename.exists()) {
8226 mReadMessages.append("No settings file found\n");
8227 Log.i(TAG, "No current settings file!");
8228 return false;
8229 }
8230 str = new FileInputStream(mSettingsFilename);
8231 }
8232 XmlPullParser parser = Xml.newPullParser();
8233 parser.setInput(str, null);
8234
8235 int type;
8236 while ((type=parser.next()) != XmlPullParser.START_TAG
8237 && type != XmlPullParser.END_DOCUMENT) {
8238 ;
8239 }
8240
8241 if (type != XmlPullParser.START_TAG) {
8242 mReadMessages.append("No start tag found in settings file\n");
8243 Log.e(TAG, "No start tag found in package manager settings");
8244 return false;
8245 }
8246
8247 int outerDepth = parser.getDepth();
8248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8249 && (type != XmlPullParser.END_TAG
8250 || parser.getDepth() > outerDepth)) {
8251 if (type == XmlPullParser.END_TAG
8252 || type == XmlPullParser.TEXT) {
8253 continue;
8254 }
8255
8256 String tagName = parser.getName();
8257 if (tagName.equals("package")) {
8258 readPackageLP(parser);
8259 } else if (tagName.equals("permissions")) {
8260 readPermissionsLP(mPermissions, parser);
8261 } else if (tagName.equals("permission-trees")) {
8262 readPermissionsLP(mPermissionTrees, parser);
8263 } else if (tagName.equals("shared-user")) {
8264 readSharedUserLP(parser);
8265 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008266 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 } else if (tagName.equals("preferred-activities")) {
8268 readPreferredActivitiesLP(parser);
8269 } else if(tagName.equals("updated-package")) {
8270 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008271 } else if (tagName.equals("cleaning-package")) {
8272 String name = parser.getAttributeValue(null, "name");
8273 if (name != null) {
8274 mPackagesToBeCleaned.add(name);
8275 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008276 } else if (tagName.equals("renamed-package")) {
8277 String nname = parser.getAttributeValue(null, "new");
8278 String oname = parser.getAttributeValue(null, "old");
8279 if (nname != null && oname != null) {
8280 mRenamedPackages.put(nname, oname);
8281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 } else {
8283 Log.w(TAG, "Unknown element under <packages>: "
8284 + parser.getName());
8285 XmlUtils.skipCurrentTag(parser);
8286 }
8287 }
8288
8289 str.close();
8290
8291 } catch(XmlPullParserException e) {
8292 mReadMessages.append("Error reading: " + e.toString());
8293 Log.e(TAG, "Error reading package manager settings", e);
8294
8295 } catch(java.io.IOException e) {
8296 mReadMessages.append("Error reading: " + e.toString());
8297 Log.e(TAG, "Error reading package manager settings", e);
8298
8299 }
8300
8301 int N = mPendingPackages.size();
8302 for (int i=0; i<N; i++) {
8303 final PendingPackage pp = mPendingPackages.get(i);
8304 Object idObj = getUserIdLP(pp.sharedId);
8305 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008306 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008307 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008308 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 if (p == null) {
8310 Log.w(TAG, "Unable to create application package for "
8311 + pp.name);
8312 continue;
8313 }
8314 p.copyFrom(pp);
8315 } else if (idObj != null) {
8316 String msg = "Bad package setting: package " + pp.name
8317 + " has shared uid " + pp.sharedId
8318 + " that is not a shared uid\n";
8319 mReadMessages.append(msg);
8320 Log.e(TAG, msg);
8321 } else {
8322 String msg = "Bad package setting: package " + pp.name
8323 + " has shared uid " + pp.sharedId
8324 + " that is not defined\n";
8325 mReadMessages.append(msg);
8326 Log.e(TAG, msg);
8327 }
8328 }
8329 mPendingPackages.clear();
8330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 mReadMessages.append("Read completed successfully: "
8332 + mPackages.size() + " packages, "
8333 + mSharedUsers.size() + " shared uids\n");
8334
8335 return true;
8336 }
8337
8338 private int readInt(XmlPullParser parser, String ns, String name,
8339 int defValue) {
8340 String v = parser.getAttributeValue(ns, name);
8341 try {
8342 if (v == null) {
8343 return defValue;
8344 }
8345 return Integer.parseInt(v);
8346 } catch (NumberFormatException e) {
8347 reportSettingsProblem(Log.WARN,
8348 "Error in package manager settings: attribute " +
8349 name + " has bad integer value " + v + " at "
8350 + parser.getPositionDescription());
8351 }
8352 return defValue;
8353 }
8354
8355 private void readPermissionsLP(HashMap<String, BasePermission> out,
8356 XmlPullParser parser)
8357 throws IOException, XmlPullParserException {
8358 int outerDepth = parser.getDepth();
8359 int type;
8360 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8361 && (type != XmlPullParser.END_TAG
8362 || parser.getDepth() > outerDepth)) {
8363 if (type == XmlPullParser.END_TAG
8364 || type == XmlPullParser.TEXT) {
8365 continue;
8366 }
8367
8368 String tagName = parser.getName();
8369 if (tagName.equals("item")) {
8370 String name = parser.getAttributeValue(null, "name");
8371 String sourcePackage = parser.getAttributeValue(null, "package");
8372 String ptype = parser.getAttributeValue(null, "type");
8373 if (name != null && sourcePackage != null) {
8374 boolean dynamic = "dynamic".equals(ptype);
8375 BasePermission bp = new BasePermission(name, sourcePackage,
8376 dynamic
8377 ? BasePermission.TYPE_DYNAMIC
8378 : BasePermission.TYPE_NORMAL);
8379 if (dynamic) {
8380 PermissionInfo pi = new PermissionInfo();
8381 pi.packageName = sourcePackage.intern();
8382 pi.name = name.intern();
8383 pi.icon = readInt(parser, null, "icon", 0);
8384 pi.nonLocalizedLabel = parser.getAttributeValue(
8385 null, "label");
8386 pi.protectionLevel = readInt(parser, null, "protection",
8387 PermissionInfo.PROTECTION_NORMAL);
8388 bp.pendingInfo = pi;
8389 }
8390 out.put(bp.name, bp);
8391 } else {
8392 reportSettingsProblem(Log.WARN,
8393 "Error in package manager settings: permissions has"
8394 + " no name at " + parser.getPositionDescription());
8395 }
8396 } else {
8397 reportSettingsProblem(Log.WARN,
8398 "Unknown element reading permissions: "
8399 + parser.getName() + " at "
8400 + parser.getPositionDescription());
8401 }
8402 XmlUtils.skipCurrentTag(parser);
8403 }
8404 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008407 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008409 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 String codePathStr = parser.getAttributeValue(null, "codePath");
8411 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008412 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008413 resourcePathStr = codePathStr;
8414 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008415 String version = parser.getAttributeValue(null, "version");
8416 int versionCode = 0;
8417 if (version != null) {
8418 try {
8419 versionCode = Integer.parseInt(version);
8420 } catch (NumberFormatException e) {
8421 }
8422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008424 int pkgFlags = 0;
8425 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008426 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008427 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008428 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008429 String timeStampStr = parser.getAttributeValue(null, "ts");
8430 if (timeStampStr != null) {
8431 try {
8432 long timeStamp = Long.parseLong(timeStampStr);
8433 ps.setTimeStamp(timeStamp, timeStampStr);
8434 } catch (NumberFormatException e) {
8435 }
8436 }
8437 String idStr = parser.getAttributeValue(null, "userId");
8438 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8439 if(ps.userId <= 0) {
8440 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8441 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8442 }
8443 int outerDepth = parser.getDepth();
8444 int type;
8445 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8446 && (type != XmlPullParser.END_TAG
8447 || parser.getDepth() > outerDepth)) {
8448 if (type == XmlPullParser.END_TAG
8449 || type == XmlPullParser.TEXT) {
8450 continue;
8451 }
8452
8453 String tagName = parser.getName();
8454 if (tagName.equals("perms")) {
8455 readGrantedPermissionsLP(parser,
8456 ps.grantedPermissions);
8457 } else {
8458 reportSettingsProblem(Log.WARN,
8459 "Unknown element under <updated-package>: "
8460 + parser.getName());
8461 XmlUtils.skipCurrentTag(parser);
8462 }
8463 }
8464 mDisabledSysPackages.put(name, ps);
8465 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 private void readPackageLP(XmlPullParser parser)
8468 throws XmlPullParserException, IOException {
8469 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008470 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 String idStr = null;
8472 String sharedIdStr = null;
8473 String codePathStr = null;
8474 String resourcePathStr = null;
8475 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008476 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008477 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 int pkgFlags = 0;
8479 String timeStampStr;
8480 long timeStamp = 0;
8481 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008482 String version = null;
8483 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 try {
8485 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008486 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008488 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8490 codePathStr = parser.getAttributeValue(null, "codePath");
8491 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008492 version = parser.getAttributeValue(null, "version");
8493 if (version != null) {
8494 try {
8495 versionCode = Integer.parseInt(version);
8496 } catch (NumberFormatException e) {
8497 }
8498 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008499 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008500
8501 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008503 try {
8504 pkgFlags = Integer.parseInt(systemStr);
8505 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 }
8507 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008508 // For backward compatibility
8509 systemStr = parser.getAttributeValue(null, "system");
8510 if (systemStr != null) {
8511 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8512 } else {
8513 // Old settings that don't specify system... just treat
8514 // them as system, good enough.
8515 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 }
8518 timeStampStr = parser.getAttributeValue(null, "ts");
8519 if (timeStampStr != null) {
8520 try {
8521 timeStamp = Long.parseLong(timeStampStr);
8522 } catch (NumberFormatException e) {
8523 }
8524 }
8525 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8526 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8527 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8528 if (resourcePathStr == null) {
8529 resourcePathStr = codePathStr;
8530 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008531 if (realName != null) {
8532 realName = realName.intern();
8533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 if (name == null) {
8535 reportSettingsProblem(Log.WARN,
8536 "Error in package manager settings: <package> has no name at "
8537 + parser.getPositionDescription());
8538 } else if (codePathStr == null) {
8539 reportSettingsProblem(Log.WARN,
8540 "Error in package manager settings: <package> has no codePath at "
8541 + parser.getPositionDescription());
8542 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008543 packageSetting = addPackageLP(name.intern(), realName,
8544 new File(codePathStr), new File(resourcePathStr),
8545 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8547 + ": userId=" + userId + " pkg=" + packageSetting);
8548 if (packageSetting == null) {
8549 reportSettingsProblem(Log.ERROR,
8550 "Failure adding uid " + userId
8551 + " while parsing settings at "
8552 + parser.getPositionDescription());
8553 } else {
8554 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8555 }
8556 } else if (sharedIdStr != null) {
8557 userId = sharedIdStr != null
8558 ? Integer.parseInt(sharedIdStr) : 0;
8559 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008560 packageSetting = new PendingPackage(name.intern(), realName,
8561 new File(codePathStr), new File(resourcePathStr),
8562 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8564 mPendingPackages.add((PendingPackage) packageSetting);
8565 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8566 + ": sharedUserId=" + userId + " pkg="
8567 + packageSetting);
8568 } else {
8569 reportSettingsProblem(Log.WARN,
8570 "Error in package manager settings: package "
8571 + name + " has bad sharedId " + sharedIdStr
8572 + " at " + parser.getPositionDescription());
8573 }
8574 } else {
8575 reportSettingsProblem(Log.WARN,
8576 "Error in package manager settings: package "
8577 + name + " has bad userId " + idStr + " at "
8578 + parser.getPositionDescription());
8579 }
8580 } catch (NumberFormatException e) {
8581 reportSettingsProblem(Log.WARN,
8582 "Error in package manager settings: package "
8583 + name + " has bad userId " + idStr + " at "
8584 + parser.getPositionDescription());
8585 }
8586 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008587 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008588 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008589 final String enabledStr = parser.getAttributeValue(null, "enabled");
8590 if (enabledStr != null) {
8591 if (enabledStr.equalsIgnoreCase("true")) {
8592 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8593 } else if (enabledStr.equalsIgnoreCase("false")) {
8594 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8595 } else if (enabledStr.equalsIgnoreCase("default")) {
8596 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8597 } else {
8598 reportSettingsProblem(Log.WARN,
8599 "Error in package manager settings: package "
8600 + name + " has bad enabled value: " + idStr
8601 + " at " + parser.getPositionDescription());
8602 }
8603 } else {
8604 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8605 }
8606 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8607 if (installStatusStr != null) {
8608 if (installStatusStr.equalsIgnoreCase("false")) {
8609 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8610 } else {
8611 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8612 }
8613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 int outerDepth = parser.getDepth();
8616 int type;
8617 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8618 && (type != XmlPullParser.END_TAG
8619 || parser.getDepth() > outerDepth)) {
8620 if (type == XmlPullParser.END_TAG
8621 || type == XmlPullParser.TEXT) {
8622 continue;
8623 }
8624
8625 String tagName = parser.getName();
8626 if (tagName.equals("disabled-components")) {
8627 readDisabledComponentsLP(packageSetting, parser);
8628 } else if (tagName.equals("enabled-components")) {
8629 readEnabledComponentsLP(packageSetting, parser);
8630 } else if (tagName.equals("sigs")) {
8631 packageSetting.signatures.readXml(parser, mPastSignatures);
8632 } else if (tagName.equals("perms")) {
8633 readGrantedPermissionsLP(parser,
8634 packageSetting.loadedPermissions);
8635 packageSetting.permissionsFixed = true;
8636 } else {
8637 reportSettingsProblem(Log.WARN,
8638 "Unknown element under <package>: "
8639 + parser.getName());
8640 XmlUtils.skipCurrentTag(parser);
8641 }
8642 }
8643 } else {
8644 XmlUtils.skipCurrentTag(parser);
8645 }
8646 }
8647
8648 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8649 XmlPullParser parser)
8650 throws IOException, XmlPullParserException {
8651 int outerDepth = parser.getDepth();
8652 int type;
8653 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8654 && (type != XmlPullParser.END_TAG
8655 || parser.getDepth() > outerDepth)) {
8656 if (type == XmlPullParser.END_TAG
8657 || type == XmlPullParser.TEXT) {
8658 continue;
8659 }
8660
8661 String tagName = parser.getName();
8662 if (tagName.equals("item")) {
8663 String name = parser.getAttributeValue(null, "name");
8664 if (name != null) {
8665 packageSetting.disabledComponents.add(name.intern());
8666 } else {
8667 reportSettingsProblem(Log.WARN,
8668 "Error in package manager settings: <disabled-components> has"
8669 + " no name at " + parser.getPositionDescription());
8670 }
8671 } else {
8672 reportSettingsProblem(Log.WARN,
8673 "Unknown element under <disabled-components>: "
8674 + parser.getName());
8675 }
8676 XmlUtils.skipCurrentTag(parser);
8677 }
8678 }
8679
8680 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8681 XmlPullParser parser)
8682 throws IOException, XmlPullParserException {
8683 int outerDepth = parser.getDepth();
8684 int type;
8685 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8686 && (type != XmlPullParser.END_TAG
8687 || parser.getDepth() > outerDepth)) {
8688 if (type == XmlPullParser.END_TAG
8689 || type == XmlPullParser.TEXT) {
8690 continue;
8691 }
8692
8693 String tagName = parser.getName();
8694 if (tagName.equals("item")) {
8695 String name = parser.getAttributeValue(null, "name");
8696 if (name != null) {
8697 packageSetting.enabledComponents.add(name.intern());
8698 } else {
8699 reportSettingsProblem(Log.WARN,
8700 "Error in package manager settings: <enabled-components> has"
8701 + " no name at " + parser.getPositionDescription());
8702 }
8703 } else {
8704 reportSettingsProblem(Log.WARN,
8705 "Unknown element under <enabled-components>: "
8706 + parser.getName());
8707 }
8708 XmlUtils.skipCurrentTag(parser);
8709 }
8710 }
8711
8712 private void readSharedUserLP(XmlPullParser parser)
8713 throws XmlPullParserException, IOException {
8714 String name = null;
8715 String idStr = null;
8716 int pkgFlags = 0;
8717 SharedUserSetting su = null;
8718 try {
8719 name = parser.getAttributeValue(null, "name");
8720 idStr = parser.getAttributeValue(null, "userId");
8721 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8722 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8723 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8724 }
8725 if (name == null) {
8726 reportSettingsProblem(Log.WARN,
8727 "Error in package manager settings: <shared-user> has no name at "
8728 + parser.getPositionDescription());
8729 } else if (userId == 0) {
8730 reportSettingsProblem(Log.WARN,
8731 "Error in package manager settings: shared-user "
8732 + name + " has bad userId " + idStr + " at "
8733 + parser.getPositionDescription());
8734 } else {
8735 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8736 reportSettingsProblem(Log.ERROR,
8737 "Occurred while parsing settings at "
8738 + parser.getPositionDescription());
8739 }
8740 }
8741 } catch (NumberFormatException e) {
8742 reportSettingsProblem(Log.WARN,
8743 "Error in package manager settings: package "
8744 + name + " has bad userId " + idStr + " at "
8745 + parser.getPositionDescription());
8746 };
8747
8748 if (su != null) {
8749 int outerDepth = parser.getDepth();
8750 int type;
8751 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8752 && (type != XmlPullParser.END_TAG
8753 || parser.getDepth() > outerDepth)) {
8754 if (type == XmlPullParser.END_TAG
8755 || type == XmlPullParser.TEXT) {
8756 continue;
8757 }
8758
8759 String tagName = parser.getName();
8760 if (tagName.equals("sigs")) {
8761 su.signatures.readXml(parser, mPastSignatures);
8762 } else if (tagName.equals("perms")) {
8763 readGrantedPermissionsLP(parser, su.loadedPermissions);
8764 } else {
8765 reportSettingsProblem(Log.WARN,
8766 "Unknown element under <shared-user>: "
8767 + parser.getName());
8768 XmlUtils.skipCurrentTag(parser);
8769 }
8770 }
8771
8772 } else {
8773 XmlUtils.skipCurrentTag(parser);
8774 }
8775 }
8776
8777 private void readGrantedPermissionsLP(XmlPullParser parser,
8778 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8779 int outerDepth = parser.getDepth();
8780 int type;
8781 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8782 && (type != XmlPullParser.END_TAG
8783 || parser.getDepth() > outerDepth)) {
8784 if (type == XmlPullParser.END_TAG
8785 || type == XmlPullParser.TEXT) {
8786 continue;
8787 }
8788
8789 String tagName = parser.getName();
8790 if (tagName.equals("item")) {
8791 String name = parser.getAttributeValue(null, "name");
8792 if (name != null) {
8793 outPerms.add(name.intern());
8794 } else {
8795 reportSettingsProblem(Log.WARN,
8796 "Error in package manager settings: <perms> has"
8797 + " no name at " + parser.getPositionDescription());
8798 }
8799 } else {
8800 reportSettingsProblem(Log.WARN,
8801 "Unknown element under <perms>: "
8802 + parser.getName());
8803 }
8804 XmlUtils.skipCurrentTag(parser);
8805 }
8806 }
8807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 private void readPreferredActivitiesLP(XmlPullParser parser)
8809 throws XmlPullParserException, IOException {
8810 int outerDepth = parser.getDepth();
8811 int type;
8812 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8813 && (type != XmlPullParser.END_TAG
8814 || parser.getDepth() > outerDepth)) {
8815 if (type == XmlPullParser.END_TAG
8816 || type == XmlPullParser.TEXT) {
8817 continue;
8818 }
8819
8820 String tagName = parser.getName();
8821 if (tagName.equals("item")) {
8822 PreferredActivity pa = new PreferredActivity(parser);
8823 if (pa.mParseError == null) {
8824 mPreferredActivities.addFilter(pa);
8825 } else {
8826 reportSettingsProblem(Log.WARN,
8827 "Error in package manager settings: <preferred-activity> "
8828 + pa.mParseError + " at "
8829 + parser.getPositionDescription());
8830 }
8831 } else {
8832 reportSettingsProblem(Log.WARN,
8833 "Unknown element under <preferred-activities>: "
8834 + parser.getName());
8835 XmlUtils.skipCurrentTag(parser);
8836 }
8837 }
8838 }
8839
8840 // Returns -1 if we could not find an available UserId to assign
8841 private int newUserIdLP(Object obj) {
8842 // Let's be stupidly inefficient for now...
8843 final int N = mUserIds.size();
8844 for (int i=0; i<N; i++) {
8845 if (mUserIds.get(i) == null) {
8846 mUserIds.set(i, obj);
8847 return FIRST_APPLICATION_UID + i;
8848 }
8849 }
8850
8851 // None left?
8852 if (N >= MAX_APPLICATION_UIDS) {
8853 return -1;
8854 }
8855
8856 mUserIds.add(obj);
8857 return FIRST_APPLICATION_UID + N;
8858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 public PackageSetting getDisabledSystemPkg(String name) {
8861 synchronized(mPackages) {
8862 PackageSetting ps = mDisabledSysPackages.get(name);
8863 return ps;
8864 }
8865 }
8866
8867 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8868 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8869 if (Config.LOGV) {
8870 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8871 + " componentName = " + componentInfo.name);
8872 Log.v(TAG, "enabledComponents: "
8873 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8874 Log.v(TAG, "disabledComponents: "
8875 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8876 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008877 if (packageSettings == null) {
8878 if (false) {
8879 Log.w(TAG, "WAITING FOR DEBUGGER");
8880 Debug.waitForDebugger();
8881 Log.i(TAG, "We will crash!");
8882 }
8883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8885 || ((componentInfo.enabled
8886 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8887 || (componentInfo.applicationInfo.enabled
8888 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8889 && !packageSettings.disabledComponents.contains(componentInfo.name))
8890 || packageSettings.enabledComponents.contains(componentInfo.name));
8891 }
8892 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008893
8894 // ------- apps on sdcard specific code -------
8895 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008896 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008897 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008898 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008899 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008900
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008901 private String getEncryptKey() {
8902 try {
8903 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8904 if (sdEncKey == null) {
8905 sdEncKey = SystemKeyStore.getInstance().
8906 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8907 if (sdEncKey == null) {
8908 Log.e(TAG, "Failed to create encryption keys");
8909 return null;
8910 }
8911 }
8912 return sdEncKey;
8913 } catch (NoSuchAlgorithmException nsae) {
8914 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8915 return null;
8916 }
8917 }
8918
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008919 static String getTempContainerId() {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008920 String prefix = "smdl2tmp";
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008921 int tmpIdx = 1;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008922 String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008923 if (list != null) {
8924 int idx = 0;
8925 int idList[] = new int[MAX_CONTAINERS];
8926 boolean neverFound = true;
8927 for (String name : list) {
8928 // Ignore null entries
8929 if (name == null) {
8930 continue;
8931 }
8932 int sidx = name.indexOf(prefix);
8933 if (sidx == -1) {
8934 // Not a temp file. just ignore
8935 continue;
8936 }
8937 String subStr = name.substring(sidx + prefix.length());
8938 idList[idx] = -1;
8939 if (subStr != null) {
8940 try {
8941 int cid = Integer.parseInt(subStr);
8942 idList[idx++] = cid;
8943 neverFound = false;
8944 } catch (NumberFormatException e) {
8945 }
8946 }
8947 }
8948 if (!neverFound) {
8949 // Sort idList
8950 Arrays.sort(idList);
8951 for (int j = 1; j <= idList.length; j++) {
8952 if (idList[j-1] != j) {
8953 tmpIdx = j;
8954 break;
8955 }
8956 }
8957 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008958 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008959 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008960 }
8961
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08008962 /*
8963 * Return true if PackageManager does have packages to be updated.
8964 */
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008965 public boolean updateExternalMediaStatus(final boolean mediaStatus) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008966 final boolean ret;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008967 synchronized (mPackages) {
8968 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8969 mediaStatus+", mMediaMounted=" + mMediaMounted);
8970 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008971 return false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008972 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008973 mMediaMounted = mediaStatus;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008974 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8975 ret = appList != null && appList.size() > 0;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008976 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008977 // Queue up an async operation since the package installation may take a little while.
8978 mHandler.post(new Runnable() {
8979 public void run() {
8980 mHandler.removeCallbacks(this);
8981 updateExternalMediaStatusInner(mediaStatus, ret);
8982 }
8983 });
8984 return ret;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008985 }
8986
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008987 private void updateExternalMediaStatusInner(boolean mediaStatus,
8988 boolean sendUpdateBroadcast) {
8989 // If we are up here that means there are packages to be
8990 // enabled or disabled.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08008991 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008992 if (list == null || list.length == 0) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008993 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008994 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08008995
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008996 int uidList[] = new int[list.length];
8997 int num = 0;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08008998 HashSet<String> removeCids = new HashSet<String>();
8999 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9000 /*HashMap<String, String> cidPathMap = new HashMap<String, String>();
9001 // Don't hold any locks when getting cache paths
9002 for (String cid : list) {
9003 String cpath = PackageHelper.getSdDir(cid);
9004 if (cpath == null) {
9005 removeCids.add(cid);
9006 } else {
9007 cidPathMap.put(cid, cpath);
9008 }
9009 }*/
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009010 synchronized (mPackages) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009011 for (String cid : list) {
9012 SdInstallArgs args = new SdInstallArgs(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009013 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
9014 boolean failed = true;
9015 try {
9016 String pkgName = args.getPackageName();
9017 if (pkgName == null) {
9018 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009019 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009020 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9021 PackageSetting ps = mSettings.mPackages.get(pkgName);
9022 if (ps != null && ps.codePathString != null &&
9023 (ps.pkgFlags & ApplicationInfo.FLAG_ON_SDCARD) != 0) {
9024 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9025 " corresponds to pkg : " + pkgName +
9026 " at code path: " + ps.codePathString);
9027 // We do have a valid package installed on sdcard
9028 processCids.put(args, ps.codePathString);
9029 failed = false;
9030 int uid = ps.userId;
9031 if (uid != -1) {
9032 uidList[num++] = uid;
9033 }
9034 }
9035 } finally {
9036 if (failed) {
9037 // Stale container on sdcard. Just delete
9038 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9039 removeCids.add(cid);
9040 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009041 }
9042 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009043 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009044 // Organize uids
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009045 int uidArr[] = null;
9046 if (num > 0) {
9047 // Sort uid list
9048 Arrays.sort(uidList, 0, num);
9049 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009050 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009051 uidArr[0] = uidList[0];
9052 int di = 0;
9053 for (int i = 1; i < num; i++) {
9054 if (uidList[i-1] != uidList[i]) {
9055 uidArr[di++] = uidList[i];
9056 }
9057 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009058 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009059 // Process packages with valid entries.
9060 if (mediaStatus) {
9061 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
9062 loadMediaPackages(processCids, uidArr, sendUpdateBroadcast, removeCids);
9063 startCleaningPackages();
9064 } else {
9065 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
9066 unloadMediaPackages(processCids, uidArr, sendUpdateBroadcast);
9067 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009068 }
9069
9070 private void sendResourcesChangedBroadcast(boolean mediaStatus,
9071 ArrayList<String> pkgList, int uidArr[]) {
9072 int size = pkgList.size();
9073 if (size > 0) {
9074 // Send broadcasts here
9075 Bundle extras = new Bundle();
9076 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9077 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009078 if (uidArr != null) {
9079 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9080 }
9081 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9082 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009083 sendPackageBroadcast(action, null, extras);
9084 }
9085 }
9086
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009087 /*
9088 * Look at potentially valid container ids from processCids
9089 * If package information doesn't match the one on record
9090 * or package scanning fails, the cid is added to list of
9091 * removeCids and cleaned up. Since cleaning up containers
9092 * involves destroying them, we do not want any parse
9093 * references to such stale containers. So force gc's
9094 * to avoid unnecessary crashes.
9095 */
9096 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9097 int uidArr[], boolean sendUpdateBroadcast,
9098 HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009099 ArrayList<String> pkgList = new ArrayList<String>();
9100 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009101 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009102 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009103 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9105 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009106 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009107 try {
9108 // Make sure there are no container errors first.
9109 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9110 != PackageManager.INSTALL_SUCCEEDED) {
9111 Log.e(TAG, "Failed to mount cid : " + args.cid +
9112 " when installing from sdcard");
9113 continue;
9114 }
9115 // Check code path here.
9116 if (codePath == null || !codePath.equals(args.getCodePath())) {
9117 Log.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
9118 " does not match one in settings " + codePath);
9119 continue;
9120 }
9121 // Parse package
9122 int parseFlags = PackageParser.PARSE_CHATTY |
9123 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
9124 PackageParser pp = new PackageParser(codePath);
9125 pp.setSeparateProcesses(mSeparateProcesses);
9126 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
9127 codePath, mMetrics, parseFlags);
9128 pp = null;
9129 doGc = true;
9130 // Check for parse errors
9131 if (pkg == null) {
9132 Log.e(TAG, "Parse error when installing install pkg : "
9133 + args.cid + " from " + args.cachePath);
9134 continue;
9135 }
9136 setApplicationInfoPaths(pkg, codePath, codePath);
9137 synchronized (mInstallLock) {
9138 // Scan the package
9139 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
9140 synchronized (mPackages) {
9141 // Grant permissions
9142 grantPermissionsLP(pkg, false);
9143 // Persist settings
9144 mSettings.writeLP();
9145 retCode = PackageManager.INSTALL_SUCCEEDED;
9146 pkgList.add(pkg.packageName);
9147 // Post process args
9148 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9149 }
9150 } else {
9151 Log.i(TAG, "Failed to install pkg: " +
9152 pkg.packageName + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009153 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009154 }
9155
9156 } finally {
9157 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9158 // Don't destroy container here. Wait till gc clears things up.
9159 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009160 }
9161 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009162 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009163 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009164 if (sendUpdateBroadcast) {
9165 sendResourcesChangedBroadcast(true, pkgList, uidArr);
9166 }
9167 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009168 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009169 }
9170 // Delete any stale containers if needed.
9171 if (removeCids != null) {
9172 for (String cid : removeCids) {
9173 Log.i(TAG, "Destroying stale container : " + cid);
9174 PackageHelper.destroySdDir(cid);
9175 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009176 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009177 }
9178
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009179 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
9180 int uidArr[], boolean sendUpdateBroadcast) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009181 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009182 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009183 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009184 Set<SdInstallArgs> keys = processCids.keySet();
9185 for (SdInstallArgs args : keys) {
9186 String cid = args.cid;
9187 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009188 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009189 // Delete package internally
9190 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9191 synchronized (mInstallLock) {
9192 boolean res = deletePackageLI(pkgName, false,
9193 PackageManager.DONT_DELETE_DATA, outInfo);
9194 if (res) {
9195 pkgList.add(pkgName);
9196 } else {
9197 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009198 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009199 }
9200 }
9201 }
9202 // Send broadcasts
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009203 if (sendUpdateBroadcast) {
9204 sendResourcesChangedBroadcast(false, pkgList, uidArr);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009205 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009206 // Force gc
9207 Runtime.getRuntime().gc();
9208 // Just unmount all valid containers.
9209 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009210 synchronized (mInstallLock) {
9211 args.doPostDeleteLI(false);
9212 }
9213 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009214 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009215
9216 public void movePackage(final String packageName,
9217 final IPackageMoveObserver observer, final int flags) {
9218 if (packageName == null) {
9219 return;
9220 }
9221 mContext.enforceCallingOrSelfPermission(
9222 android.Manifest.permission.MOVE_PACKAGE, null);
9223 int returnCode = PackageManager.MOVE_SUCCEEDED;
9224 int currFlags = 0;
9225 int newFlags = 0;
9226 synchronized (mPackages) {
9227 PackageParser.Package pkg = mPackages.get(packageName);
9228 if (pkg == null) {
9229 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9230 }
9231 // Disable moving fwd locked apps and system packages
9232 if (pkg.applicationInfo != null &&
9233 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9234 Log.w(TAG, "Cannot move system application");
9235 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9236 } else if (pkg.applicationInfo != null &&
9237 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9238 Log.w(TAG, "Cannot move forward locked app.");
9239 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
9240 } else {
9241 // Find install location first
9242 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9243 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9244 Log.w(TAG, "Ambigous flags specified for move location.");
9245 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9246 } else {
9247 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9248 PackageManager.INSTALL_EXTERNAL : 0;
9249 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD) != 0 ?
9250 PackageManager.INSTALL_EXTERNAL : 0;
9251 if (newFlags == currFlags) {
9252 Log.w(TAG, "No move required. Trying to move to same location");
9253 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9254 }
9255 }
9256 }
9257 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
9258 processPendingMove(new MoveParams(null, observer, 0, null), returnCode);
9259 } else {
9260 Message msg = mHandler.obtainMessage(INIT_COPY);
9261 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9262 pkg.applicationInfo.publicSourceDir);
9263 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9264 packageName);
9265 msg.obj = mp;
9266 mHandler.sendMessage(msg);
9267 }
9268 }
9269 }
9270
9271 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9272 // Queue up an async operation since the package deletion may take a little while.
9273 mHandler.post(new Runnable() {
9274 public void run() {
9275 mHandler.removeCallbacks(this);
9276 int returnCode = currentStatus;
9277 boolean moveSucceeded = (returnCode == PackageManager.MOVE_SUCCEEDED);
9278 if (moveSucceeded) {
9279 int uid = -1;
9280 synchronized (mPackages) {
9281 uid = mPackages.get(mp.packageName).applicationInfo.uid;
9282 }
9283 ArrayList<String> pkgList = new ArrayList<String>();
9284 pkgList.add(mp.packageName);
9285 int uidArr[] = new int[] { uid };
9286 // Send resources unavailable broadcast
9287 sendResourcesChangedBroadcast(false, pkgList, uidArr);
9288
9289 // Update package code and resource paths
9290 synchronized (mPackages) {
9291 PackageParser.Package pkg = mPackages.get(mp.packageName);
9292 if (pkg != null) {
9293 String oldCodePath = pkg.mPath;
9294 String newCodePath = mp.targetArgs.getCodePath();
9295 String newResPath = mp.targetArgs.getResourcePath();
9296 pkg.mPath = newCodePath;
9297 // Move dex files around
9298 if (moveDexFiles(pkg)
9299 != PackageManager.INSTALL_SUCCEEDED) {
9300 // Moving of dex files failed. Set
9301 // error code and abort move.
9302 pkg.mPath = pkg.mScanPath;
9303 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9304 moveSucceeded = false;
9305 } else {
9306 pkg.mScanPath = newCodePath;
9307 pkg.applicationInfo.sourceDir = newCodePath;
9308 pkg.applicationInfo.publicSourceDir = newResPath;
9309 PackageSetting ps = (PackageSetting) pkg.mExtras;
9310 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9311 ps.codePathString = ps.codePath.getPath();
9312 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9313 ps.resourcePathString = ps.resourcePath.getPath();
9314 // Set the application info flag correctly.
9315 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9316 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_ON_SDCARD;
9317 } else {
9318 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_ON_SDCARD;
9319 }
9320 ps.setFlags(pkg.applicationInfo.flags);
9321 mAppDirs.remove(oldCodePath);
9322 mAppDirs.put(newCodePath, pkg);
9323 // Persist settings
9324 mSettings.writeLP();
9325 }
9326 }
9327 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009328 // Send resources available broadcast
9329 sendResourcesChangedBroadcast(true, pkgList, uidArr);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009330 }
9331 if (!moveSucceeded){
9332 // Clean up failed installation
9333 if (mp.targetArgs != null) {
9334 mp.targetArgs.doPostInstall(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009335 returnCode);
9336 }
9337 } else {
9338 // Force a gc to clear things up.
9339 Runtime.getRuntime().gc();
9340 // Delete older code
9341 synchronized (mInstallLock) {
9342 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009343 }
9344 }
9345 IPackageMoveObserver observer = mp.observer;
9346 if (observer != null) {
9347 try {
9348 observer.packageMoved(mp.packageName, returnCode);
9349 } catch (RemoteException e) {
9350 Log.i(TAG, "Observer no longer exists.");
9351 }
9352 }
9353 }
9354 });
9355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356}