blob: a5213a02fd9f2f402ac86ff69016c3734bcac8f7 [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;
Tom Taylord4a47292009-12-21 13:59:18 -080021import com.android.common.FastXmlSerializer;
22import com.android.common.XmlUtils;
David 'Digit' Turneradd13762010-02-03 17:34:58 -080023import com.android.server.JournaledFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024
25import org.xmlpull.v1.XmlPullParser;
26import org.xmlpull.v1.XmlPullParserException;
27import org.xmlpull.v1.XmlSerializer;
28
29import android.app.ActivityManagerNative;
30import android.app.IActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.ComponentName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070035import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080036import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070037import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.pm.ActivityInfo;
39import android.content.pm.ApplicationInfo;
40import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070041import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.IPackageDataObserver;
43import android.content.pm.IPackageDeleteObserver;
44import android.content.pm.IPackageInstallObserver;
45import android.content.pm.IPackageManager;
46import android.content.pm.IPackageStatsObserver;
47import android.content.pm.InstrumentationInfo;
48import android.content.pm.PackageInfo;
49import android.content.pm.PackageManager;
50import android.content.pm.PackageStats;
51import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
52import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
53import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
54import static android.content.pm.PackageManager.PKG_INSTALL_COMPLETE;
55import static android.content.pm.PackageManager.PKG_INSTALL_INCOMPLETE;
56import android.content.pm.PackageParser;
57import android.content.pm.PermissionInfo;
58import android.content.pm.PermissionGroupInfo;
59import android.content.pm.ProviderInfo;
60import android.content.pm.ResolveInfo;
61import android.content.pm.ServiceInfo;
62import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.Uri;
64import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070065import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080067import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080069import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070070import android.os.Looper;
71import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Parcel;
73import android.os.RemoteException;
74import android.os.Environment;
75import android.os.FileObserver;
76import android.os.FileUtils;
77import android.os.Handler;
San Mehatb1043402010-02-05 08:26:50 -080078import android.os.storage.StorageResultCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.ParcelFileDescriptor;
80import android.os.Process;
81import android.os.ServiceManager;
82import android.os.SystemClock;
83import android.os.SystemProperties;
Oscar Montemayord02546b2010-01-14 16:38:40 -080084import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.util.*;
86import android.view.Display;
87import android.view.WindowManager;
88
89import java.io.File;
90import java.io.FileDescriptor;
91import java.io.FileInputStream;
92import java.io.FileNotFoundException;
93import java.io.FileOutputStream;
94import java.io.FileReader;
95import java.io.FilenameFilter;
96import java.io.IOException;
97import java.io.InputStream;
98import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -080099import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800100import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.util.ArrayList;
102import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700103import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.util.Collections;
105import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Enumeration;
108import java.util.HashMap;
109import java.util.HashSet;
110import java.util.Iterator;
111import java.util.List;
112import java.util.Map;
113import java.util.Set;
114import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800115import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import java.util.zip.ZipFile;
117import java.util.zip.ZipOutputStream;
118
119class PackageManagerService extends IPackageManager.Stub {
120 private static final String TAG = "PackageManager";
121 private static final boolean DEBUG_SETTINGS = false;
122 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800123 private static final boolean DEBUG_UPGRADE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
125 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
126 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400127 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 private static final int FIRST_APPLICATION_UID =
129 Process.FIRST_APPLICATION_UID;
130 private static final int MAX_APPLICATION_UIDS = 1000;
131
132 private static final boolean SHOW_INFO = false;
133
134 private static final boolean GET_CERTIFICATES = true;
135
Oscar Montemayora8529f62009-11-18 10:14:20 -0800136 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 private static final int REMOVE_EVENTS =
139 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
140 private static final int ADD_EVENTS =
141 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
142
143 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
144
145 static final int SCAN_MONITOR = 1<<0;
146 static final int SCAN_NO_DEX = 1<<1;
147 static final int SCAN_FORCE_DEX = 1<<2;
148 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800149 static final int SCAN_NEW_INSTALL = 1<<4;
150 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800152 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
153 "com.android.defcontainer",
154 "com.android.defcontainer.DefaultContainerService");
155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
157 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700158 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn851a5412009-05-08 12:06:44 -0700160 final int mSdkVersion = Build.VERSION.SDK_INT;
161 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
162 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 final Context mContext;
165 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700166 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 final DisplayMetrics mMetrics;
168 final int mDefParseFlags;
169 final String[] mSeparateProcesses;
170
171 // This is where all application persistent data goes.
172 final File mAppDataDir;
173
Oscar Montemayora8529f62009-11-18 10:14:20 -0800174 // If Encrypted File System feature is enabled, all application persistent data
175 // should go here instead.
176 final File mSecureAppDataDir;
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 // This is the object monitoring the framework dir.
179 final FileObserver mFrameworkInstallObserver;
180
181 // This is the object monitoring the system app dir.
182 final FileObserver mSystemInstallObserver;
183
184 // This is the object monitoring mAppInstallDir.
185 final FileObserver mAppInstallObserver;
186
187 // This is the object monitoring mDrmAppPrivateInstallDir.
188 final FileObserver mDrmAppInstallObserver;
189
190 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
191 // LOCK HELD. Can be called with mInstallLock held.
192 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 final File mFrameworkDir;
195 final File mSystemAppDir;
196 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700197 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
199 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
200 // apps.
201 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // Lock for state used when installing and doing other long running
206 // operations. Methods that must be called with this lock held have
207 // the prefix "LI".
208 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 // These are the directories in the 3rd party applications installed dir
211 // that we have currently loaded packages from. Keys are the application's
212 // installed zip file (absolute codePath), and values are Package.
213 final HashMap<String, PackageParser.Package> mAppDirs =
214 new HashMap<String, PackageParser.Package>();
215
216 // Information for the parser to write more useful error messages.
217 File mScanningPath;
218 int mLastScanError;
219
220 final int[] mOutPermissions = new int[3];
221
222 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 // Keys are String (package name), values are Package. This also serves
225 // as the lock for the global state. Methods that must be called with
226 // this lock held have the prefix "LP".
227 final HashMap<String, PackageParser.Package> mPackages =
228 new HashMap<String, PackageParser.Package>();
229
230 final Settings mSettings;
231 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
234 int[] mGlobalGids;
235
236 // These are the built-in uid -> permission mappings that were read from the
237 // etc/permissions.xml file.
238 final SparseArray<HashSet<String>> mSystemPermissions =
239 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 // These are the built-in shared libraries that were read from the
242 // etc/permissions.xml file.
243 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800244
Dianne Hackborn49237342009-08-27 20:08:01 -0700245 // Temporary for building the final shared libraries for an .apk.
246 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
Dianne Hackborn49237342009-08-27 20:08:01 -0700248 // These are the features this devices supports that were read from the
249 // etc/permissions.xml file.
250 final HashMap<String, FeatureInfo> mAvailableFeatures =
251 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // All available activities, for your resolving pleasure.
254 final ActivityIntentResolver mActivities =
255 new ActivityIntentResolver();
256
257 // All available receivers, for your resolving pleasure.
258 final ActivityIntentResolver mReceivers =
259 new ActivityIntentResolver();
260
261 // All available services, for your resolving pleasure.
262 final ServiceIntentResolver mServices = new ServiceIntentResolver();
263
264 // Keys are String (provider class name), values are Provider.
265 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
266 new HashMap<ComponentName, PackageParser.Provider>();
267
268 // Mapping from provider base names (first directory in content URI codePath)
269 // to the provider information.
270 final HashMap<String, PackageParser.Provider> mProviders =
271 new HashMap<String, PackageParser.Provider>();
272
273 // Mapping from instrumentation class names to info about them.
274 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
275 new HashMap<ComponentName, PackageParser.Instrumentation>();
276
277 // Mapping from permission names to info about them.
278 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
279 new HashMap<String, PackageParser.PermissionGroup>();
280
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800281 // Packages whose data we have transfered into another package, thus
282 // should no longer exist.
283 final HashSet<String> mTransferedPackages = new HashSet<String>();
284
Dianne Hackborn854060af2009-07-09 18:14:31 -0700285 // Broadcast actions that are only available to the system.
286 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 boolean mSystemReady;
289 boolean mSafeMode;
290 boolean mHasSystemUidErrors;
291
292 ApplicationInfo mAndroidApplication;
293 final ActivityInfo mResolveActivity = new ActivityInfo();
294 final ResolveInfo mResolveInfo = new ResolveInfo();
295 ComponentName mResolveComponentName;
296 PackageParser.Package mPlatformPackage;
297
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700298 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800299 final HashMap<String, ArrayList<String>> mPendingBroadcasts
300 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700301 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800302 static final int MCS_BOUND = 3;
303 static final int END_COPY = 4;
304 static final int INIT_COPY = 5;
305 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800306 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700307 // Delay time in millisecs
308 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800309 private ServiceConnection mDefContainerConn = new ServiceConnection() {
310 public void onServiceConnected(ComponentName name, IBinder service) {
311 IMediaContainerService imcs =
312 IMediaContainerService.Stub.asInterface(service);
313 Message msg = mHandler.obtainMessage(MCS_BOUND, imcs);
314 mHandler.sendMessage(msg);
315 }
316
317 public void onServiceDisconnected(ComponentName name) {
318 }
319 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700320
321 class PackageHandler extends Handler {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800322 final ArrayList<InstallArgs> mPendingInstalls =
323 new ArrayList<InstallArgs>();
324 // Service Connection to remote media container service to copy
325 // package uri's from external media onto secure containers
326 // or internal storage.
327 private IMediaContainerService mContainerService = null;
328
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700329 PackageHandler(Looper looper) {
330 super(looper);
331 }
332 public void handleMessage(Message msg) {
333 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800334 case INIT_COPY: {
335 InstallArgs args = (InstallArgs) msg.obj;
336 args.createCopyFile();
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800337 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800338 if (mContainerService != null) {
339 // No need to add to pending list. Use remote stub directly
340 handleStartCopy(args);
341 } else {
342 if (mContext.bindService(service, mDefContainerConn,
343 Context.BIND_AUTO_CREATE)) {
344 mPendingInstalls.add(args);
345 } else {
346 Log.e(TAG, "Failed to bind to media container service");
347 // Indicate install failure TODO add new error code
348 processPendingInstall(args,
349 PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800350 }
351 }
352 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 }
354 case MCS_BOUND: {
355 // Initialize mContainerService if needed.
356 if (msg.obj != null) {
357 mContainerService = (IMediaContainerService) msg.obj;
358 }
359 if (mPendingInstalls.size() > 0) {
360 InstallArgs args = mPendingInstalls.remove(0);
361 if (args != null) {
362 handleStartCopy(args);
363 }
364 }
365 break;
366 }
367 case MCS_UNBIND : {
368 if (mPendingInstalls.size() == 0) {
369 mContext.unbindService(mDefContainerConn);
370 mContainerService = null;
371 }
372 break;
373 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800375 String packages[];
376 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700377 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378 int uids[];
379 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800380 if (mPendingBroadcasts == null) {
381 return;
382 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700383 size = mPendingBroadcasts.size();
384 if (size <= 0) {
385 // Nothing to be done. Just return
386 return;
387 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800388 packages = new String[size];
389 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700390 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800391 Iterator<HashMap.Entry<String, ArrayList<String>>>
392 it = mPendingBroadcasts.entrySet().iterator();
393 int i = 0;
394 while (it.hasNext() && i < size) {
395 HashMap.Entry<String, ArrayList<String>> ent = it.next();
396 packages[i] = ent.getKey();
397 components[i] = ent.getValue();
398 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700399 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800400 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800402 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700403 mPendingBroadcasts.clear();
404 }
405 // Send broadcasts
406 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800407 sendPackageChangedBroadcast(packages[i], true,
408 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700409 }
410 break;
411 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800412 case START_CLEANING_PACKAGE: {
413 String packageName = (String)msg.obj;
414 synchronized (mPackages) {
415 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
416 mSettings.mPackagesToBeCleaned.add(packageName);
417 }
418 }
419 startCleaningPackages();
420 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 }
422 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800423
424 // Utility method to initiate copying apk via media
425 // container service.
426 private void handleStartCopy(InstallArgs args) {
427 int ret = PackageManager.INSTALL_SUCCEEDED;
428 if (mContainerService == null) {
429 // Install error
430 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
431 } else {
432 ret = args.copyApk(mContainerService);
433 }
434 mHandler.sendEmptyMessage(MCS_UNBIND);
435 processPendingInstall(args, ret);
436 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700437 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800438
439 static boolean installOnSd(int flags) {
440 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
441 ((flags & PackageManager.INSTALL_ON_SDCARD) == 0)) {
442 return false;
443 }
444 return true;
445 }
446
447 static boolean isFwdLocked(int flags) {
448 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
449 return true;
450 }
451 return false;
452 }
453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 public static final IPackageManager main(Context context, boolean factoryTest) {
455 PackageManagerService m = new PackageManagerService(context, factoryTest);
456 ServiceManager.addService("package", m);
457 return m;
458 }
459
460 static String[] splitString(String str, char sep) {
461 int count = 1;
462 int i = 0;
463 while ((i=str.indexOf(sep, i)) >= 0) {
464 count++;
465 i++;
466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 String[] res = new String[count];
469 i=0;
470 count = 0;
471 int lastI=0;
472 while ((i=str.indexOf(sep, i)) >= 0) {
473 res[count] = str.substring(lastI, i);
474 count++;
475 i++;
476 lastI = i;
477 }
478 res[count] = str.substring(lastI, str.length());
479 return res;
480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800482 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800483 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 if (mSdkVersion <= 0) {
487 Log.w(TAG, "**** ro.build.version.sdk not set!");
488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490 mContext = context;
491 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700492 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800493 mMetrics = new DisplayMetrics();
494 mSettings = new Settings();
495 mSettings.addSharedUserLP("android.uid.system",
496 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
497 mSettings.addSharedUserLP("android.uid.phone",
498 MULTIPLE_APPLICATION_UIDS
499 ? RADIO_UID : FIRST_APPLICATION_UID,
500 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400501 mSettings.addSharedUserLP("android.uid.log",
502 MULTIPLE_APPLICATION_UIDS
503 ? LOG_UID : FIRST_APPLICATION_UID,
504 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505
506 String separateProcesses = SystemProperties.get("debug.separate_processes");
507 if (separateProcesses != null && separateProcesses.length() > 0) {
508 if ("*".equals(separateProcesses)) {
509 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
510 mSeparateProcesses = null;
511 Log.w(TAG, "Running with debug.separate_processes: * (ALL)");
512 } else {
513 mDefParseFlags = 0;
514 mSeparateProcesses = separateProcesses.split(",");
515 Log.w(TAG, "Running with debug.separate_processes: "
516 + separateProcesses);
517 }
518 } else {
519 mDefParseFlags = 0;
520 mSeparateProcesses = null;
521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 Installer installer = new Installer();
524 // Little hacky thing to check if installd is here, to determine
525 // whether we are running on the simulator and thus need to take
526 // care of building the /data file structure ourself.
527 // (apparently the sim now has a working installer)
528 if (installer.ping() && Process.supportsProcesses()) {
529 mInstaller = installer;
530 } else {
531 mInstaller = null;
532 }
533
534 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
535 Display d = wm.getDefaultDisplay();
536 d.getMetrics(mMetrics);
537
538 synchronized (mInstallLock) {
539 synchronized (mPackages) {
540 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 File dataDir = Environment.getDataDirectory();
544 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800545 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
547
548 if (mInstaller == null) {
549 // Make sure these dirs exist, when we are running in
550 // the simulator.
551 // Make a wide-open directory for random misc stuff.
552 File miscDir = new File(dataDir, "misc");
553 miscDir.mkdirs();
554 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800555 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 mDrmAppPrivateInstallDir.mkdirs();
557 }
558
559 readPermissions();
560
561 mRestoredSettings = mSettings.readLP();
562 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800563
564 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800566
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800567 // Set flag to monitor and not change apk file paths when
568 // scanning install directories.
569 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700570 if (mNoDexOpt) {
571 Log.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800572 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700578 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700581 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 /**
584 * Out of paranoia, ensure that everything in the boot class
585 * path has been dexed.
586 */
587 String bootClassPath = System.getProperty("java.boot.class.path");
588 if (bootClassPath != null) {
589 String[] paths = splitString(bootClassPath, ':');
590 for (int i=0; i<paths.length; i++) {
591 try {
592 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
593 libFiles.add(paths[i]);
594 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700595 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 }
597 } catch (FileNotFoundException e) {
598 Log.w(TAG, "Boot class path not found: " + paths[i]);
599 } catch (IOException e) {
600 Log.w(TAG, "Exception reading boot class path: " + paths[i], e);
601 }
602 }
603 } else {
604 Log.w(TAG, "No BOOTCLASSPATH found!");
605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 /**
608 * Also ensure all external libraries have had dexopt run on them.
609 */
610 if (mSharedLibraries.size() > 0) {
611 Iterator<String> libs = mSharedLibraries.values().iterator();
612 while (libs.hasNext()) {
613 String lib = libs.next();
614 try {
615 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
616 libFiles.add(lib);
617 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700618 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
620 } catch (FileNotFoundException e) {
621 Log.w(TAG, "Library not found: " + lib);
622 } catch (IOException e) {
623 Log.w(TAG, "Exception reading library: " + lib, e);
624 }
625 }
626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 // Gross hack for now: we know this file doesn't contain any
629 // code, so don't dexopt it to avoid the resulting log spew.
630 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 /**
633 * And there are a number of commands implemented in Java, which
634 * we currently need to do the dexopt on so that they can be
635 * run from a non-root shell.
636 */
637 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700638 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 for (int i=0; i<frameworkFiles.length; i++) {
640 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
641 String path = libPath.getPath();
642 // Skip the file if we alrady did it.
643 if (libFiles.contains(path)) {
644 continue;
645 }
646 // Skip the file if it is not a type we want to dexopt.
647 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
648 continue;
649 }
650 try {
651 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
652 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700653 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 }
655 } catch (FileNotFoundException e) {
656 Log.w(TAG, "Jar not found: " + path);
657 } catch (IOException e) {
658 Log.w(TAG, "Exception reading jar: " + path, e);
659 }
660 }
661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800662
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700663 if (didDexOpt) {
664 // If we had to do a dexopt of one of the previous
665 // things, then something on the system has changed.
666 // Consider this significant, and wipe away all other
667 // existing dexopt files to ensure we don't leave any
668 // dangling around.
669 String[] files = mDalvikCacheDir.list();
670 if (files != null) {
671 for (int i=0; i<files.length; i++) {
672 String fn = files[i];
673 if (fn.startsWith("data@app@")
674 || fn.startsWith("data@app-private@")) {
675 Log.i(TAG, "Pruning dalvik file: " + fn);
676 (new File(mDalvikCacheDir, fn)).delete();
677 }
678 }
679 }
680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800682
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800683 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 mFrameworkInstallObserver = new AppDirObserver(
685 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
686 mFrameworkInstallObserver.startWatching();
687 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800688 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800689
690 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
692 mSystemInstallObserver = new AppDirObserver(
693 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
694 mSystemInstallObserver.startWatching();
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800695 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800696
697 if (mInstaller != null) {
698 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
699 mInstaller.moveFiles();
700 }
701
702 // Prune any system packages that no longer exist.
703 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
704 while (psit.hasNext()) {
705 PackageSetting ps = psit.next();
706 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800707 && !mPackages.containsKey(ps.name)
708 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800709 psit.remove();
710 String msg = "System package " + ps.name
711 + " no longer exists; wiping its data";
712 reportSettingsProblem(Log.WARN, msg);
713 if (mInstaller != null) {
714 // XXX how to set useEncryptedFSDir for packages that
715 // are not encrypted?
716 mInstaller.remove(ps.name, true);
717 }
718 }
719 }
720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mAppInstallDir = new File(dataDir, "app");
722 if (mInstaller == null) {
723 // Make sure these dirs exist, when we are running in
724 // the simulator.
725 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
726 }
727 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800728 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 //clean up list
730 for(int i = 0; i < deletePkgsList.size(); i++) {
731 //clean up here
732 cleanupInstallFailedPackage(deletePkgsList.get(i));
733 }
734 //delete tmp files
735 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800736
737 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 SystemClock.uptimeMillis());
739 mAppInstallObserver = new AppDirObserver(
740 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
741 mAppInstallObserver.startWatching();
742 scanDirLI(mAppInstallDir, 0, scanMode);
743
744 mDrmAppInstallObserver = new AppDirObserver(
745 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
746 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800747 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800749 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 SystemClock.uptimeMillis());
751 Log.i(TAG, "Time to scan packages: "
752 + ((SystemClock.uptimeMillis()-startTime)/1000f)
753 + " seconds");
754
755 updatePermissionsLP();
756
757 mSettings.writeLP();
758
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800759 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 // Now after opening every single application zip, make sure they
763 // are all flushed. Not really needed, but keeps things nice and
764 // tidy.
765 Runtime.getRuntime().gc();
766 } // synchronized (mPackages)
767 } // synchronized (mInstallLock)
768 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -0700769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 @Override
771 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
772 throws RemoteException {
773 try {
774 return super.onTransact(code, data, reply, flags);
775 } catch (RuntimeException e) {
776 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
777 Log.e(TAG, "Package Manager Crash", e);
778 }
779 throw e;
780 }
781 }
782
Dianne Hackborne6620b22010-01-22 14:46:21 -0800783 void cleanupInstallFailedPackage(PackageSetting ps) {
784 Log.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -0800786 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
787 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 if (retCode < 0) {
789 Log.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -0800790 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792 } else {
793 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -0800794 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 File dataDir = new File(pkg.applicationInfo.dataDir);
796 dataDir.delete();
797 }
Dianne Hackborne6620b22010-01-22 14:46:21 -0800798 if (ps.codePath != null) {
799 if (!ps.codePath.delete()) {
800 Log.w(TAG, "Unable to remove old code file: " + ps.codePath);
801 }
802 }
803 if (ps.resourcePath != null) {
804 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
805 Log.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
806 }
807 }
808 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 }
810
811 void readPermissions() {
812 // Read permissions from .../etc/permission directory.
813 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
814 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
815 Log.w(TAG, "No directory " + libraryDir + ", skipping");
816 return;
817 }
818 if (!libraryDir.canRead()) {
819 Log.w(TAG, "Directory " + libraryDir + " cannot be read");
820 return;
821 }
822
823 // Iterate over the files in the directory and scan .xml files
824 for (File f : libraryDir.listFiles()) {
825 // We'll read platform.xml last
826 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
827 continue;
828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 if (!f.getPath().endsWith(".xml")) {
831 Log.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
832 continue;
833 }
834 if (!f.canRead()) {
835 Log.w(TAG, "Permissions library file " + f + " cannot be read");
836 continue;
837 }
838
839 readPermissionsFromXml(f);
840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
843 final File permFile = new File(Environment.getRootDirectory(),
844 "etc/permissions/platform.xml");
845 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800846
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700847 StringBuilder sb = new StringBuilder(128);
848 sb.append("Libs:");
849 Iterator<String> it = mSharedLibraries.keySet().iterator();
850 while (it.hasNext()) {
851 sb.append(' ');
852 String name = it.next();
853 sb.append(name);
854 sb.append(':');
855 sb.append(mSharedLibraries.get(name));
856 }
857 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700859 sb.setLength(0);
860 sb.append("Features:");
861 it = mAvailableFeatures.keySet().iterator();
862 while (it.hasNext()) {
863 sb.append(' ');
864 sb.append(it.next());
865 }
866 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800868
869 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 FileReader permReader = null;
871 try {
872 permReader = new FileReader(permFile);
873 } catch (FileNotFoundException e) {
874 Log.w(TAG, "Couldn't find or open permissions file " + permFile);
875 return;
876 }
877
878 try {
879 XmlPullParser parser = Xml.newPullParser();
880 parser.setInput(permReader);
881
882 XmlUtils.beginDocument(parser, "permissions");
883
884 while (true) {
885 XmlUtils.nextElement(parser);
886 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
887 break;
888 }
889
890 String name = parser.getName();
891 if ("group".equals(name)) {
892 String gidStr = parser.getAttributeValue(null, "gid");
893 if (gidStr != null) {
894 int gid = Integer.parseInt(gidStr);
895 mGlobalGids = appendInt(mGlobalGids, gid);
896 } else {
897 Log.w(TAG, "<group> without gid at "
898 + parser.getPositionDescription());
899 }
900
901 XmlUtils.skipCurrentTag(parser);
902 continue;
903 } else if ("permission".equals(name)) {
904 String perm = parser.getAttributeValue(null, "name");
905 if (perm == null) {
906 Log.w(TAG, "<permission> without name at "
907 + parser.getPositionDescription());
908 XmlUtils.skipCurrentTag(parser);
909 continue;
910 }
911 perm = perm.intern();
912 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 } else if ("assign-permission".equals(name)) {
915 String perm = parser.getAttributeValue(null, "name");
916 if (perm == null) {
917 Log.w(TAG, "<assign-permission> without name at "
918 + parser.getPositionDescription());
919 XmlUtils.skipCurrentTag(parser);
920 continue;
921 }
922 String uidStr = parser.getAttributeValue(null, "uid");
923 if (uidStr == null) {
924 Log.w(TAG, "<assign-permission> without uid at "
925 + parser.getPositionDescription());
926 XmlUtils.skipCurrentTag(parser);
927 continue;
928 }
929 int uid = Process.getUidForName(uidStr);
930 if (uid < 0) {
931 Log.w(TAG, "<assign-permission> with unknown uid \""
932 + uidStr + "\" at "
933 + parser.getPositionDescription());
934 XmlUtils.skipCurrentTag(parser);
935 continue;
936 }
937 perm = perm.intern();
938 HashSet<String> perms = mSystemPermissions.get(uid);
939 if (perms == null) {
940 perms = new HashSet<String>();
941 mSystemPermissions.put(uid, perms);
942 }
943 perms.add(perm);
944 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 } else if ("library".equals(name)) {
947 String lname = parser.getAttributeValue(null, "name");
948 String lfile = parser.getAttributeValue(null, "file");
949 if (lname == null) {
950 Log.w(TAG, "<library> without name at "
951 + parser.getPositionDescription());
952 } else if (lfile == null) {
953 Log.w(TAG, "<library> without file at "
954 + parser.getPositionDescription());
955 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700956 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -0700957 mSharedLibraries.put(lname, lfile);
958 }
959 XmlUtils.skipCurrentTag(parser);
960 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800961
Dianne Hackborn49237342009-08-27 20:08:01 -0700962 } else if ("feature".equals(name)) {
963 String fname = parser.getAttributeValue(null, "name");
964 if (fname == null) {
965 Log.w(TAG, "<feature> without name at "
966 + parser.getPositionDescription());
967 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700968 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -0700969 FeatureInfo fi = new FeatureInfo();
970 fi.name = fname;
971 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973 XmlUtils.skipCurrentTag(parser);
974 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 } else {
977 XmlUtils.skipCurrentTag(parser);
978 continue;
979 }
980
981 }
982 } catch (XmlPullParserException e) {
983 Log.w(TAG, "Got execption parsing permissions.", e);
984 } catch (IOException e) {
985 Log.w(TAG, "Got execption parsing permissions.", e);
986 }
987 }
988
989 void readPermission(XmlPullParser parser, String name)
990 throws IOException, XmlPullParserException {
991
992 name = name.intern();
993
994 BasePermission bp = mSettings.mPermissions.get(name);
995 if (bp == null) {
996 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
997 mSettings.mPermissions.put(name, bp);
998 }
999 int outerDepth = parser.getDepth();
1000 int type;
1001 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1002 && (type != XmlPullParser.END_TAG
1003 || parser.getDepth() > outerDepth)) {
1004 if (type == XmlPullParser.END_TAG
1005 || type == XmlPullParser.TEXT) {
1006 continue;
1007 }
1008
1009 String tagName = parser.getName();
1010 if ("group".equals(tagName)) {
1011 String gidStr = parser.getAttributeValue(null, "gid");
1012 if (gidStr != null) {
1013 int gid = Process.getGidForName(gidStr);
1014 bp.gids = appendInt(bp.gids, gid);
1015 } else {
1016 Log.w(TAG, "<group> without gid at "
1017 + parser.getPositionDescription());
1018 }
1019 }
1020 XmlUtils.skipCurrentTag(parser);
1021 }
1022 }
1023
1024 static int[] appendInt(int[] cur, int val) {
1025 if (cur == null) {
1026 return new int[] { val };
1027 }
1028 final int N = cur.length;
1029 for (int i=0; i<N; i++) {
1030 if (cur[i] == val) {
1031 return cur;
1032 }
1033 }
1034 int[] ret = new int[N+1];
1035 System.arraycopy(cur, 0, ret, 0, N);
1036 ret[N] = val;
1037 return ret;
1038 }
1039
1040 static int[] appendInts(int[] cur, int[] add) {
1041 if (add == null) return cur;
1042 if (cur == null) return add;
1043 final int N = add.length;
1044 for (int i=0; i<N; i++) {
1045 cur = appendInt(cur, add[i]);
1046 }
1047 return cur;
1048 }
1049
1050 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001051 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1052 // The package has been uninstalled but has retained data and resources.
1053 return PackageParser.generatePackageInfo(p, null, flags);
1054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 final PackageSetting ps = (PackageSetting)p.mExtras;
1056 if (ps == null) {
1057 return null;
1058 }
1059 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1060 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1061 }
1062
1063 public PackageInfo getPackageInfo(String packageName, int flags) {
1064 synchronized (mPackages) {
1065 PackageParser.Package p = mPackages.get(packageName);
1066 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001067 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 + ": " + p);
1069 if (p != null) {
1070 return generatePackageInfo(p, flags);
1071 }
1072 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1073 return generatePackageInfoFromSettingsLP(packageName, flags);
1074 }
1075 }
1076 return null;
1077 }
1078
Dianne Hackborn47096932010-02-11 15:57:09 -08001079 public String[] currentToCanonicalPackageNames(String[] names) {
1080 String[] out = new String[names.length];
1081 synchronized (mPackages) {
1082 for (int i=names.length-1; i>=0; i--) {
1083 PackageSetting ps = mSettings.mPackages.get(names[i]);
1084 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1085 }
1086 }
1087 return out;
1088 }
1089
1090 public String[] canonicalToCurrentPackageNames(String[] names) {
1091 String[] out = new String[names.length];
1092 synchronized (mPackages) {
1093 for (int i=names.length-1; i>=0; i--) {
1094 String cur = mSettings.mRenamedPackages.get(names[i]);
1095 out[i] = cur != null ? cur : names[i];
1096 }
1097 }
1098 return out;
1099 }
1100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 public int getPackageUid(String packageName) {
1102 synchronized (mPackages) {
1103 PackageParser.Package p = mPackages.get(packageName);
1104 if(p != null) {
1105 return p.applicationInfo.uid;
1106 }
1107 PackageSetting ps = mSettings.mPackages.get(packageName);
1108 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1109 return -1;
1110 }
1111 p = ps.pkg;
1112 return p != null ? p.applicationInfo.uid : -1;
1113 }
1114 }
1115
1116 public int[] getPackageGids(String packageName) {
1117 synchronized (mPackages) {
1118 PackageParser.Package p = mPackages.get(packageName);
1119 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001120 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 + ": " + p);
1122 if (p != null) {
1123 final PackageSetting ps = (PackageSetting)p.mExtras;
1124 final SharedUserSetting suid = ps.sharedUser;
1125 return suid != null ? suid.gids : ps.gids;
1126 }
1127 }
1128 // stupid thing to indicate an error.
1129 return new int[0];
1130 }
1131
1132 public PermissionInfo getPermissionInfo(String name, int flags) {
1133 synchronized (mPackages) {
1134 final BasePermission p = mSettings.mPermissions.get(name);
1135 if (p != null && p.perm != null) {
1136 return PackageParser.generatePermissionInfo(p.perm, flags);
1137 }
1138 return null;
1139 }
1140 }
1141
1142 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1143 synchronized (mPackages) {
1144 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1145 for (BasePermission p : mSettings.mPermissions.values()) {
1146 if (group == null) {
1147 if (p.perm.info.group == null) {
1148 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1149 }
1150 } else {
1151 if (group.equals(p.perm.info.group)) {
1152 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1153 }
1154 }
1155 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 if (out.size() > 0) {
1158 return out;
1159 }
1160 return mPermissionGroups.containsKey(group) ? out : null;
1161 }
1162 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1165 synchronized (mPackages) {
1166 return PackageParser.generatePermissionGroupInfo(
1167 mPermissionGroups.get(name), flags);
1168 }
1169 }
1170
1171 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1172 synchronized (mPackages) {
1173 final int N = mPermissionGroups.size();
1174 ArrayList<PermissionGroupInfo> out
1175 = new ArrayList<PermissionGroupInfo>(N);
1176 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1177 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1178 }
1179 return out;
1180 }
1181 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1184 PackageSetting ps = mSettings.mPackages.get(packageName);
1185 if(ps != null) {
1186 if(ps.pkg == null) {
1187 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1188 if(pInfo != null) {
1189 return pInfo.applicationInfo;
1190 }
1191 return null;
1192 }
1193 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1194 }
1195 return null;
1196 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1199 PackageSetting ps = mSettings.mPackages.get(packageName);
1200 if(ps != null) {
1201 if(ps.pkg == null) {
1202 ps.pkg = new PackageParser.Package(packageName);
1203 ps.pkg.applicationInfo.packageName = packageName;
1204 }
1205 return generatePackageInfo(ps.pkg, flags);
1206 }
1207 return null;
1208 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1211 synchronized (mPackages) {
1212 PackageParser.Package p = mPackages.get(packageName);
1213 if (Config.LOGV) Log.v(
1214 TAG, "getApplicationInfo " + packageName
1215 + ": " + p);
1216 if (p != null) {
1217 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001218 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
1220 if ("android".equals(packageName)||"system".equals(packageName)) {
1221 return mAndroidApplication;
1222 }
1223 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1224 return generateApplicationInfoFromSettingsLP(packageName, flags);
1225 }
1226 }
1227 return null;
1228 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001229
1230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1232 mContext.enforceCallingOrSelfPermission(
1233 android.Manifest.permission.CLEAR_APP_CACHE, null);
1234 // Queue up an async operation since clearing cache may take a little while.
1235 mHandler.post(new Runnable() {
1236 public void run() {
1237 mHandler.removeCallbacks(this);
1238 int retCode = -1;
1239 if (mInstaller != null) {
1240 retCode = mInstaller.freeCache(freeStorageSize);
1241 if (retCode < 0) {
1242 Log.w(TAG, "Couldn't clear application caches");
1243 }
1244 } //end if mInstaller
1245 if (observer != null) {
1246 try {
1247 observer.onRemoveCompleted(null, (retCode >= 0));
1248 } catch (RemoteException e) {
1249 Log.w(TAG, "RemoveException when invoking call back");
1250 }
1251 }
1252 }
1253 });
1254 }
1255
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001256 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001257 mContext.enforceCallingOrSelfPermission(
1258 android.Manifest.permission.CLEAR_APP_CACHE, null);
1259 // Queue up an async operation since clearing cache may take a little while.
1260 mHandler.post(new Runnable() {
1261 public void run() {
1262 mHandler.removeCallbacks(this);
1263 int retCode = -1;
1264 if (mInstaller != null) {
1265 retCode = mInstaller.freeCache(freeStorageSize);
1266 if (retCode < 0) {
1267 Log.w(TAG, "Couldn't clear application caches");
1268 }
1269 }
1270 if(pi != null) {
1271 try {
1272 // Callback via pending intent
1273 int code = (retCode >= 0) ? 1 : 0;
1274 pi.sendIntent(null, code, null,
1275 null, null);
1276 } catch (SendIntentException e1) {
1277 Log.i(TAG, "Failed to send pending intent");
1278 }
1279 }
1280 }
1281 });
1282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1285 synchronized (mPackages) {
1286 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001287
1288 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001290 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292 if (mResolveComponentName.equals(component)) {
1293 return mResolveActivity;
1294 }
1295 }
1296 return null;
1297 }
1298
1299 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1300 synchronized (mPackages) {
1301 PackageParser.Activity a = mReceivers.mActivities.get(component);
1302 if (Config.LOGV) Log.v(
1303 TAG, "getReceiverInfo " + component + ": " + a);
1304 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1305 return PackageParser.generateActivityInfo(a, flags);
1306 }
1307 }
1308 return null;
1309 }
1310
1311 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1312 synchronized (mPackages) {
1313 PackageParser.Service s = mServices.mServices.get(component);
1314 if (Config.LOGV) Log.v(
1315 TAG, "getServiceInfo " + component + ": " + s);
1316 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1317 return PackageParser.generateServiceInfo(s, flags);
1318 }
1319 }
1320 return null;
1321 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 public String[] getSystemSharedLibraryNames() {
1324 Set<String> libSet;
1325 synchronized (mPackages) {
1326 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001327 int size = libSet.size();
1328 if (size > 0) {
1329 String[] libs = new String[size];
1330 libSet.toArray(libs);
1331 return libs;
1332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001334 return null;
1335 }
1336
1337 public FeatureInfo[] getSystemAvailableFeatures() {
1338 Collection<FeatureInfo> featSet;
1339 synchronized (mPackages) {
1340 featSet = mAvailableFeatures.values();
1341 int size = featSet.size();
1342 if (size > 0) {
1343 FeatureInfo[] features = new FeatureInfo[size+1];
1344 featSet.toArray(features);
1345 FeatureInfo fi = new FeatureInfo();
1346 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1347 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1348 features[size] = fi;
1349 return features;
1350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
1352 return null;
1353 }
1354
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001355 public boolean hasSystemFeature(String name) {
1356 synchronized (mPackages) {
1357 return mAvailableFeatures.containsKey(name);
1358 }
1359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 public int checkPermission(String permName, String pkgName) {
1362 synchronized (mPackages) {
1363 PackageParser.Package p = mPackages.get(pkgName);
1364 if (p != null && p.mExtras != null) {
1365 PackageSetting ps = (PackageSetting)p.mExtras;
1366 if (ps.sharedUser != null) {
1367 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1368 return PackageManager.PERMISSION_GRANTED;
1369 }
1370 } else if (ps.grantedPermissions.contains(permName)) {
1371 return PackageManager.PERMISSION_GRANTED;
1372 }
1373 }
1374 }
1375 return PackageManager.PERMISSION_DENIED;
1376 }
1377
1378 public int checkUidPermission(String permName, int uid) {
1379 synchronized (mPackages) {
1380 Object obj = mSettings.getUserIdLP(uid);
1381 if (obj != null) {
1382 if (obj instanceof SharedUserSetting) {
1383 SharedUserSetting sus = (SharedUserSetting)obj;
1384 if (sus.grantedPermissions.contains(permName)) {
1385 return PackageManager.PERMISSION_GRANTED;
1386 }
1387 } else if (obj instanceof PackageSetting) {
1388 PackageSetting ps = (PackageSetting)obj;
1389 if (ps.grantedPermissions.contains(permName)) {
1390 return PackageManager.PERMISSION_GRANTED;
1391 }
1392 }
1393 } else {
1394 HashSet<String> perms = mSystemPermissions.get(uid);
1395 if (perms != null && perms.contains(permName)) {
1396 return PackageManager.PERMISSION_GRANTED;
1397 }
1398 }
1399 }
1400 return PackageManager.PERMISSION_DENIED;
1401 }
1402
1403 private BasePermission findPermissionTreeLP(String permName) {
1404 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1405 if (permName.startsWith(bp.name) &&
1406 permName.length() > bp.name.length() &&
1407 permName.charAt(bp.name.length()) == '.') {
1408 return bp;
1409 }
1410 }
1411 return null;
1412 }
1413
1414 private BasePermission checkPermissionTreeLP(String permName) {
1415 if (permName != null) {
1416 BasePermission bp = findPermissionTreeLP(permName);
1417 if (bp != null) {
1418 if (bp.uid == Binder.getCallingUid()) {
1419 return bp;
1420 }
1421 throw new SecurityException("Calling uid "
1422 + Binder.getCallingUid()
1423 + " is not allowed to add to permission tree "
1424 + bp.name + " owned by uid " + bp.uid);
1425 }
1426 }
1427 throw new SecurityException("No permission tree found for " + permName);
1428 }
1429
1430 public boolean addPermission(PermissionInfo info) {
1431 synchronized (mPackages) {
1432 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1433 throw new SecurityException("Label must be specified in permission");
1434 }
1435 BasePermission tree = checkPermissionTreeLP(info.name);
1436 BasePermission bp = mSettings.mPermissions.get(info.name);
1437 boolean added = bp == null;
1438 if (added) {
1439 bp = new BasePermission(info.name, tree.sourcePackage,
1440 BasePermission.TYPE_DYNAMIC);
1441 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1442 throw new SecurityException(
1443 "Not allowed to modify non-dynamic permission "
1444 + info.name);
1445 }
1446 bp.perm = new PackageParser.Permission(tree.perm.owner,
1447 new PermissionInfo(info));
1448 bp.perm.info.packageName = tree.perm.info.packageName;
1449 bp.uid = tree.uid;
1450 if (added) {
1451 mSettings.mPermissions.put(info.name, bp);
1452 }
1453 mSettings.writeLP();
1454 return added;
1455 }
1456 }
1457
1458 public void removePermission(String name) {
1459 synchronized (mPackages) {
1460 checkPermissionTreeLP(name);
1461 BasePermission bp = mSettings.mPermissions.get(name);
1462 if (bp != null) {
1463 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1464 throw new SecurityException(
1465 "Not allowed to modify non-dynamic permission "
1466 + name);
1467 }
1468 mSettings.mPermissions.remove(name);
1469 mSettings.writeLP();
1470 }
1471 }
1472 }
1473
Dianne Hackborn854060af2009-07-09 18:14:31 -07001474 public boolean isProtectedBroadcast(String actionName) {
1475 synchronized (mPackages) {
1476 return mProtectedBroadcasts.contains(actionName);
1477 }
1478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 public int checkSignatures(String pkg1, String pkg2) {
1481 synchronized (mPackages) {
1482 PackageParser.Package p1 = mPackages.get(pkg1);
1483 PackageParser.Package p2 = mPackages.get(pkg2);
1484 if (p1 == null || p1.mExtras == null
1485 || p2 == null || p2.mExtras == null) {
1486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1487 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001488 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 }
1491
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001492 public int checkUidSignatures(int uid1, int uid2) {
1493 synchronized (mPackages) {
1494 Signature[] s1;
1495 Signature[] s2;
1496 Object obj = mSettings.getUserIdLP(uid1);
1497 if (obj != null) {
1498 if (obj instanceof SharedUserSetting) {
1499 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1500 } else if (obj instanceof PackageSetting) {
1501 s1 = ((PackageSetting)obj).signatures.mSignatures;
1502 } else {
1503 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1504 }
1505 } else {
1506 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1507 }
1508 obj = mSettings.getUserIdLP(uid2);
1509 if (obj != null) {
1510 if (obj instanceof SharedUserSetting) {
1511 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1512 } else if (obj instanceof PackageSetting) {
1513 s2 = ((PackageSetting)obj).signatures.mSignatures;
1514 } else {
1515 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1516 }
1517 } else {
1518 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1519 }
1520 return checkSignaturesLP(s1, s2);
1521 }
1522 }
1523
1524 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1525 if (s1 == null) {
1526 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1528 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1529 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001530 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1532 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001533 final int N1 = s1.length;
1534 final int N2 = s2.length;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 for (int i=0; i<N1; i++) {
1536 boolean match = false;
1537 for (int j=0; j<N2; j++) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001538 if (s1[i].equals(s2[j])) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 match = true;
1540 break;
1541 }
1542 }
1543 if (!match) {
1544 return PackageManager.SIGNATURE_NO_MATCH;
1545 }
1546 }
1547 return PackageManager.SIGNATURE_MATCH;
1548 }
1549
1550 public String[] getPackagesForUid(int uid) {
1551 synchronized (mPackages) {
1552 Object obj = mSettings.getUserIdLP(uid);
1553 if (obj instanceof SharedUserSetting) {
1554 SharedUserSetting sus = (SharedUserSetting)obj;
1555 final int N = sus.packages.size();
1556 String[] res = new String[N];
1557 Iterator<PackageSetting> it = sus.packages.iterator();
1558 int i=0;
1559 while (it.hasNext()) {
1560 res[i++] = it.next().name;
1561 }
1562 return res;
1563 } else if (obj instanceof PackageSetting) {
1564 PackageSetting ps = (PackageSetting)obj;
1565 return new String[] { ps.name };
1566 }
1567 }
1568 return null;
1569 }
1570
1571 public String getNameForUid(int uid) {
1572 synchronized (mPackages) {
1573 Object obj = mSettings.getUserIdLP(uid);
1574 if (obj instanceof SharedUserSetting) {
1575 SharedUserSetting sus = (SharedUserSetting)obj;
1576 return sus.name + ":" + sus.userId;
1577 } else if (obj instanceof PackageSetting) {
1578 PackageSetting ps = (PackageSetting)obj;
1579 return ps.name;
1580 }
1581 }
1582 return null;
1583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 public int getUidForSharedUser(String sharedUserName) {
1586 if(sharedUserName == null) {
1587 return -1;
1588 }
1589 synchronized (mPackages) {
1590 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1591 if(suid == null) {
1592 return -1;
1593 }
1594 return suid.userId;
1595 }
1596 }
1597
1598 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1599 int flags) {
1600 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001601 return chooseBestActivity(intent, resolvedType, flags, query);
1602 }
1603
Mihai Predaeae850c2009-05-13 10:13:48 +02001604 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1605 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 if (query != null) {
1607 final int N = query.size();
1608 if (N == 1) {
1609 return query.get(0);
1610 } else if (N > 1) {
1611 // If there is more than one activity with the same priority,
1612 // then let the user decide between them.
1613 ResolveInfo r0 = query.get(0);
1614 ResolveInfo r1 = query.get(1);
1615 if (false) {
1616 System.out.println(r0.activityInfo.name +
1617 "=" + r0.priority + " vs " +
1618 r1.activityInfo.name +
1619 "=" + r1.priority);
1620 }
1621 // If the first activity has a higher priority, or a different
1622 // default, then it is always desireable to pick it.
1623 if (r0.priority != r1.priority
1624 || r0.preferredOrder != r1.preferredOrder
1625 || r0.isDefault != r1.isDefault) {
1626 return query.get(0);
1627 }
1628 // If we have saved a preference for a preferred activity for
1629 // this Intent, use that.
1630 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1631 flags, query, r0.priority);
1632 if (ri != null) {
1633 return ri;
1634 }
1635 return mResolveInfo;
1636 }
1637 }
1638 return null;
1639 }
1640
1641 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1642 int flags, List<ResolveInfo> query, int priority) {
1643 synchronized (mPackages) {
1644 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1645 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001646 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1648 if (prefs != null && prefs.size() > 0) {
1649 // First figure out how good the original match set is.
1650 // We will only allow preferred activities that came
1651 // from the same match quality.
1652 int match = 0;
1653 final int N = query.size();
1654 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1655 for (int j=0; j<N; j++) {
1656 ResolveInfo ri = query.get(j);
1657 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1658 + ": 0x" + Integer.toHexString(match));
1659 if (ri.match > match) match = ri.match;
1660 }
1661 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
1662 + Integer.toHexString(match));
1663 match &= IntentFilter.MATCH_CATEGORY_MASK;
1664 final int M = prefs.size();
1665 for (int i=0; i<M; i++) {
1666 PreferredActivity pa = prefs.get(i);
1667 if (pa.mMatch != match) {
1668 continue;
1669 }
1670 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
1671 if (DEBUG_PREFERRED) {
1672 Log.v(TAG, "Got preferred activity:");
1673 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
1674 }
1675 if (ai != null) {
1676 for (int j=0; j<N; j++) {
1677 ResolveInfo ri = query.get(j);
1678 if (!ri.activityInfo.applicationInfo.packageName
1679 .equals(ai.applicationInfo.packageName)) {
1680 continue;
1681 }
1682 if (!ri.activityInfo.name.equals(ai.name)) {
1683 continue;
1684 }
1685
1686 // Okay we found a previously set preferred app.
1687 // If the result set is different from when this
1688 // was created, we need to clear it and re-ask the
1689 // user their preference.
1690 if (!pa.sameSet(query, priority)) {
1691 Log.i(TAG, "Result set changed, dropping preferred activity for "
1692 + intent + " type " + resolvedType);
1693 mSettings.mPreferredActivities.removeFilter(pa);
1694 return null;
1695 }
1696
1697 // Yay!
1698 return ri;
1699 }
1700 }
1701 }
1702 }
1703 }
1704 return null;
1705 }
1706
1707 public List<ResolveInfo> queryIntentActivities(Intent intent,
1708 String resolvedType, int flags) {
1709 ComponentName comp = intent.getComponent();
1710 if (comp != null) {
1711 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1712 ActivityInfo ai = getActivityInfo(comp, flags);
1713 if (ai != null) {
1714 ResolveInfo ri = new ResolveInfo();
1715 ri.activityInfo = ai;
1716 list.add(ri);
1717 }
1718 return list;
1719 }
1720
1721 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001722 String pkgName = intent.getPackage();
1723 if (pkgName == null) {
1724 return (List<ResolveInfo>)mActivities.queryIntent(intent,
1725 resolvedType, flags);
1726 }
1727 PackageParser.Package pkg = mPackages.get(pkgName);
1728 if (pkg != null) {
1729 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
1730 resolvedType, flags, pkg.activities);
1731 }
1732 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 }
1734 }
1735
1736 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1737 Intent[] specifics, String[] specificTypes, Intent intent,
1738 String resolvedType, int flags) {
1739 final String resultsAction = intent.getAction();
1740
1741 List<ResolveInfo> results = queryIntentActivities(
1742 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
1743 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
1744
1745 int specificsPos = 0;
1746 int N;
1747
1748 // todo: note that the algorithm used here is O(N^2). This
1749 // isn't a problem in our current environment, but if we start running
1750 // into situations where we have more than 5 or 10 matches then this
1751 // should probably be changed to something smarter...
1752
1753 // First we go through and resolve each of the specific items
1754 // that were supplied, taking care of removing any corresponding
1755 // duplicate items in the generic resolve list.
1756 if (specifics != null) {
1757 for (int i=0; i<specifics.length; i++) {
1758 final Intent sintent = specifics[i];
1759 if (sintent == null) {
1760 continue;
1761 }
1762
1763 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
1764 String action = sintent.getAction();
1765 if (resultsAction != null && resultsAction.equals(action)) {
1766 // If this action was explicitly requested, then don't
1767 // remove things that have it.
1768 action = null;
1769 }
1770 ComponentName comp = sintent.getComponent();
1771 ResolveInfo ri = null;
1772 ActivityInfo ai = null;
1773 if (comp == null) {
1774 ri = resolveIntent(
1775 sintent,
1776 specificTypes != null ? specificTypes[i] : null,
1777 flags);
1778 if (ri == null) {
1779 continue;
1780 }
1781 if (ri == mResolveInfo) {
1782 // ACK! Must do something better with this.
1783 }
1784 ai = ri.activityInfo;
1785 comp = new ComponentName(ai.applicationInfo.packageName,
1786 ai.name);
1787 } else {
1788 ai = getActivityInfo(comp, flags);
1789 if (ai == null) {
1790 continue;
1791 }
1792 }
1793
1794 // Look for any generic query activities that are duplicates
1795 // of this specific one, and remove them from the results.
1796 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
1797 N = results.size();
1798 int j;
1799 for (j=specificsPos; j<N; j++) {
1800 ResolveInfo sri = results.get(j);
1801 if ((sri.activityInfo.name.equals(comp.getClassName())
1802 && sri.activityInfo.applicationInfo.packageName.equals(
1803 comp.getPackageName()))
1804 || (action != null && sri.filter.matchAction(action))) {
1805 results.remove(j);
1806 if (Config.LOGV) Log.v(
1807 TAG, "Removing duplicate item from " + j
1808 + " due to specific " + specificsPos);
1809 if (ri == null) {
1810 ri = sri;
1811 }
1812 j--;
1813 N--;
1814 }
1815 }
1816
1817 // Add this specific item to its proper place.
1818 if (ri == null) {
1819 ri = new ResolveInfo();
1820 ri.activityInfo = ai;
1821 }
1822 results.add(specificsPos, ri);
1823 ri.specificIndex = i;
1824 specificsPos++;
1825 }
1826 }
1827
1828 // Now we go through the remaining generic results and remove any
1829 // duplicate actions that are found here.
1830 N = results.size();
1831 for (int i=specificsPos; i<N-1; i++) {
1832 final ResolveInfo rii = results.get(i);
1833 if (rii.filter == null) {
1834 continue;
1835 }
1836
1837 // Iterate over all of the actions of this result's intent
1838 // filter... typically this should be just one.
1839 final Iterator<String> it = rii.filter.actionsIterator();
1840 if (it == null) {
1841 continue;
1842 }
1843 while (it.hasNext()) {
1844 final String action = it.next();
1845 if (resultsAction != null && resultsAction.equals(action)) {
1846 // If this action was explicitly requested, then don't
1847 // remove things that have it.
1848 continue;
1849 }
1850 for (int j=i+1; j<N; j++) {
1851 final ResolveInfo rij = results.get(j);
1852 if (rij.filter != null && rij.filter.hasAction(action)) {
1853 results.remove(j);
1854 if (Config.LOGV) Log.v(
1855 TAG, "Removing duplicate item from " + j
1856 + " due to action " + action + " at " + i);
1857 j--;
1858 N--;
1859 }
1860 }
1861 }
1862
1863 // If the caller didn't request filter information, drop it now
1864 // so we don't have to marshall/unmarshall it.
1865 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1866 rii.filter = null;
1867 }
1868 }
1869
1870 // Filter out the caller activity if so requested.
1871 if (caller != null) {
1872 N = results.size();
1873 for (int i=0; i<N; i++) {
1874 ActivityInfo ainfo = results.get(i).activityInfo;
1875 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
1876 && caller.getClassName().equals(ainfo.name)) {
1877 results.remove(i);
1878 break;
1879 }
1880 }
1881 }
1882
1883 // If the caller didn't request filter information,
1884 // drop them now so we don't have to
1885 // marshall/unmarshall it.
1886 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
1887 N = results.size();
1888 for (int i=0; i<N; i++) {
1889 results.get(i).filter = null;
1890 }
1891 }
1892
1893 if (Config.LOGV) Log.v(TAG, "Result: " + results);
1894 return results;
1895 }
1896
1897 public List<ResolveInfo> queryIntentReceivers(Intent intent,
1898 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001899 ComponentName comp = intent.getComponent();
1900 if (comp != null) {
1901 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1902 ActivityInfo ai = getReceiverInfo(comp, flags);
1903 if (ai != null) {
1904 ResolveInfo ri = new ResolveInfo();
1905 ri.activityInfo = ai;
1906 list.add(ri);
1907 }
1908 return list;
1909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001912 String pkgName = intent.getPackage();
1913 if (pkgName == null) {
1914 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
1915 resolvedType, flags);
1916 }
1917 PackageParser.Package pkg = mPackages.get(pkgName);
1918 if (pkg != null) {
1919 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
1920 resolvedType, flags, pkg.receivers);
1921 }
1922 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 }
1924 }
1925
1926 public ResolveInfo resolveService(Intent intent, String resolvedType,
1927 int flags) {
1928 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
1929 flags);
1930 if (query != null) {
1931 if (query.size() >= 1) {
1932 // If there is more than one service with the same priority,
1933 // just arbitrarily pick the first one.
1934 return query.get(0);
1935 }
1936 }
1937 return null;
1938 }
1939
1940 public List<ResolveInfo> queryIntentServices(Intent intent,
1941 String resolvedType, int flags) {
1942 ComponentName comp = intent.getComponent();
1943 if (comp != null) {
1944 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
1945 ServiceInfo si = getServiceInfo(comp, flags);
1946 if (si != null) {
1947 ResolveInfo ri = new ResolveInfo();
1948 ri.serviceInfo = si;
1949 list.add(ri);
1950 }
1951 return list;
1952 }
1953
1954 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07001955 String pkgName = intent.getPackage();
1956 if (pkgName == null) {
1957 return (List<ResolveInfo>)mServices.queryIntent(intent,
1958 resolvedType, flags);
1959 }
1960 PackageParser.Package pkg = mPackages.get(pkgName);
1961 if (pkg != null) {
1962 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
1963 resolvedType, flags, pkg.services);
1964 }
1965 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 public List<PackageInfo> getInstalledPackages(int flags) {
1970 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
1971
1972 synchronized (mPackages) {
1973 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1974 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
1975 while (i.hasNext()) {
1976 final PackageSetting ps = i.next();
1977 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
1978 if(psPkg != null) {
1979 finalList.add(psPkg);
1980 }
1981 }
1982 }
1983 else {
1984 Iterator<PackageParser.Package> i = mPackages.values().iterator();
1985 while (i.hasNext()) {
1986 final PackageParser.Package p = i.next();
1987 if (p.applicationInfo != null) {
1988 PackageInfo pi = generatePackageInfo(p, flags);
1989 if(pi != null) {
1990 finalList.add(pi);
1991 }
1992 }
1993 }
1994 }
1995 }
1996 return finalList;
1997 }
1998
1999 public List<ApplicationInfo> getInstalledApplications(int flags) {
2000 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2001 synchronized(mPackages) {
2002 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2003 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2004 while (i.hasNext()) {
2005 final PackageSetting ps = i.next();
2006 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2007 if(ai != null) {
2008 finalList.add(ai);
2009 }
2010 }
2011 }
2012 else {
2013 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2014 while (i.hasNext()) {
2015 final PackageParser.Package p = i.next();
2016 if (p.applicationInfo != null) {
2017 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2018 if(ai != null) {
2019 finalList.add(ai);
2020 }
2021 }
2022 }
2023 }
2024 }
2025 return finalList;
2026 }
2027
2028 public List<ApplicationInfo> getPersistentApplications(int flags) {
2029 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2030
2031 synchronized (mPackages) {
2032 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2033 while (i.hasNext()) {
2034 PackageParser.Package p = i.next();
2035 if (p.applicationInfo != null
2036 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2037 && (!mSafeMode || (p.applicationInfo.flags
2038 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2039 finalList.add(p.applicationInfo);
2040 }
2041 }
2042 }
2043
2044 return finalList;
2045 }
2046
2047 public ProviderInfo resolveContentProvider(String name, int flags) {
2048 synchronized (mPackages) {
2049 final PackageParser.Provider provider = mProviders.get(name);
2050 return provider != null
2051 && mSettings.isEnabledLP(provider.info, flags)
2052 && (!mSafeMode || (provider.info.applicationInfo.flags
2053 &ApplicationInfo.FLAG_SYSTEM) != 0)
2054 ? PackageParser.generateProviderInfo(provider, flags)
2055 : null;
2056 }
2057 }
2058
Fred Quintana718d8a22009-04-29 17:53:20 -07002059 /**
2060 * @deprecated
2061 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 public void querySyncProviders(List outNames, List outInfo) {
2063 synchronized (mPackages) {
2064 Iterator<Map.Entry<String, PackageParser.Provider>> i
2065 = mProviders.entrySet().iterator();
2066
2067 while (i.hasNext()) {
2068 Map.Entry<String, PackageParser.Provider> entry = i.next();
2069 PackageParser.Provider p = entry.getValue();
2070
2071 if (p.syncable
2072 && (!mSafeMode || (p.info.applicationInfo.flags
2073 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2074 outNames.add(entry.getKey());
2075 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2076 }
2077 }
2078 }
2079 }
2080
2081 public List<ProviderInfo> queryContentProviders(String processName,
2082 int uid, int flags) {
2083 ArrayList<ProviderInfo> finalList = null;
2084
2085 synchronized (mPackages) {
2086 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2087 while (i.hasNext()) {
2088 PackageParser.Provider p = i.next();
2089 if (p.info.authority != null
2090 && (processName == null ||
2091 (p.info.processName.equals(processName)
2092 && p.info.applicationInfo.uid == uid))
2093 && mSettings.isEnabledLP(p.info, flags)
2094 && (!mSafeMode || (p.info.applicationInfo.flags
2095 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2096 if (finalList == null) {
2097 finalList = new ArrayList<ProviderInfo>(3);
2098 }
2099 finalList.add(PackageParser.generateProviderInfo(p,
2100 flags));
2101 }
2102 }
2103 }
2104
2105 if (finalList != null) {
2106 Collections.sort(finalList, mProviderInitOrderSorter);
2107 }
2108
2109 return finalList;
2110 }
2111
2112 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2113 int flags) {
2114 synchronized (mPackages) {
2115 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2116 return PackageParser.generateInstrumentationInfo(i, flags);
2117 }
2118 }
2119
2120 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2121 int flags) {
2122 ArrayList<InstrumentationInfo> finalList =
2123 new ArrayList<InstrumentationInfo>();
2124
2125 synchronized (mPackages) {
2126 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2127 while (i.hasNext()) {
2128 PackageParser.Instrumentation p = i.next();
2129 if (targetPackage == null
2130 || targetPackage.equals(p.info.targetPackage)) {
2131 finalList.add(PackageParser.generateInstrumentationInfo(p,
2132 flags));
2133 }
2134 }
2135 }
2136
2137 return finalList;
2138 }
2139
2140 private void scanDirLI(File dir, int flags, int scanMode) {
2141 Log.d(TAG, "Scanning app dir " + dir);
2142
2143 String[] files = dir.list();
2144
2145 int i;
2146 for (i=0; i<files.length; i++) {
2147 File file = new File(dir, files[i]);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002148 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002150 // Don't mess around with apps in system partition.
2151 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0) {
2152 // Delete the apk
2153 Log.w(TAG, "Cleaning up failed install of " + file);
2154 file.delete();
2155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157 }
2158
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002159 private static File getSettingsProblemFile() {
2160 File dataDir = Environment.getDataDirectory();
2161 File systemDir = new File(dataDir, "system");
2162 File fname = new File(systemDir, "uiderrors.txt");
2163 return fname;
2164 }
2165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 private static void reportSettingsProblem(int priority, String msg) {
2167 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002168 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 FileOutputStream out = new FileOutputStream(fname, true);
2170 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002171 SimpleDateFormat formatter = new SimpleDateFormat();
2172 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2173 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 pw.close();
2175 FileUtils.setPermissions(
2176 fname.toString(),
2177 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2178 -1, -1);
2179 } catch (java.io.IOException e) {
2180 }
2181 Log.println(priority, TAG, msg);
2182 }
2183
2184 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2185 PackageParser.Package pkg, File srcFile, int parseFlags) {
2186 if (GET_CERTIFICATES) {
2187 if (ps == null || !ps.codePath.equals(srcFile)
2188 || ps.getTimeStamp() != srcFile.lastModified()) {
2189 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2190 if (!pp.collectCertificates(pkg, parseFlags)) {
2191 mLastScanError = pp.getParseError();
2192 return false;
2193 }
2194 }
2195 }
2196 return true;
2197 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 /*
2200 * Scan a package and return the newly parsed package.
2201 * Returns null in case of errors and the error code is stored in mLastScanError
2202 */
2203 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002204 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002206 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002208 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002211 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 if (pkg == null) {
2213 mLastScanError = pp.getParseError();
2214 return null;
2215 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002216 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 PackageSetting updatedPkg;
2218 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002219 // Look to see if we already know about this package.
2220 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
2221 if (oldName != null && oldName.equals(pkg.mOriginalPackage)) {
2222 // This package has been renamed to its original name. Let's
2223 // use that.
2224 ps = mSettings.peekPackageLP(pkg.mOriginalPackage);
2225 }
2226 // If there was no original package, see one for the real package name.
2227 if (ps == null) {
2228 ps = mSettings.peekPackageLP(pkg.packageName);
2229 }
2230 // Check to see if this package could be hiding/updating a system
2231 // package. Must look for it either under the original or real
2232 // package name depending on our state.
2233 updatedPkg = mSettings.mDisabledSysPackages.get(
2234 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002236 // First check if this is a system package that may involve an update
2237 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2238 if (!ps.codePath.equals(scanFile)) {
2239 // The path has changed from what was last scanned... check the
2240 // version of the new path against what we have stored to determine
2241 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002242 if (pkg.mVersionCode < ps.versionCode) {
2243 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002244 // Ignore entry. Skip it.
2245 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2246 + "ignored: updated version " + ps.versionCode
2247 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002248 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2249 return null;
2250 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002251 // The current app on the system partion is better than
2252 // what we have updated to on the data partition; switch
2253 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002254 // At this point, its safely assumed that package installation for
2255 // apps in system partition will go through. If not there won't be a working
2256 // version of the app
2257 synchronized (mPackages) {
2258 // Just remove the loaded entries from package lists.
2259 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002260 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002261 Log.w(TAG, "Package " + ps.name + " at " + scanFile
2262 + "reverting from " + ps.codePathString
2263 + ": new version " + pkg.mVersionCode
2264 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002265 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2266 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002267 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002271 if (updatedPkg != null) {
2272 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2273 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2274 }
2275 // Verify certificates against what was last scanned
2276 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
2277 Log.i(TAG, "Failed verifying certificates for package:" + pkg.packageName);
2278 return null;
2279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 // The apk is forward locked (not public) if its code and resources
2281 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002282 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002284 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002285 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002286
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002287 String codePath = null;
2288 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002289 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2290 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002291 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002292 } else {
2293 // Should not happen at all. Just log an error.
2294 Log.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
2295 }
2296 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002297 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002298 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002299 codePath = pkg.mScanPath;
2300 // Set application objects path explicitly.
2301 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002302 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002303 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304 }
2305
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002306 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2307 String destCodePath, String destResPath) {
2308 pkg.mPath = pkg.mScanPath = destCodePath;
2309 pkg.applicationInfo.sourceDir = destCodePath;
2310 pkg.applicationInfo.publicSourceDir = destResPath;
2311 }
2312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002313 private static String fixProcessName(String defProcessName,
2314 String processName, int uid) {
2315 if (processName == null) {
2316 return defProcessName;
2317 }
2318 return processName;
2319 }
2320
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002321 private boolean verifySignaturesLP(PackageSetting pkgSetting,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 PackageParser.Package pkg, int parseFlags, boolean updateSignature) {
2323 if (pkg.mSignatures != null) {
2324 if (!pkgSetting.signatures.updateSignatures(pkg.mSignatures,
2325 updateSignature)) {
2326 Log.e(TAG, "Package " + pkg.packageName
2327 + " signatures do not match the previously installed version; ignoring!");
2328 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2329 return false;
2330 }
2331
2332 if (pkgSetting.sharedUser != null) {
2333 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2334 pkg.mSignatures, updateSignature)) {
2335 Log.e(TAG, "Package " + pkg.packageName
2336 + " has no signatures that match those in shared user "
2337 + pkgSetting.sharedUser.name + "; ignoring!");
2338 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2339 return false;
2340 }
2341 }
2342 } else {
2343 pkg.mSignatures = pkgSetting.signatures.mSignatures;
2344 }
2345 return true;
2346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002347
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002348 public boolean performDexOpt(String packageName) {
2349 if (!mNoDexOpt) {
2350 return false;
2351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002352
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002353 PackageParser.Package p;
2354 synchronized (mPackages) {
2355 p = mPackages.get(packageName);
2356 if (p == null || p.mDidDexOpt) {
2357 return false;
2358 }
2359 }
2360 synchronized (mInstallLock) {
2361 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2362 }
2363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002364
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002365 static final int DEX_OPT_SKIPPED = 0;
2366 static final int DEX_OPT_PERFORMED = 1;
2367 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002368
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002369 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2370 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002371 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002372 String path = pkg.mScanPath;
2373 int ret = 0;
2374 try {
2375 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002376 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002377 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002378 pkg.mDidDexOpt = true;
2379 performed = true;
2380 }
2381 } catch (FileNotFoundException e) {
2382 Log.w(TAG, "Apk not found for dexopt: " + path);
2383 ret = -1;
2384 } catch (IOException e) {
2385 Log.w(TAG, "Exception reading apk: " + path, e);
2386 ret = -1;
2387 }
2388 if (ret < 0) {
2389 //error from installer
2390 return DEX_OPT_FAILED;
2391 }
2392 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002393
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002394 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2395 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002396
2397 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2398 return Environment.isEncryptedFilesystemEnabled() &&
2399 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2400 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002401
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002402 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2403 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2404 Log.w(TAG, "Unable to update from " + oldPkg.name
2405 + " to " + newPkg.packageName
2406 + ": old package not in system partition");
2407 return false;
2408 } else if (mPackages.get(oldPkg.name) != null) {
2409 Log.w(TAG, "Unable to update from " + oldPkg.name
2410 + " to " + newPkg.packageName
2411 + ": old package still exists");
2412 return false;
2413 }
2414 return true;
2415 }
2416
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002417 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2418 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002419 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002420 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2421 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002422 // Bail out. The resource and code paths haven't been set.
2423 Log.w(TAG, " Code and resource paths haven't been set correctly");
2424 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2425 return null;
2426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 mScanningPath = scanFile;
2428 if (pkg == null) {
2429 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2430 return null;
2431 }
2432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2434 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2435 }
2436
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002437 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002438 synchronized (mPackages) {
2439 if (mAndroidApplication != null) {
2440 Log.w(TAG, "*************************************************");
2441 Log.w(TAG, "Core android package being redefined. Skipping.");
2442 Log.w(TAG, " file=" + mScanningPath);
2443 Log.w(TAG, "*************************************************");
2444 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2445 return null;
2446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 // Set up information for our fall-back user intent resolution
2449 // activity.
2450 mPlatformPackage = pkg;
2451 pkg.mVersionCode = mSdkVersion;
2452 mAndroidApplication = pkg.applicationInfo;
2453 mResolveActivity.applicationInfo = mAndroidApplication;
2454 mResolveActivity.name = ResolverActivity.class.getName();
2455 mResolveActivity.packageName = mAndroidApplication.packageName;
2456 mResolveActivity.processName = mAndroidApplication.processName;
2457 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2458 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2459 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2460 mResolveActivity.exported = true;
2461 mResolveActivity.enabled = true;
2462 mResolveInfo.activityInfo = mResolveActivity;
2463 mResolveInfo.priority = 0;
2464 mResolveInfo.preferredOrder = 0;
2465 mResolveInfo.match = 0;
2466 mResolveComponentName = new ComponentName(
2467 mAndroidApplication.packageName, mResolveActivity.name);
2468 }
2469 }
2470
2471 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002472 TAG, "Scanning package " + pkg.packageName);
2473 if (mPackages.containsKey(pkg.packageName)
2474 || mSharedLibraries.containsKey(pkg.packageName)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 Log.w(TAG, "*************************************************");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002476 Log.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 + " already installed. Skipping duplicate.");
2478 Log.w(TAG, "*************************************************");
2479 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2480 return null;
2481 }
2482
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002483 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002484 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2485 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 SharedUserSetting suid = null;
2488 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 boolean removeExisting = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002491
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002492 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2493 // Only system apps can use these features.
2494 pkg.mOriginalPackage = null;
2495 pkg.mRealPackage = null;
2496 pkg.mAdoptPermissions = null;
2497 }
2498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 synchronized (mPackages) {
2500 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002501 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2502 if (mTmpSharedLibraries == null ||
2503 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2504 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2505 }
2506 int num = 0;
2507 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2508 for (int i=0; i<N; i++) {
2509 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 if (file == null) {
2511 Log.e(TAG, "Package " + pkg.packageName
2512 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002513 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2515 return null;
2516 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002517 mTmpSharedLibraries[num] = file;
2518 num++;
2519 }
2520 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2521 for (int i=0; i<N; i++) {
2522 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2523 if (file == null) {
2524 Log.w(TAG, "Package " + pkg.packageName
2525 + " desires unavailable shared library "
2526 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2527 } else {
2528 mTmpSharedLibraries[num] = file;
2529 num++;
2530 }
2531 }
2532 if (num > 0) {
2533 pkg.usesLibraryFiles = new String[num];
2534 System.arraycopy(mTmpSharedLibraries, 0,
2535 pkg.usesLibraryFiles, 0, num);
2536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002537
Dianne Hackborn49237342009-08-27 20:08:01 -07002538 if (pkg.reqFeatures != null) {
2539 N = pkg.reqFeatures.size();
2540 for (int i=0; i<N; i++) {
2541 FeatureInfo fi = pkg.reqFeatures.get(i);
2542 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2543 // Don't care.
2544 continue;
2545 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002546
Dianne Hackborn49237342009-08-27 20:08:01 -07002547 if (fi.name != null) {
2548 if (mAvailableFeatures.get(fi.name) == null) {
2549 Log.e(TAG, "Package " + pkg.packageName
2550 + " requires unavailable feature "
2551 + fi.name + "; failing!");
2552 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2553 return null;
2554 }
2555 }
2556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 }
2558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 if (pkg.mSharedUserId != null) {
2561 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2562 pkg.applicationInfo.flags, true);
2563 if (suid == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002564 Log.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 + " for shared user failed");
2566 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2567 return null;
2568 }
2569 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2570 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2571 + suid.userId + "): packages=" + suid.packages);
2572 }
2573 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002574
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 if (false) {
2576 if (pkg.mOriginalPackage != null) {
2577 Log.w(TAG, "WAITING FOR DEBUGGER");
2578 Debug.waitForDebugger();
2579 Log.i(TAG, "Package " + pkg.packageName + " from original package"
2580 + pkg.mOriginalPackage);
2581 }
2582 }
2583
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002584 // Check if we are renaming from an original package name.
2585 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002586 String realName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002587 if (pkg.mOriginalPackage != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 // This package may need to be renamed to a previously
2589 // installed name. Let's check on that...
2590 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
2591 if (pkg.mOriginalPackage.equals(renamed)) {
2592 // This package had originally been installed as the
2593 // original name, and we have already taken care of
2594 // transitioning to the new one. Just update the new
2595 // one to continue using the old name.
2596 realName = pkg.mRealPackage;
2597 if (!pkg.packageName.equals(renamed)) {
2598 // Callers into this function may have already taken
2599 // care of renaming the package; only do it here if
2600 // it is not already done.
2601 pkg.setPackageName(renamed);
2602 }
2603
2604 } else if ((origPackage
2605 = mSettings.peekPackageLP(pkg.mOriginalPackage)) != null) {
2606 // We do have the package already installed under its
2607 // original name... should we use it?
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002608 if (!verifyPackageUpdate(origPackage, pkg)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002609 // New package is not compatible with original.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002610 origPackage = null;
2611 } else if (origPackage.sharedUser != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 // Make sure uid is compatible between packages.
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002613 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
2614 Log.w(TAG, "Unable to migrate data from " + origPackage.name
2615 + " to " + pkg.packageName + ": old uid "
2616 + origPackage.sharedUser.name
2617 + " differs from " + pkg.mSharedUserId);
2618 origPackage = null;
2619 }
2620 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2622 + pkg.packageName + " to old name " + origPackage.name);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002623 }
2624 }
2625 }
2626
2627 if (mTransferedPackages.contains(pkg.packageName)) {
2628 Log.w(TAG, "Package " + pkg.packageName
2629 + " was transferred to another, but its .apk remains");
2630 }
2631
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002632 // Just create the setting, don't add it yet. For already existing packages
2633 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 destResourceFile, pkg.applicationInfo.flags, true, false);
2636 if (pkgSetting == null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002637 Log.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2639 return null;
2640 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002641
2642 if (pkgSetting.origPackage != null) {
2643 // If we are first transitioning from an original package,
2644 // fix up the new package's name now. We need to do this after
2645 // looking up the package under its new name, so getPackageLP
2646 // can take care of fiddling things correctly.
2647 pkg.setPackageName(origPackage.name);
2648
2649 // File a report about this.
2650 String msg = "New package " + pkgSetting.realName
2651 + " renamed to replace old package " + pkgSetting.name;
2652 reportSettingsProblem(Log.WARN, msg);
2653
2654 // Make a note of it.
2655 mTransferedPackages.add(origPackage.name);
2656
2657 // No longer need to retain this.
2658 pkgSetting.origPackage = null;
2659 }
2660
2661 if (realName != null) {
2662 // Make a note of it.
2663 mTransferedPackages.add(pkg.packageName);
2664 }
2665
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002666 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
2668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 pkg.applicationInfo.uid = pkgSetting.userId;
2671 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002672
2673 if (!verifySignaturesLP(pkgSetting, pkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 (scanMode&SCAN_UPDATE_SIGNATURE) != 0)) {
2675 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) == 0) {
2676 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
2677 return null;
2678 }
2679 // The signature has changed, but this package is in the system
2680 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07002681 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 // However... if this package is part of a shared user, but it
2683 // doesn't match the signature of the shared user, let's fail.
2684 // What this means is that you can't change the signatures
2685 // associated with an overall shared user, which doesn't seem all
2686 // that unreasonable.
2687 if (pkgSetting.sharedUser != null) {
2688 if (!pkgSetting.sharedUser.signatures.mergeSignatures(
2689 pkg.mSignatures, false)) {
2690 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
2691 return null;
2692 }
2693 }
2694 removeExisting = true;
2695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002696
The Android Open Source Project10592532009-03-18 17:39:46 -07002697 // Verify that this new package doesn't have any content providers
2698 // that conflict with existing packages. Only do this if the
2699 // package isn't already installed, since we don't want to break
2700 // things that are installed.
2701 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
2702 int N = pkg.providers.size();
2703 int i;
2704 for (i=0; i<N; i++) {
2705 PackageParser.Provider p = pkg.providers.get(i);
2706 String names[] = p.info.authority.split(";");
2707 for (int j = 0; j < names.length; j++) {
2708 if (mProviders.containsKey(names[j])) {
2709 PackageParser.Provider other = mProviders.get(names[j]);
2710 Log.w(TAG, "Can't install because provider name " + names[j] +
2711 " (in package " + pkg.applicationInfo.packageName +
2712 ") is already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002713 + ((other != null && other.getComponentName() != null)
2714 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project10592532009-03-18 17:39:46 -07002715 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
2716 return null;
2717 }
2718 }
2719 }
2720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002723 final String pkgName = pkg.packageName;
2724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 if (removeExisting) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002726 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002728 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 if (ret != 0) {
2730 String msg = "System package " + pkg.packageName
2731 + " could not have data directory erased after signature change.";
2732 reportSettingsProblem(Log.WARN, msg);
2733 mLastScanError = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
2734 return null;
2735 }
2736 }
2737 Log.w(TAG, "System package " + pkg.packageName
2738 + " signature changed: existing data removed.");
2739 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
2740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002741
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002742 if (pkg.mAdoptPermissions != null) {
2743 // This package wants to adopt ownership of permissions from
2744 // another package.
2745 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
2746 String origName = pkg.mAdoptPermissions.get(i);
2747 PackageSetting orig = mSettings.peekPackageLP(origName);
2748 if (orig != null) {
2749 if (verifyPackageUpdate(orig, pkg)) {
2750 Log.i(TAG, "Adopting permissions from "
2751 + origName + " to " + pkg.packageName);
2752 mSettings.transferPermissions(origName, pkg.packageName);
2753 }
2754 }
2755 }
2756 }
2757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 long scanFileTime = scanFile.lastModified();
2759 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
2760 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
2761 pkg.applicationInfo.processName = fixProcessName(
2762 pkg.applicationInfo.packageName,
2763 pkg.applicationInfo.processName,
2764 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765
2766 File dataPath;
2767 if (mPlatformPackage == pkg) {
2768 // The system package is special.
2769 dataPath = new File (Environment.getDataDirectory(), "system");
2770 pkg.applicationInfo.dataDir = dataPath.getPath();
2771 } else {
2772 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002773 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2774 if (useEncryptedFSDir) {
2775 dataPath = new File(mSecureAppDataDir, pkgName);
2776 } else {
2777 dataPath = new File(mAppDataDir, pkgName);
2778 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002779
2780 boolean uidError = false;
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 if (dataPath.exists()) {
2783 mOutPermissions[1] = 0;
2784 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
2785 if (mOutPermissions[1] == pkg.applicationInfo.uid
2786 || !Process.supportsProcesses()) {
2787 pkg.applicationInfo.dataDir = dataPath.getPath();
2788 } else {
2789 boolean recovered = false;
2790 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2791 // If this is a system app, we can at least delete its
2792 // current data so the application will still work.
2793 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002794 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002795 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 // Old data gone!
2797 String msg = "System package " + pkg.packageName
2798 + " has changed from uid: "
2799 + mOutPermissions[1] + " to "
2800 + pkg.applicationInfo.uid + "; old data erased";
2801 reportSettingsProblem(Log.WARN, msg);
2802 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08002805 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 pkg.applicationInfo.uid);
2807 if (ret == -1) {
2808 // Ack should not happen!
2809 msg = "System package " + pkg.packageName
2810 + " could not have data directory re-created after delete.";
2811 reportSettingsProblem(Log.WARN, msg);
2812 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2813 return null;
2814 }
2815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 if (!recovered) {
2818 mHasSystemUidErrors = true;
2819 }
2820 }
2821 if (!recovered) {
2822 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
2823 + pkg.applicationInfo.uid + "/fs_"
2824 + mOutPermissions[1];
2825 String msg = "Package " + pkg.packageName
2826 + " has mismatched uid: "
2827 + mOutPermissions[1] + " on disk, "
2828 + pkg.applicationInfo.uid + " in settings";
2829 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002830 mSettings.mReadMessages.append(msg);
2831 mSettings.mReadMessages.append('\n');
2832 uidError = true;
2833 if (!pkgSetting.uidError) {
2834 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 }
2837 }
2838 }
2839 pkg.applicationInfo.dataDir = dataPath.getPath();
2840 } else {
2841 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
2842 Log.v(TAG, "Want this data dir: " + dataPath);
2843 //invoke installer to do the actual installation
2844 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08002845 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 pkg.applicationInfo.uid);
2847 if(ret < 0) {
2848 // Error from installer
2849 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2850 return null;
2851 }
2852 } else {
2853 dataPath.mkdirs();
2854 if (dataPath.exists()) {
2855 FileUtils.setPermissions(
2856 dataPath.toString(),
2857 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2858 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
2859 }
2860 }
2861 if (dataPath.exists()) {
2862 pkg.applicationInfo.dataDir = dataPath.getPath();
2863 } else {
2864 Log.w(TAG, "Unable to create data directory: " + dataPath);
2865 pkg.applicationInfo.dataDir = null;
2866 }
2867 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002868
2869 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 }
2871
2872 // Perform shared library installation and dex validation and
2873 // optimization, if this is not a system app.
2874 if (mInstaller != null) {
2875 String path = scanFile.getPath();
2876 if (scanFileNewer) {
2877 Log.i(TAG, path + " changed; unpacking");
Dianne Hackbornb1811182009-05-21 15:45:42 -07002878 int err = cachePackageSharedLibsLI(pkg, dataPath, scanFile);
2879 if (err != PackageManager.INSTALL_SUCCEEDED) {
2880 mLastScanError = err;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 return null;
2882 }
2883 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002884 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002885
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002886 if ((scanMode&SCAN_NO_DEX) == 0) {
2887 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
2889 return null;
2890 }
2891 }
2892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 if (mFactoryTest && pkg.requestedPermissions.contains(
2895 android.Manifest.permission.FACTORY_TEST)) {
2896 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
2897 }
2898
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002899 // We don't expect installation to fail beyond this point,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 if ((scanMode&SCAN_MONITOR) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 mAppDirs.put(pkg.mPath, pkg);
2902 }
2903
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002904 // Request the ActivityManager to kill the process(only for existing packages)
2905 // so that we do not end up in a confused state while the user is still using the older
2906 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002907 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002908 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002909 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07002910 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002914 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002916 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08002917 // Make sure we don't accidentally delete its data.
2918 mSettings.mPackagesToBeCleaned.remove(pkgName);
2919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 int N = pkg.providers.size();
2921 StringBuilder r = null;
2922 int i;
2923 for (i=0; i<N; i++) {
2924 PackageParser.Provider p = pkg.providers.get(i);
2925 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
2926 p.info.processName, pkg.applicationInfo.uid);
2927 mProvidersByComponent.put(new ComponentName(p.info.packageName,
2928 p.info.name), p);
2929 p.syncable = p.info.isSyncable;
2930 String names[] = p.info.authority.split(";");
2931 p.info.authority = null;
2932 for (int j = 0; j < names.length; j++) {
2933 if (j == 1 && p.syncable) {
2934 // We only want the first authority for a provider to possibly be
2935 // syncable, so if we already added this provider using a different
2936 // authority clear the syncable flag. We copy the provider before
2937 // changing it because the mProviders object contains a reference
2938 // to a provider that we don't want to change.
2939 // Only do this for the second authority since the resulting provider
2940 // object can be the same for all future authorities for this provider.
2941 p = new PackageParser.Provider(p);
2942 p.syncable = false;
2943 }
2944 if (!mProviders.containsKey(names[j])) {
2945 mProviders.put(names[j], p);
2946 if (p.info.authority == null) {
2947 p.info.authority = names[j];
2948 } else {
2949 p.info.authority = p.info.authority + ";" + names[j];
2950 }
2951 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
2952 Log.d(TAG, "Registered content provider: " + names[j] +
2953 ", className = " + p.info.name +
2954 ", isSyncable = " + p.info.isSyncable);
2955 } else {
The Android Open Source Project10592532009-03-18 17:39:46 -07002956 PackageParser.Provider other = mProviders.get(names[j]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 Log.w(TAG, "Skipping provider name " + names[j] +
2958 " (in package " + pkg.applicationInfo.packageName +
The Android Open Source Project10592532009-03-18 17:39:46 -07002959 "): name already used by "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 + ((other != null && other.getComponentName() != null)
2961 ? other.getComponentName().getPackageName() : "?"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 }
2963 }
2964 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2965 if (r == null) {
2966 r = new StringBuilder(256);
2967 } else {
2968 r.append(' ');
2969 }
2970 r.append(p.info.name);
2971 }
2972 }
2973 if (r != null) {
2974 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
2975 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 N = pkg.services.size();
2978 r = null;
2979 for (i=0; i<N; i++) {
2980 PackageParser.Service s = pkg.services.get(i);
2981 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
2982 s.info.processName, pkg.applicationInfo.uid);
2983 mServices.addService(s);
2984 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
2985 if (r == null) {
2986 r = new StringBuilder(256);
2987 } else {
2988 r.append(' ');
2989 }
2990 r.append(s.info.name);
2991 }
2992 }
2993 if (r != null) {
2994 if (Config.LOGD) Log.d(TAG, " Services: " + r);
2995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002997 N = pkg.receivers.size();
2998 r = null;
2999 for (i=0; i<N; i++) {
3000 PackageParser.Activity a = pkg.receivers.get(i);
3001 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3002 a.info.processName, pkg.applicationInfo.uid);
3003 mReceivers.addActivity(a, "receiver");
3004 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3005 if (r == null) {
3006 r = new StringBuilder(256);
3007 } else {
3008 r.append(' ');
3009 }
3010 r.append(a.info.name);
3011 }
3012 }
3013 if (r != null) {
3014 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 N = pkg.activities.size();
3018 r = null;
3019 for (i=0; i<N; i++) {
3020 PackageParser.Activity a = pkg.activities.get(i);
3021 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3022 a.info.processName, pkg.applicationInfo.uid);
3023 mActivities.addActivity(a, "activity");
3024 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3025 if (r == null) {
3026 r = new StringBuilder(256);
3027 } else {
3028 r.append(' ');
3029 }
3030 r.append(a.info.name);
3031 }
3032 }
3033 if (r != null) {
3034 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 N = pkg.permissionGroups.size();
3038 r = null;
3039 for (i=0; i<N; i++) {
3040 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3041 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3042 if (cur == null) {
3043 mPermissionGroups.put(pg.info.name, pg);
3044 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3045 if (r == null) {
3046 r = new StringBuilder(256);
3047 } else {
3048 r.append(' ');
3049 }
3050 r.append(pg.info.name);
3051 }
3052 } else {
3053 Log.w(TAG, "Permission group " + pg.info.name + " from package "
3054 + pg.info.packageName + " ignored: original from "
3055 + cur.info.packageName);
3056 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3057 if (r == null) {
3058 r = new StringBuilder(256);
3059 } else {
3060 r.append(' ');
3061 }
3062 r.append("DUP:");
3063 r.append(pg.info.name);
3064 }
3065 }
3066 }
3067 if (r != null) {
3068 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3069 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 N = pkg.permissions.size();
3072 r = null;
3073 for (i=0; i<N; i++) {
3074 PackageParser.Permission p = pkg.permissions.get(i);
3075 HashMap<String, BasePermission> permissionMap =
3076 p.tree ? mSettings.mPermissionTrees
3077 : mSettings.mPermissions;
3078 p.group = mPermissionGroups.get(p.info.group);
3079 if (p.info.group == null || p.group != null) {
3080 BasePermission bp = permissionMap.get(p.info.name);
3081 if (bp == null) {
3082 bp = new BasePermission(p.info.name, p.info.packageName,
3083 BasePermission.TYPE_NORMAL);
3084 permissionMap.put(p.info.name, bp);
3085 }
3086 if (bp.perm == null) {
3087 if (bp.sourcePackage == null
3088 || bp.sourcePackage.equals(p.info.packageName)) {
3089 BasePermission tree = findPermissionTreeLP(p.info.name);
3090 if (tree == null
3091 || tree.sourcePackage.equals(p.info.packageName)) {
3092 bp.perm = p;
3093 bp.uid = pkg.applicationInfo.uid;
3094 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3095 if (r == null) {
3096 r = new StringBuilder(256);
3097 } else {
3098 r.append(' ');
3099 }
3100 r.append(p.info.name);
3101 }
3102 } else {
3103 Log.w(TAG, "Permission " + p.info.name + " from package "
3104 + p.info.packageName + " ignored: base tree "
3105 + tree.name + " is from package "
3106 + tree.sourcePackage);
3107 }
3108 } else {
3109 Log.w(TAG, "Permission " + p.info.name + " from package "
3110 + p.info.packageName + " ignored: original from "
3111 + bp.sourcePackage);
3112 }
3113 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3114 if (r == null) {
3115 r = new StringBuilder(256);
3116 } else {
3117 r.append(' ');
3118 }
3119 r.append("DUP:");
3120 r.append(p.info.name);
3121 }
3122 } else {
3123 Log.w(TAG, "Permission " + p.info.name + " from package "
3124 + p.info.packageName + " ignored: no group "
3125 + p.group);
3126 }
3127 }
3128 if (r != null) {
3129 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 N = pkg.instrumentation.size();
3133 r = null;
3134 for (i=0; i<N; i++) {
3135 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3136 a.info.packageName = pkg.applicationInfo.packageName;
3137 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3138 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3139 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003140 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3142 if (r == null) {
3143 r = new StringBuilder(256);
3144 } else {
3145 r.append(' ');
3146 }
3147 r.append(a.info.name);
3148 }
3149 }
3150 if (r != null) {
3151 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3152 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003153
Dianne Hackborn854060af2009-07-09 18:14:31 -07003154 if (pkg.protectedBroadcasts != null) {
3155 N = pkg.protectedBroadcasts.size();
3156 for (i=0; i<N; i++) {
3157 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3158 }
3159 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 pkgSetting.setTimeStamp(scanFileTime);
3162 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 return pkg;
3165 }
3166
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003167 private void killApplication(String pkgName, int uid) {
3168 // Request the ActivityManager to kill the process(only for existing packages)
3169 // so that we do not end up in a confused state while the user is still using the older
3170 // version of the application while the new one gets installed.
3171 IActivityManager am = ActivityManagerNative.getDefault();
3172 if (am != null) {
3173 try {
3174 am.killApplicationWithUid(pkgName, uid);
3175 } catch (RemoteException e) {
3176 }
3177 }
3178 }
3179
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003180 // The following constants are returned by cachePackageSharedLibsForAbiLI
3181 // to indicate if native shared libraries were found in the package.
3182 // Values are:
3183 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3184 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3185 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3186 // in package (and not installed)
3187 //
3188 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3189 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3190 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003192 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3193 // and automatically copy them to /data/data/<appname>/lib if present.
3194 //
3195 // NOTE: this method may throw an IOException if the library cannot
3196 // be copied to its final destination, e.g. if there isn't enough
3197 // room left on the data partition, or a ZipException if the package
3198 // file is malformed.
3199 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003200 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
3201 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003202 File sharedLibraryDir = new File(dataPath.getPath() + "/lib");
3203 final String apkLib = "lib/";
3204 final int apkLibLen = apkLib.length();
3205 final int cpuAbiLen = cpuAbi.length();
3206 final String libPrefix = "lib";
3207 final int libPrefixLen = libPrefix.length();
3208 final String libSuffix = ".so";
3209 final int libSuffixLen = libSuffix.length();
3210 boolean hasNativeLibraries = false;
3211 boolean installedNativeLibraries = false;
3212
3213 // the minimum length of a valid native shared library of the form
3214 // lib/<something>/lib<name>.so.
3215 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3216
3217 ZipFile zipFile = new ZipFile(scanFile);
3218 Enumeration<ZipEntry> entries =
3219 (Enumeration<ZipEntry>) zipFile.entries();
3220
3221 while (entries.hasMoreElements()) {
3222 ZipEntry entry = entries.nextElement();
3223 // skip directories
3224 if (entry.isDirectory()) {
3225 continue;
3226 }
3227 String entryName = entry.getName();
3228
3229 // check that the entry looks like lib/<something>/lib<name>.so
3230 // here, but don't check the ABI just yet.
3231 //
3232 // - must be sufficiently long
3233 // - must end with libSuffix, i.e. ".so"
3234 // - must start with apkLib, i.e. "lib/"
3235 if (entryName.length() < minEntryLen ||
3236 !entryName.endsWith(libSuffix) ||
3237 !entryName.startsWith(apkLib) ) {
3238 continue;
3239 }
3240
3241 // file name must start with libPrefix, i.e. "lib"
3242 int lastSlash = entryName.lastIndexOf('/');
3243
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003244 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003245 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3246 continue;
3247 }
3248
3249 hasNativeLibraries = true;
3250
3251 // check the cpuAbi now, between lib/ and /lib<name>.so
3252 //
3253 if (lastSlash != apkLibLen + cpuAbiLen ||
3254 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3255 continue;
3256
3257 // extract the library file name, ensure it doesn't contain
3258 // weird characters. we're guaranteed here that it doesn't contain
3259 // a directory separator though.
3260 String libFileName = entryName.substring(lastSlash+1);
3261 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3262 continue;
3263 }
3264
3265 installedNativeLibraries = true;
3266
3267 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3268 File.separator + libFileName;
3269 File sharedLibraryFile = new File(sharedLibraryFilePath);
3270 if (! sharedLibraryFile.exists() ||
3271 sharedLibraryFile.length() != entry.getSize() ||
3272 sharedLibraryFile.lastModified() != entry.getTime()) {
3273 if (Config.LOGD) {
3274 Log.d(TAG, "Caching shared lib " + entry.getName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003276 if (mInstaller == null) {
3277 sharedLibraryDir.mkdir();
Dianne Hackbornb1811182009-05-21 15:45:42 -07003278 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003279 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003280 sharedLibraryFile);
3281 }
3282 }
3283 if (!hasNativeLibraries)
3284 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3285
3286 if (!installedNativeLibraries)
3287 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3288
3289 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3290 }
3291
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003292 // Find the gdbserver executable program in a package at
3293 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3294 //
3295 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3296 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3297 //
3298 private int cachePackageGdbServerLI(PackageParser.Package pkg,
3299 File dataPath, File scanFile, String cpuAbi) throws IOException, ZipException {
3300 File installGdbServerDir = new File(dataPath.getPath() + "/lib");
3301 final String GDBSERVER = "gdbserver";
3302 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3303
3304 ZipFile zipFile = new ZipFile(scanFile);
3305 Enumeration<ZipEntry> entries =
3306 (Enumeration<ZipEntry>) zipFile.entries();
3307
3308 while (entries.hasMoreElements()) {
3309 ZipEntry entry = entries.nextElement();
3310 // skip directories
3311 if (entry.isDirectory()) {
3312 continue;
3313 }
3314 String entryName = entry.getName();
3315
3316 if (!entryName.equals(apkGdbServerPath)) {
3317 continue;
3318 }
3319
3320 String installGdbServerPath = installGdbServerDir.getPath() +
3321 "/" + GDBSERVER;
3322 File installGdbServerFile = new File(installGdbServerPath);
3323 if (! installGdbServerFile.exists() ||
3324 installGdbServerFile.length() != entry.getSize() ||
3325 installGdbServerFile.lastModified() != entry.getTime()) {
3326 if (Config.LOGD) {
3327 Log.d(TAG, "Caching gdbserver " + entry.getName());
3328 }
3329 if (mInstaller == null) {
3330 installGdbServerDir.mkdir();
3331 }
3332 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3333 installGdbServerFile);
3334 }
3335 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3336 }
3337 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3338 }
3339
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003340 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3341 // and copy them to /data/data/<appname>/lib.
3342 //
3343 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3344 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3345 // one if ro.product.cpu.abi2 is defined.
3346 //
3347 private int cachePackageSharedLibsLI(PackageParser.Package pkg,
3348 File dataPath, File scanFile) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003349 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003350 try {
3351 int result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi);
3352
3353 // some architectures are capable of supporting several CPU ABIs
3354 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3355 // this is indicated by the definition of the ro.product.cpu.abi2
3356 // system property.
3357 //
3358 // only scan the package twice in case of ABI mismatch
3359 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003360 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003361 if (cpuAbi2 != null) {
3362 result = cachePackageSharedLibsForAbiLI(pkg, dataPath, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003364
3365 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
3366 Log.w(TAG,"Native ABI mismatch from package file");
3367 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003369
3370 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3371 cpuAbi = cpuAbi2;
3372 }
3373 }
3374
3375 // for debuggable packages, also extract gdbserver from lib/<abi>
3376 // into /data/data/<appname>/lib too.
3377 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3378 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
3379 int result2 = cachePackageGdbServerLI(pkg, dataPath, scanFile, cpuAbi);
3380 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3381 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003384 } catch (ZipException e) {
3385 Log.w(TAG, "Failed to extract data from package file", e);
3386 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 } catch (IOException e) {
Dianne Hackbornb1811182009-05-21 15:45:42 -07003388 Log.w(TAG, "Failed to cache package shared libs", e);
3389 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003391 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 }
3393
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003394 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003396 File binaryDir,
3397 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 InputStream inputStream = zipFile.getInputStream(entry);
3399 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003400 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003402 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 // now need to be left as world readable and owned by the system.
3404 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3405 ! tempFile.setLastModified(entry.getTime()) ||
3406 FileUtils.setPermissions(tempFilePath,
3407 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003408 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003410 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 // Failed to properly write file.
3412 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003413 throw new IOException("Couldn't create cached binary "
3414 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 }
3416 } finally {
3417 inputStream.close();
3418 }
3419 }
3420
3421 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3422 if (chatty && Config.LOGD) Log.d(
3423 TAG, "Removing package " + pkg.applicationInfo.packageName );
3424
3425 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 mPackages.remove(pkg.applicationInfo.packageName);
3429 if (pkg.mPath != null) {
3430 mAppDirs.remove(pkg.mPath);
3431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 PackageSetting ps = (PackageSetting)pkg.mExtras;
3434 if (ps != null && ps.sharedUser != null) {
3435 // XXX don't do this until the data is removed.
3436 if (false) {
3437 ps.sharedUser.packages.remove(ps);
3438 if (ps.sharedUser.packages.size() == 0) {
3439 // Remove.
3440 }
3441 }
3442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 int N = pkg.providers.size();
3445 StringBuilder r = null;
3446 int i;
3447 for (i=0; i<N; i++) {
3448 PackageParser.Provider p = pkg.providers.get(i);
3449 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3450 p.info.name));
3451 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 /* The is another ContentProvider with this authority when
3454 * this app was installed so this authority is null,
3455 * Ignore it as we don't have to unregister the provider.
3456 */
3457 continue;
3458 }
3459 String names[] = p.info.authority.split(";");
3460 for (int j = 0; j < names.length; j++) {
3461 if (mProviders.get(names[j]) == p) {
3462 mProviders.remove(names[j]);
3463 if (chatty && Config.LOGD) Log.d(
3464 TAG, "Unregistered content provider: " + names[j] +
3465 ", className = " + p.info.name +
3466 ", isSyncable = " + p.info.isSyncable);
3467 }
3468 }
3469 if (chatty) {
3470 if (r == null) {
3471 r = new StringBuilder(256);
3472 } else {
3473 r.append(' ');
3474 }
3475 r.append(p.info.name);
3476 }
3477 }
3478 if (r != null) {
3479 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 N = pkg.services.size();
3483 r = null;
3484 for (i=0; i<N; i++) {
3485 PackageParser.Service s = pkg.services.get(i);
3486 mServices.removeService(s);
3487 if (chatty) {
3488 if (r == null) {
3489 r = new StringBuilder(256);
3490 } else {
3491 r.append(' ');
3492 }
3493 r.append(s.info.name);
3494 }
3495 }
3496 if (r != null) {
3497 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003500 N = pkg.receivers.size();
3501 r = null;
3502 for (i=0; i<N; i++) {
3503 PackageParser.Activity a = pkg.receivers.get(i);
3504 mReceivers.removeActivity(a, "receiver");
3505 if (chatty) {
3506 if (r == null) {
3507 r = new StringBuilder(256);
3508 } else {
3509 r.append(' ');
3510 }
3511 r.append(a.info.name);
3512 }
3513 }
3514 if (r != null) {
3515 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 N = pkg.activities.size();
3519 r = null;
3520 for (i=0; i<N; i++) {
3521 PackageParser.Activity a = pkg.activities.get(i);
3522 mActivities.removeActivity(a, "activity");
3523 if (chatty) {
3524 if (r == null) {
3525 r = new StringBuilder(256);
3526 } else {
3527 r.append(' ');
3528 }
3529 r.append(a.info.name);
3530 }
3531 }
3532 if (r != null) {
3533 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 N = pkg.permissions.size();
3537 r = null;
3538 for (i=0; i<N; i++) {
3539 PackageParser.Permission p = pkg.permissions.get(i);
3540 boolean tree = false;
3541 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3542 if (bp == null) {
3543 tree = true;
3544 bp = mSettings.mPermissionTrees.get(p.info.name);
3545 }
3546 if (bp != null && bp.perm == p) {
3547 if (bp.type != BasePermission.TYPE_BUILTIN) {
3548 if (tree) {
3549 mSettings.mPermissionTrees.remove(p.info.name);
3550 } else {
3551 mSettings.mPermissions.remove(p.info.name);
3552 }
3553 } else {
3554 bp.perm = null;
3555 }
3556 if (chatty) {
3557 if (r == null) {
3558 r = new StringBuilder(256);
3559 } else {
3560 r.append(' ');
3561 }
3562 r.append(p.info.name);
3563 }
3564 }
3565 }
3566 if (r != null) {
3567 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 N = pkg.instrumentation.size();
3571 r = null;
3572 for (i=0; i<N; i++) {
3573 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003574 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003575 if (chatty) {
3576 if (r == null) {
3577 r = new StringBuilder(256);
3578 } else {
3579 r.append(' ');
3580 }
3581 r.append(a.info.name);
3582 }
3583 }
3584 if (r != null) {
3585 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3586 }
3587 }
3588 }
3589
3590 private static final boolean isPackageFilename(String name) {
3591 return name != null && name.endsWith(".apk");
3592 }
3593
3594 private void updatePermissionsLP() {
3595 // Make sure there are no dangling permission trees.
3596 Iterator<BasePermission> it = mSettings.mPermissionTrees
3597 .values().iterator();
3598 while (it.hasNext()) {
3599 BasePermission bp = it.next();
3600 if (bp.perm == null) {
3601 Log.w(TAG, "Removing dangling permission tree: " + bp.name
3602 + " from package " + bp.sourcePackage);
3603 it.remove();
3604 }
3605 }
3606
3607 // Make sure all dynamic permissions have been assigned to a package,
3608 // and make sure there are no dangling permissions.
3609 it = mSettings.mPermissions.values().iterator();
3610 while (it.hasNext()) {
3611 BasePermission bp = it.next();
3612 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3613 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3614 + bp.name + " pkg=" + bp.sourcePackage
3615 + " info=" + bp.pendingInfo);
3616 if (bp.perm == null && bp.pendingInfo != null) {
3617 BasePermission tree = findPermissionTreeLP(bp.name);
3618 if (tree != null) {
3619 bp.perm = new PackageParser.Permission(tree.perm.owner,
3620 new PermissionInfo(bp.pendingInfo));
3621 bp.perm.info.packageName = tree.perm.info.packageName;
3622 bp.perm.info.name = bp.name;
3623 bp.uid = tree.uid;
3624 }
3625 }
3626 }
3627 if (bp.perm == null) {
3628 Log.w(TAG, "Removing dangling permission: " + bp.name
3629 + " from package " + bp.sourcePackage);
3630 it.remove();
3631 }
3632 }
3633
3634 // Now update the permissions for all packages, in particular
3635 // replace the granted permissions of the system packages.
3636 for (PackageParser.Package pkg : mPackages.values()) {
3637 grantPermissionsLP(pkg, false);
3638 }
3639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3642 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3643 if (ps == null) {
3644 return;
3645 }
3646 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3647 boolean addedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 if (replace) {
3650 ps.permissionsFixed = false;
3651 if (gp == ps) {
3652 gp.grantedPermissions.clear();
3653 gp.gids = mGlobalGids;
3654 }
3655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 if (gp.gids == null) {
3658 gp.gids = mGlobalGids;
3659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 final int N = pkg.requestedPermissions.size();
3662 for (int i=0; i<N; i++) {
3663 String name = pkg.requestedPermissions.get(i);
3664 BasePermission bp = mSettings.mPermissions.get(name);
3665 PackageParser.Permission p = bp != null ? bp.perm : null;
3666 if (false) {
3667 if (gp != ps) {
3668 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
3669 + ": " + p);
3670 }
3671 }
3672 if (p != null) {
3673 final String perm = p.info.name;
3674 boolean allowed;
3675 if (p.info.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3676 || p.info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
3677 allowed = true;
3678 } else if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3679 || p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003680 allowed = (checkSignaturesLP(p.owner.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003682 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 == PackageManager.SIGNATURE_MATCH);
3684 if (p.info.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3685 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
3686 // For updated system applications, the signatureOrSystem permission
3687 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003688 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3690 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3691 if(sysPs.grantedPermissions.contains(perm)) {
3692 allowed = true;
3693 } else {
3694 allowed = false;
3695 }
3696 } else {
3697 allowed = true;
3698 }
3699 }
3700 }
3701 } else {
3702 allowed = false;
3703 }
3704 if (false) {
3705 if (gp != ps) {
3706 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3707 }
3708 }
3709 if (allowed) {
3710 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3711 && ps.permissionsFixed) {
3712 // If this is an existing, non-system package, then
3713 // we can't add any new permissions to it.
3714 if (!gp.loadedPermissions.contains(perm)) {
3715 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003716 // Except... if this is a permission that was added
3717 // to the platform (note: need to only do this when
3718 // updating the platform).
3719 final int NP = PackageParser.NEW_PERMISSIONS.length;
3720 for (int ip=0; ip<NP; ip++) {
3721 final PackageParser.NewPermissionInfo npi
3722 = PackageParser.NEW_PERMISSIONS[ip];
3723 if (npi.name.equals(perm)
3724 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3725 allowed = true;
San Mehat5a3a77d2009-06-01 09:25:28 -07003726 Log.i(TAG, "Auto-granting WRITE_EXTERNAL_STORAGE to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003727 + pkg.packageName);
3728 break;
3729 }
3730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003731 }
3732 }
3733 if (allowed) {
3734 if (!gp.grantedPermissions.contains(perm)) {
3735 addedPermission = true;
3736 gp.grantedPermissions.add(perm);
3737 gp.gids = appendInts(gp.gids, bp.gids);
3738 }
3739 } else {
3740 Log.w(TAG, "Not granting permission " + perm
3741 + " to package " + pkg.packageName
3742 + " because it was previously installed without");
3743 }
3744 } else {
3745 Log.w(TAG, "Not granting permission " + perm
3746 + " to package " + pkg.packageName
3747 + " (protectionLevel=" + p.info.protectionLevel
3748 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3749 + ")");
3750 }
3751 } else {
3752 Log.w(TAG, "Unknown permission " + name
3753 + " in package " + pkg.packageName);
3754 }
3755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if ((addedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003758 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3759 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 // This is the first that we have heard about this package, so the
3761 // permissions we have now selected are fixed until explicitly
3762 // changed.
3763 ps.permissionsFixed = true;
3764 gp.loadedPermissions = new HashSet<String>(gp.grantedPermissions);
3765 }
3766 }
3767
3768 private final class ActivityIntentResolver
3769 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003770 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003772 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774
Mihai Preda074edef2009-05-18 17:13:31 +02003775 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003777 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3779 }
3780
Mihai Predaeae850c2009-05-13 10:13:48 +02003781 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3782 ArrayList<PackageParser.Activity> packageActivities) {
3783 if (packageActivities == null) {
3784 return null;
3785 }
3786 mFlags = flags;
3787 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3788 int N = packageActivities.size();
3789 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
3790 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02003791
3792 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02003793 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02003794 intentFilters = packageActivities.get(i).intents;
3795 if (intentFilters != null && intentFilters.size() > 0) {
3796 listCut.add(intentFilters);
3797 }
Mihai Predaeae850c2009-05-13 10:13:48 +02003798 }
3799 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3800 }
3801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003803 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 if (SHOW_INFO || Config.LOGV) Log.v(
3805 TAG, " " + type + " " +
3806 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3807 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3808 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003809 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3811 if (SHOW_INFO || Config.LOGV) {
3812 Log.v(TAG, " IntentFilter:");
3813 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3814 }
3815 if (!intent.debugCheck()) {
3816 Log.w(TAG, "==> For Activity " + a.info.name);
3817 }
3818 addFilter(intent);
3819 }
3820 }
3821
3822 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003823 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 if (SHOW_INFO || Config.LOGV) Log.v(
3825 TAG, " " + type + " " +
3826 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
3827 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
3828 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02003829 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
3831 if (SHOW_INFO || Config.LOGV) {
3832 Log.v(TAG, " IntentFilter:");
3833 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3834 }
3835 removeFilter(intent);
3836 }
3837 }
3838
3839 @Override
3840 protected boolean allowFilterResult(
3841 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
3842 ActivityInfo filterAi = filter.activity.info;
3843 for (int i=dest.size()-1; i>=0; i--) {
3844 ActivityInfo destAi = dest.get(i).activityInfo;
3845 if (destAi.name == filterAi.name
3846 && destAi.packageName == filterAi.packageName) {
3847 return false;
3848 }
3849 }
3850 return true;
3851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 @Override
3854 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
3855 int match) {
3856 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
3857 return null;
3858 }
3859 final PackageParser.Activity activity = info.activity;
3860 if (mSafeMode && (activity.info.applicationInfo.flags
3861 &ApplicationInfo.FLAG_SYSTEM) == 0) {
3862 return null;
3863 }
3864 final ResolveInfo res = new ResolveInfo();
3865 res.activityInfo = PackageParser.generateActivityInfo(activity,
3866 mFlags);
3867 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
3868 res.filter = info;
3869 }
3870 res.priority = info.getPriority();
3871 res.preferredOrder = activity.owner.mPreferredOrder;
3872 //System.out.println("Result: " + res.activityInfo.className +
3873 // " = " + res.priority);
3874 res.match = match;
3875 res.isDefault = info.hasDefault;
3876 res.labelRes = info.labelRes;
3877 res.nonLocalizedLabel = info.nonLocalizedLabel;
3878 res.icon = info.icon;
3879 return res;
3880 }
3881
3882 @Override
3883 protected void sortResults(List<ResolveInfo> results) {
3884 Collections.sort(results, mResolvePrioritySorter);
3885 }
3886
3887 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003888 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003890 out.print(prefix); out.print(
3891 Integer.toHexString(System.identityHashCode(filter.activity)));
3892 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003893 out.println(filter.activity.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 }
3895
3896// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
3897// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
3898// final List<ResolveInfo> retList = Lists.newArrayList();
3899// while (i.hasNext()) {
3900// final ResolveInfo resolveInfo = i.next();
3901// if (isEnabledLP(resolveInfo.activityInfo)) {
3902// retList.add(resolveInfo);
3903// }
3904// }
3905// return retList;
3906// }
3907
3908 // Keys are String (activity class name), values are Activity.
3909 private final HashMap<ComponentName, PackageParser.Activity> mActivities
3910 = new HashMap<ComponentName, PackageParser.Activity>();
3911 private int mFlags;
3912 }
3913
3914 private final class ServiceIntentResolver
3915 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003916 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02003918 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 }
3920
Mihai Preda074edef2009-05-18 17:13:31 +02003921 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02003923 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
3925 }
3926
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07003927 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
3928 ArrayList<PackageParser.Service> packageServices) {
3929 if (packageServices == null) {
3930 return null;
3931 }
3932 mFlags = flags;
3933 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
3934 int N = packageServices.size();
3935 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
3936 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
3937
3938 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
3939 for (int i = 0; i < N; ++i) {
3940 intentFilters = packageServices.get(i).intents;
3941 if (intentFilters != null && intentFilters.size() > 0) {
3942 listCut.add(intentFilters);
3943 }
3944 }
3945 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
3946 }
3947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003949 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 if (SHOW_INFO || Config.LOGV) Log.v(
3951 TAG, " " + (s.info.nonLocalizedLabel != null
3952 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3953 if (SHOW_INFO || Config.LOGV) Log.v(
3954 TAG, " Class=" + s.info.name);
3955 int NI = s.intents.size();
3956 int j;
3957 for (j=0; j<NI; j++) {
3958 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3959 if (SHOW_INFO || Config.LOGV) {
3960 Log.v(TAG, " IntentFilter:");
3961 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3962 }
3963 if (!intent.debugCheck()) {
3964 Log.w(TAG, "==> For Service " + s.info.name);
3965 }
3966 addFilter(intent);
3967 }
3968 }
3969
3970 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003971 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 if (SHOW_INFO || Config.LOGV) Log.v(
3973 TAG, " " + (s.info.nonLocalizedLabel != null
3974 ? s.info.nonLocalizedLabel : s.info.name) + ":");
3975 if (SHOW_INFO || Config.LOGV) Log.v(
3976 TAG, " Class=" + s.info.name);
3977 int NI = s.intents.size();
3978 int j;
3979 for (j=0; j<NI; j++) {
3980 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
3981 if (SHOW_INFO || Config.LOGV) {
3982 Log.v(TAG, " IntentFilter:");
3983 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
3984 }
3985 removeFilter(intent);
3986 }
3987 }
3988
3989 @Override
3990 protected boolean allowFilterResult(
3991 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
3992 ServiceInfo filterSi = filter.service.info;
3993 for (int i=dest.size()-1; i>=0; i--) {
3994 ServiceInfo destAi = dest.get(i).serviceInfo;
3995 if (destAi.name == filterSi.name
3996 && destAi.packageName == filterSi.packageName) {
3997 return false;
3998 }
3999 }
4000 return true;
4001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 @Override
4004 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4005 int match) {
4006 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4007 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4008 return null;
4009 }
4010 final PackageParser.Service service = info.service;
4011 if (mSafeMode && (service.info.applicationInfo.flags
4012 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4013 return null;
4014 }
4015 final ResolveInfo res = new ResolveInfo();
4016 res.serviceInfo = PackageParser.generateServiceInfo(service,
4017 mFlags);
4018 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4019 res.filter = filter;
4020 }
4021 res.priority = info.getPriority();
4022 res.preferredOrder = service.owner.mPreferredOrder;
4023 //System.out.println("Result: " + res.activityInfo.className +
4024 // " = " + res.priority);
4025 res.match = match;
4026 res.isDefault = info.hasDefault;
4027 res.labelRes = info.labelRes;
4028 res.nonLocalizedLabel = info.nonLocalizedLabel;
4029 res.icon = info.icon;
4030 return res;
4031 }
4032
4033 @Override
4034 protected void sortResults(List<ResolveInfo> results) {
4035 Collections.sort(results, mResolvePrioritySorter);
4036 }
4037
4038 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004039 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004041 out.print(prefix); out.print(
4042 Integer.toHexString(System.identityHashCode(filter.service)));
4043 out.print(' ');
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004044 out.println(filter.service.getComponentShortName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 }
4046
4047// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4048// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4049// final List<ResolveInfo> retList = Lists.newArrayList();
4050// while (i.hasNext()) {
4051// final ResolveInfo resolveInfo = (ResolveInfo) i;
4052// if (isEnabledLP(resolveInfo.serviceInfo)) {
4053// retList.add(resolveInfo);
4054// }
4055// }
4056// return retList;
4057// }
4058
4059 // Keys are String (activity class name), values are Activity.
4060 private final HashMap<ComponentName, PackageParser.Service> mServices
4061 = new HashMap<ComponentName, PackageParser.Service>();
4062 private int mFlags;
4063 };
4064
4065 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4066 new Comparator<ResolveInfo>() {
4067 public int compare(ResolveInfo r1, ResolveInfo r2) {
4068 int v1 = r1.priority;
4069 int v2 = r2.priority;
4070 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4071 if (v1 != v2) {
4072 return (v1 > v2) ? -1 : 1;
4073 }
4074 v1 = r1.preferredOrder;
4075 v2 = r2.preferredOrder;
4076 if (v1 != v2) {
4077 return (v1 > v2) ? -1 : 1;
4078 }
4079 if (r1.isDefault != r2.isDefault) {
4080 return r1.isDefault ? -1 : 1;
4081 }
4082 v1 = r1.match;
4083 v2 = r2.match;
4084 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4085 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4086 }
4087 };
4088
4089 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4090 new Comparator<ProviderInfo>() {
4091 public int compare(ProviderInfo p1, ProviderInfo p2) {
4092 final int v1 = p1.initOrder;
4093 final int v2 = p2.initOrder;
4094 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4095 }
4096 };
4097
4098 private static final void sendPackageBroadcast(String action, String pkg, Bundle extras) {
4099 IActivityManager am = ActivityManagerNative.getDefault();
4100 if (am != null) {
4101 try {
4102 final Intent intent = new Intent(action,
4103 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4104 if (extras != null) {
4105 intent.putExtras(extras);
4106 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004107 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 am.broadcastIntent(
4109 null, intent,
4110 null, null, 0, null, null, null, false, false);
4111 } catch (RemoteException ex) {
4112 }
4113 }
4114 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004115
4116 public String nextPackageToClean(String lastPackage) {
4117 synchronized (mPackages) {
4118 if (!mMediaMounted) {
4119 // If the external storage is no longer mounted at this point,
4120 // the caller may not have been able to delete all of this
4121 // packages files and can not delete any more. Bail.
4122 return null;
4123 }
4124 if (lastPackage != null) {
4125 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4126 }
4127 return mSettings.mPackagesToBeCleaned.size() > 0
4128 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4129 }
4130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004132 void schedulePackageCleaning(String packageName) {
4133 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4134 }
4135
4136 void startCleaningPackages() {
4137 synchronized (mPackages) {
4138 if (!mMediaMounted) {
4139 return;
4140 }
4141 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4142 return;
4143 }
4144 }
4145 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4146 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4147 IActivityManager am = ActivityManagerNative.getDefault();
4148 if (am != null) {
4149 try {
4150 am.startService(null, intent, null);
4151 } catch (RemoteException e) {
4152 }
4153 }
4154 }
4155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 private final class AppDirObserver extends FileObserver {
4157 public AppDirObserver(String path, int mask, boolean isrom) {
4158 super(path, mask);
4159 mRootDir = path;
4160 mIsRom = isrom;
4161 }
4162
4163 public void onEvent(int event, String path) {
4164 String removedPackage = null;
4165 int removedUid = -1;
4166 String addedPackage = null;
4167 int addedUid = -1;
4168
4169 synchronized (mInstallLock) {
4170 String fullPathStr = null;
4171 File fullPath = null;
4172 if (path != null) {
4173 fullPath = new File(mRootDir, path);
4174 fullPathStr = fullPath.getPath();
4175 }
4176
4177 if (Config.LOGV) Log.v(
4178 TAG, "File " + fullPathStr + " changed: "
4179 + Integer.toHexString(event));
4180
4181 if (!isPackageFilename(path)) {
4182 if (Config.LOGV) Log.v(
4183 TAG, "Ignoring change of non-package file: " + fullPathStr);
4184 return;
4185 }
4186
4187 if ((event&REMOVE_EVENTS) != 0) {
4188 synchronized (mInstallLock) {
4189 PackageParser.Package p = mAppDirs.get(fullPathStr);
4190 if (p != null) {
4191 removePackageLI(p, true);
4192 removedPackage = p.applicationInfo.packageName;
4193 removedUid = p.applicationInfo.uid;
4194 }
4195 }
4196 }
4197
4198 if ((event&ADD_EVENTS) != 0) {
4199 PackageParser.Package p = mAppDirs.get(fullPathStr);
4200 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004201 p = scanPackageLI(fullPath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 (mIsRom ? PackageParser.PARSE_IS_SYSTEM : 0) |
4203 PackageParser.PARSE_CHATTY |
4204 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004205 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 if (p != null) {
4207 synchronized (mPackages) {
4208 grantPermissionsLP(p, false);
4209 }
4210 addedPackage = p.applicationInfo.packageName;
4211 addedUid = p.applicationInfo.uid;
4212 }
4213 }
4214 }
4215
4216 synchronized (mPackages) {
4217 mSettings.writeLP();
4218 }
4219 }
4220
4221 if (removedPackage != null) {
4222 Bundle extras = new Bundle(1);
4223 extras.putInt(Intent.EXTRA_UID, removedUid);
4224 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
4225 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
4226 }
4227 if (addedPackage != null) {
4228 Bundle extras = new Bundle(1);
4229 extras.putInt(Intent.EXTRA_UID, addedUid);
4230 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, extras);
4231 }
4232 }
4233
4234 private final String mRootDir;
4235 private final boolean mIsRom;
4236 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 /* Called when a downloaded package installation has been confirmed by the user */
4239 public void installPackage(
4240 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004241 installPackage(packageURI, observer, flags, null);
4242 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004243
Jacek Surazski65e13172009-04-28 15:26:38 +02004244 /* Called when a downloaded package installation has been confirmed by the user */
4245 public void installPackage(
4246 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4247 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 mContext.enforceCallingOrSelfPermission(
4249 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004250
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004251 Message msg = mHandler.obtainMessage(INIT_COPY);
4252 msg.obj = createInstallArgs(packageURI, observer, flags, installerPackageName);
4253 mHandler.sendMessage(msg);
4254 }
4255
4256 private InstallArgs createInstallArgs(Uri packageURI, IPackageInstallObserver observer,
4257 int flags, String installerPackageName) {
4258 if (installOnSd(flags)) {
4259 return new SdInstallArgs(packageURI, observer, flags,
4260 installerPackageName);
4261 } else {
4262 return new FileInstallArgs(packageURI, observer, flags,
4263 installerPackageName);
4264 }
4265 }
4266
4267 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
4268 if (installOnSd(flags)) {
4269 return new SdInstallArgs(fullCodePath, fullResourcePath);
4270 } else {
4271 return new FileInstallArgs(fullCodePath, fullResourcePath);
4272 }
4273 }
4274
4275 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 // Queue up an async operation since the package installation may take a little while.
4277 mHandler.post(new Runnable() {
4278 public void run() {
4279 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004280 // Result object to be returned
4281 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004282 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004283 res.uid = -1;
4284 res.pkg = null;
4285 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004286 args.doPreInstall(res.returnCode);
4287 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004288 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004289 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004290 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004291 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004293 if (args.observer != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004295 args.observer.packageInstalled(res.name, res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 } catch (RemoteException e) {
4297 Log.i(TAG, "Observer no longer exists.");
4298 }
4299 }
4300 // There appears to be a subtle deadlock condition if the sendPackageBroadcast
4301 // call appears in the synchronized block above.
4302 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4303 res.removedInfo.sendBroadcast(false, true);
4304 Bundle extras = new Bundle(1);
4305 extras.putInt(Intent.EXTRA_UID, res.uid);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004306 final boolean update = res.removedInfo.removedPackage != null;
4307 if (update) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 extras.putBoolean(Intent.EXTRA_REPLACING, true);
4309 }
4310 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
4311 res.pkg.applicationInfo.packageName,
4312 extras);
Dianne Hackbornf63220f2009-03-24 18:38:43 -07004313 if (update) {
4314 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
4315 res.pkg.applicationInfo.packageName,
4316 extras);
4317 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004318 if (res.removedInfo.args != null) {
4319 // Remove the replaced package's older resources safely now
4320 synchronized (mInstallLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004321 res.removedInfo.args.doPostDeleteLI(true);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004322 }
4323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 }
4325 Runtime.getRuntime().gc();
4326 }
4327 });
4328 }
4329
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004330 static abstract class InstallArgs {
4331 final IPackageInstallObserver observer;
4332 final int flags;
4333 final Uri packageURI;
4334 final String installerPackageName;
4335
4336 InstallArgs(Uri packageURI,
4337 IPackageInstallObserver observer, int flags,
4338 String installerPackageName) {
4339 this.packageURI = packageURI;
4340 this.flags = flags;
4341 this.observer = observer;
4342 this.installerPackageName = installerPackageName;
4343 }
4344
4345 abstract void createCopyFile();
4346 abstract int copyApk(IMediaContainerService imcs);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004347 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004348 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004349 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004350 abstract String getCodePath();
4351 abstract String getResourcePath();
4352 // Need installer lock especially for dex file removal.
4353 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004354 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004355 }
4356
4357 class FileInstallArgs extends InstallArgs {
4358 File installDir;
4359 String codeFileName;
4360 String resourceFileName;
4361
4362 FileInstallArgs(Uri packageURI,
4363 IPackageInstallObserver observer, int flags,
4364 String installerPackageName) {
4365 super(packageURI, observer, flags, installerPackageName);
4366 }
4367
4368 FileInstallArgs(String fullCodePath, String fullResourcePath) {
4369 super(null, null, 0, null);
4370 File codeFile = new File(fullCodePath);
4371 installDir = codeFile.getParentFile();
4372 codeFileName = fullCodePath;
4373 resourceFileName = fullResourcePath;
4374 }
4375
4376 void createCopyFile() {
4377 boolean fwdLocked = isFwdLocked(flags);
4378 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
4379 codeFileName = createTempPackageFile(installDir).getPath();
4380 resourceFileName = getResourcePathFromCodePath();
4381 }
4382
4383 String getCodePath() {
4384 return codeFileName;
4385 }
4386
4387 int copyApk(IMediaContainerService imcs) {
4388 // Get a ParcelFileDescriptor to write to the output file
4389 File codeFile = new File(codeFileName);
4390 ParcelFileDescriptor out = null;
4391 try {
4392 out = ParcelFileDescriptor.open(codeFile,
4393 ParcelFileDescriptor.MODE_READ_WRITE);
4394 } catch (FileNotFoundException e) {
4395 Log.e(TAG, "Failed to create file descritpor for : " + codeFileName);
4396 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4397 }
4398 // Copy the resource now
4399 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4400 try {
4401 if (imcs.copyResource(packageURI, out)) {
4402 ret = PackageManager.INSTALL_SUCCEEDED;
4403 }
4404 } catch (RemoteException e) {
4405 } finally {
4406 try { if (out != null) out.close(); } catch (IOException e) {}
4407 }
4408 return ret;
4409 }
4410
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004411 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004412 if (status != PackageManager.INSTALL_SUCCEEDED) {
4413 cleanUp();
4414 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004415 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004416 }
4417
4418 boolean doRename(int status, final String pkgName, String oldCodePath) {
4419 if (status != PackageManager.INSTALL_SUCCEEDED) {
4420 cleanUp();
4421 return false;
4422 } else {
4423 // Rename based on packageName
4424 File codeFile = new File(getCodePath());
4425 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
4426 File desFile = new File(installDir, apkName + ".apk");
4427 if (!codeFile.renameTo(desFile)) {
4428 return false;
4429 }
4430 // Reset paths since the file has been renamed.
4431 codeFileName = desFile.getPath();
4432 resourceFileName = getResourcePathFromCodePath();
4433 // Set permissions
4434 if (!setPermissions(pkgName)) {
4435 // Failed setting permissions.
4436 return false;
4437 }
4438 return true;
4439 }
4440 }
4441
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004442 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004443 if (status != PackageManager.INSTALL_SUCCEEDED) {
4444 cleanUp();
4445 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004446 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004447 }
4448
4449 String getResourcePath() {
4450 return resourceFileName;
4451 }
4452
4453 String getResourcePathFromCodePath() {
4454 String codePath = getCodePath();
4455 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
4456 String apkNameOnly = getApkName(codePath);
4457 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
4458 } else {
4459 return codePath;
4460 }
4461 }
4462
4463 private boolean cleanUp() {
4464 boolean ret = true;
4465 String sourceDir = getCodePath();
4466 String publicSourceDir = getResourcePath();
4467 if (sourceDir != null) {
4468 File sourceFile = new File(sourceDir);
4469 if (!sourceFile.exists()) {
4470 Log.w(TAG, "Package source " + sourceDir + " does not exist.");
4471 ret = false;
4472 }
4473 // Delete application's code and resources
4474 sourceFile.delete();
4475 }
4476 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
4477 final File publicSourceFile = new File(publicSourceDir);
4478 if (!publicSourceFile.exists()) {
4479 Log.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
4480 }
4481 if (publicSourceFile.exists()) {
4482 publicSourceFile.delete();
4483 }
4484 }
4485 return ret;
4486 }
4487
4488 void cleanUpResourcesLI() {
4489 String sourceDir = getCodePath();
4490 if (cleanUp() && mInstaller != null) {
4491 int retCode = mInstaller.rmdex(sourceDir);
4492 if (retCode < 0) {
4493 Log.w(TAG, "Couldn't remove dex file for package: "
4494 + " at location "
4495 + sourceDir + ", retcode=" + retCode);
4496 // we don't consider this to be a failure of the core package deletion
4497 }
4498 }
4499 }
4500
4501 private boolean setPermissions(String pkgName) {
4502 // TODO Do this in a more elegant way later on. for now just a hack
4503 if (!isFwdLocked(flags)) {
4504 final int filePermissions =
4505 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
4506 |FileUtils.S_IROTH;
4507 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
4508 if (retCode != 0) {
4509 Log.e(TAG, "Couldn't set new package file permissions for " +
4510 getCodePath()
4511 + ". The return code was: " + retCode);
4512 // TODO Define new internal error
4513 return false;
4514 }
4515 return true;
4516 }
4517 return true;
4518 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004519
4520 boolean doPostDeleteLI(boolean delete) {
4521 cleanUpResourcesLI();
4522 return true;
4523 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004524 }
4525
4526 class SdInstallArgs extends InstallArgs {
4527 String cid;
4528 String cachePath;
4529 static final String RES_FILE_NAME = "pkg.apk";
4530
4531 SdInstallArgs(Uri packageURI,
4532 IPackageInstallObserver observer, int flags,
4533 String installerPackageName) {
4534 super(packageURI, observer, flags, installerPackageName);
4535 }
4536
4537 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004538 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004539 // Extract cid from fullCodePath
4540 int eidx = fullCodePath.lastIndexOf("/");
4541 String subStr1 = fullCodePath.substring(0, eidx);
4542 int sidx = subStr1.lastIndexOf("/");
4543 cid = subStr1.substring(sidx+1, eidx);
4544 cachePath = subStr1;
4545 }
4546
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004547 SdInstallArgs(String cid) {
4548 super(null, null, ApplicationInfo.FLAG_ON_SDCARD, null);
4549 this.cid = cid;
4550 }
4551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004552 void createCopyFile() {
4553 cid = getTempContainerId();
4554 }
4555
4556 int copyApk(IMediaContainerService imcs) {
4557 try {
4558 cachePath = imcs.copyResourceToContainer(
4559 packageURI, cid,
4560 getEncryptKey(), RES_FILE_NAME);
4561 } catch (RemoteException e) {
4562 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004563 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
4564 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004565 }
4566
4567 @Override
4568 String getCodePath() {
4569 return cachePath + "/" + RES_FILE_NAME;
4570 }
4571
4572 @Override
4573 String getResourcePath() {
4574 return cachePath + "/" + RES_FILE_NAME;
4575 }
4576
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004577 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 if (status != PackageManager.INSTALL_SUCCEEDED) {
4579 // Destroy container
4580 destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004581 } else {
4582 // STOPSHIP Remove once new api is added in MountService
4583 //boolean mounted = isContainerMounted(cid);
4584 boolean mounted = false;
4585 if (!mounted) {
4586 cachePath = mountSdDir(cid, Process.SYSTEM_UID);
4587 if (cachePath == null) {
4588 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
4589 }
4590 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004591 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004592 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004593 }
4594
4595 boolean doRename(int status, final String pkgName,
4596 String oldCodePath) {
4597 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004598 String newCachePath = null;
4599 /*final int RENAME_FAILED = 1;
4600 final int MOUNT_FAILED = 2;
4601 final int DESTROY_FAILED = 3;
4602 final int PASS = 4;
4603 int errCode = RENAME_FAILED;
4604 if (mounted) {
4605 // Unmount the container
4606 if (!unMountSdDir(cid)) {
4607 Log.i(TAG, "Failed to unmount " + cid + " before renaming");
4608 return false;
4609 }
4610 mounted = false;
4611 }
4612 if (renameSdDir(cid, newCacheId)) {
4613 errCode = MOUNT_FAILED;
4614 if ((newCachePath = mountSdDir(newCacheId, Process.SYSTEM_UID)) != null) {
4615 errCode = PASS;
4616 }
4617 }
4618 String errMsg = "";
4619 switch (errCode) {
4620 case RENAME_FAILED:
4621 errMsg = "RENAME_FAILED";
4622 break;
4623 case MOUNT_FAILED:
4624 errMsg = "MOUNT_FAILED";
4625 break;
4626 case DESTROY_FAILED:
4627 errMsg = "DESTROY_FAILED";
4628 break;
4629 default:
4630 errMsg = "PASS";
4631 break;
4632 }
4633 Log.i(TAG, "Status: " + errMsg);
4634 if (errCode != PASS) {
4635 return false;
4636 }
4637 Log.i(TAG, "Succesfully renamed " + cid + " to " +newCacheId +
4638 " at path: " + cachePath + " to new path: " + newCachePath);
4639 cid = newCacheId;
4640 cachePath = newCachePath;
4641 return true;
4642 */
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004643 // STOPSHIP TEMPORARY HACK FOR RENAME
4644 // Create new container at newCachePath
4645 String codePath = getCodePath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004646 final int CREATE_FAILED = 1;
4647 final int COPY_FAILED = 3;
4648 final int FINALIZE_FAILED = 5;
4649 final int PASS = 7;
4650 int errCode = CREATE_FAILED;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004651
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004652 if ((newCachePath = createSdDir(new File(codePath), newCacheId)) != null) {
4653 errCode = COPY_FAILED;
4654 // Copy file from codePath
4655 if (FileUtils.copyFile(new File(codePath), new File(newCachePath, RES_FILE_NAME))) {
4656 errCode = FINALIZE_FAILED;
4657 if (finalizeSdDir(newCacheId)) {
4658 errCode = PASS;
4659 }
4660 }
4661 }
4662 // Print error based on errCode
4663 String errMsg = "";
4664 switch (errCode) {
4665 case CREATE_FAILED:
4666 errMsg = "CREATE_FAILED";
4667 break;
4668 case COPY_FAILED:
4669 errMsg = "COPY_FAILED";
4670 destroySdDir(newCacheId);
4671 break;
4672 case FINALIZE_FAILED:
4673 errMsg = "FINALIZE_FAILED";
4674 destroySdDir(newCacheId);
4675 break;
4676 default:
4677 errMsg = "PASS";
4678 break;
4679 }
4680 // Destroy the temporary container
4681 destroySdDir(cid);
4682 Log.i(TAG, "Status: " + errMsg);
4683 if (errCode != PASS) {
4684 return false;
4685 }
4686 cid = newCacheId;
4687 cachePath = newCachePath;
4688
4689 return true;
4690 }
4691
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004692 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004693 if (status != PackageManager.INSTALL_SUCCEEDED) {
4694 cleanUp();
4695 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004696 // STOP SHIP Change this once new api is added.
4697 //boolean mounted = isContainerMounted(cid);
4698 boolean mounted = false;
4699 if (!mounted) {
4700 mountSdDir(cid, Process.SYSTEM_UID);
4701 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004702 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004703 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004704 }
4705
4706 private void cleanUp() {
4707 // Destroy secure container
4708 destroySdDir(cid);
4709 }
4710
4711 void cleanUpResourcesLI() {
4712 String sourceFile = getCodePath();
4713 // Remove dex file
4714 if (mInstaller != null) {
4715 int retCode = mInstaller.rmdex(sourceFile.toString());
4716 if (retCode < 0) {
4717 Log.w(TAG, "Couldn't remove dex file for package: "
4718 + " at location "
4719 + sourceFile.toString() + ", retcode=" + retCode);
4720 // we don't consider this to be a failure of the core package deletion
4721 }
4722 }
4723 cleanUp();
4724 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004725
4726 boolean matchContainer(String app) {
4727 if (cid.startsWith(app)) {
4728 return true;
4729 }
4730 return false;
4731 }
4732
4733 String getPackageName() {
4734 int idx = cid.lastIndexOf("-");
4735 if (idx == -1) {
4736 return cid;
4737 }
4738 return cid.substring(0, idx);
4739 }
4740
4741 boolean doPostDeleteLI(boolean delete) {
4742 boolean ret = false;
4743 boolean mounted = isContainerMounted(cid);
4744 if (mounted) {
4745 // Unmount first
4746 ret = unMountSdDir(cid);
4747 }
4748 if (ret && delete) {
4749 cleanUpResourcesLI();
4750 }
4751 return ret;
4752 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004753 };
4754
4755 // Utility method used to create code paths based on package name and available index.
4756 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
4757 String idxStr = "";
4758 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004759 // Fall back to default value of idx=1 if prefix is not
4760 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004761 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004762 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004763 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00004764 if (subStr.endsWith(suffix)) {
4765 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004766 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004767 // If oldCodePath already contains prefix find out the
4768 // ending index to either increment or decrement.
4769 int sidx = subStr.lastIndexOf(prefix);
4770 if (sidx != -1) {
4771 subStr = subStr.substring(sidx + prefix.length());
4772 if (subStr != null) {
4773 if (subStr.startsWith("-")) {
4774 subStr = subStr.substring(1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004775 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004776 try {
4777 idx = Integer.parseInt(subStr);
4778 if (idx <= 1) {
4779 idx++;
4780 } else {
4781 idx--;
4782 }
4783 } catch(NumberFormatException e) {
4784 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004785 }
4786 }
4787 }
4788 idxStr = "-" + Integer.toString(idx);
4789 return prefix + idxStr;
4790 }
4791
4792 // Utility method that returns the relative package path with respect
4793 // to the installation directory. Like say for /data/data/com.test-1.apk
4794 // string com.test-1 is returned.
4795 static String getApkName(String codePath) {
4796 if (codePath == null) {
4797 return null;
4798 }
4799 int sidx = codePath.lastIndexOf("/");
4800 int eidx = codePath.lastIndexOf(".");
4801 if (eidx == -1) {
4802 eidx = codePath.length();
4803 } else if (eidx == 0) {
4804 Log.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
4805 return null;
4806 }
4807 return codePath.substring(sidx+1, eidx);
4808 }
4809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 class PackageInstalledInfo {
4811 String name;
4812 int uid;
4813 PackageParser.Package pkg;
4814 int returnCode;
4815 PackageRemovedInfo removedInfo;
4816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 /*
4819 * Install a non-existing package.
4820 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004821 private void installNewPackageLI(PackageParser.Package pkg,
4822 int parseFlags,
4823 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004824 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004825 // Remember this for later, in case we need to rollback this install
Oscar Montemayora8529f62009-11-18 10:14:20 -08004826 boolean dataDirExists;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004827 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08004828
4829 if (useEncryptedFilesystemForPackage(pkg)) {
4830 dataDirExists = (new File(mSecureAppDataDir, pkgName)).exists();
4831 } else {
4832 dataDirExists = (new File(mAppDataDir, pkgName)).exists();
4833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004834 res.name = pkgName;
4835 synchronized(mPackages) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004836 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 // Don't allow installation over an existing package with the same name.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004838 Log.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 + " without first uninstalling.");
4840 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4841 return;
4842 }
4843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004845 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004847 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4849 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
4850 }
4851 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004852 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004853 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 res);
4855 // delete the partially installed application. the data directory will have to be
4856 // restored if it was already existing
4857 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4858 // remove package from internal structures. Note that we want deletePackageX to
4859 // delete the package data and cache directories that it created in
4860 // scanPackageLocked, unless those directories existed before we even tried to
4861 // install.
4862 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004863 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
4865 res.removedInfo);
4866 }
4867 }
4868 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004869
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004870 private void replacePackageLI(PackageParser.Package pkg,
4871 int parseFlags,
4872 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004873 String installerPackageName, PackageInstalledInfo res) {
4874
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004875 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004876 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 // First find the old package info and check signatures
4878 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004879 oldPackage = mPackages.get(pkgName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004880 if (checkSignaturesLP(pkg.mSignatures, oldPackage.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004881 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
4883 return;
4884 }
4885 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07004886 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004887 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004888 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004890 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 }
4892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004895 PackageParser.Package pkg,
4896 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004897 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004898 PackageParser.Package newPackage = null;
4899 String pkgName = deletedPackage.packageName;
4900 boolean deletedPkg = true;
4901 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004902
Jacek Surazski65e13172009-04-28 15:26:38 +02004903 String oldInstallerPackageName = null;
4904 synchronized (mPackages) {
4905 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
4906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004907
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004908 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004911 res.removedInfo)) {
4912 // If the existing package was'nt successfully deleted
4913 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4914 deletedPkg = false;
4915 } else {
4916 // Successfully deleted the old package. Now proceed with re-installation
4917 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004918 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004920 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004921 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
4922 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08004923 }
4924 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004925 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02004926 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 res);
4928 updatedSettings = true;
4929 }
4930 }
4931
4932 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
4933 // If we deleted an exisiting package, the old source and resource files that we
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004934 // were keeping around in case we needed them (see below) can now be deleted.
4935 // This info will be set on the res.removedInfo to clean up later on as post
4936 // install action.
4937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 //update signature on the new package setting
4939 //this should always succeed, since we checked the
4940 //signature earlier.
4941 synchronized(mPackages) {
4942 verifySignaturesLP(mSettings.mPackages.get(pkgName), pkg,
4943 parseFlags, true);
4944 }
4945 } else {
4946 // remove package from internal structures. Note that we want deletePackageX to
4947 // delete the package data and cache directories that it created in
4948 // scanPackageLocked, unless those directories existed before we even tried to
4949 // install.
4950 if(updatedSettings) {
4951 deletePackageLI(
4952 pkgName, true,
4953 PackageManager.DONT_DELETE_DATA,
4954 res.removedInfo);
4955 }
4956 // Since we failed to install the new package we need to restore the old
4957 // package that we deleted.
4958 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004959 File restoreFile = new File(deletedPackage.mPath);
4960 if (restoreFile == null) {
4961 Log.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
4962 return;
4963 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004964 PackageInstalledInfo restoreRes = new PackageInstalledInfo();
4965 restoreRes.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004966 // Parse old package
4967 parseFlags |= ~PackageManager.INSTALL_REPLACE_EXISTING;
4968 scanPackageLI(restoreFile, parseFlags, scanMode);
4969 synchronized (mPackages) {
4970 grantPermissionsLP(deletedPackage, false);
4971 mSettings.writeLP();
4972 }
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004973 if (restoreRes.returnCode != PackageManager.INSTALL_SUCCEEDED) {
4974 Log.e(TAG, "Failed restoring pkg : " + pkgName + " after failed upgrade");
4975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
4977 }
4978 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004980 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004981 PackageParser.Package pkg,
4982 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02004983 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 PackageParser.Package newPackage = null;
4985 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004986 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004987 PackageParser.PARSE_IS_SYSTEM;
4988 String packageName = deletedPackage.packageName;
4989 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
4990 if (packageName == null) {
4991 Log.w(TAG, "Attempt to delete null packageName.");
4992 return;
4993 }
4994 PackageParser.Package oldPkg;
4995 PackageSetting oldPkgSetting;
4996 synchronized (mPackages) {
4997 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004998 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5000 (oldPkgSetting == null)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005001 Log.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 return;
5003 }
5004 }
5005 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5006 res.removedInfo.removedPackage = packageName;
5007 // Remove existing system package
5008 removePackageLI(oldPkg, true);
5009 synchronized (mPackages) {
5010 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5011 }
5012
5013 // Successfully disabled the old package. Now proceed with re-installation
5014 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5015 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005016 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 if (newPackage == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005018 Log.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5020 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5021 }
5022 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005023 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 updatedSettings = true;
5025 }
5026
5027 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
5028 //update signature on the new package setting
5029 //this should always succeed, since we checked the
5030 //signature earlier.
5031 synchronized(mPackages) {
5032 verifySignaturesLP(mSettings.mPackages.get(packageName), pkg,
5033 parseFlags, true);
5034 }
5035 } else {
5036 // Re installation failed. Restore old information
5037 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005038 if (newPackage != null) {
5039 removePackageLI(newPackage, true);
5040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005041 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005042 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005044 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 // Restore the old system information in Settings
5046 synchronized(mPackages) {
5047 if(updatedSettings) {
5048 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005049 mSettings.setInstallerPackageName(packageName,
5050 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 }
5052 mSettings.writeLP();
5053 }
5054 }
5055 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005056
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005057 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005058 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005059 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 synchronized (mPackages) {
5061 //write settings. the installStatus will be incomplete at this stage.
5062 //note that the new package setting would have already been
5063 //added to mPackages. It hasn't been persisted yet.
5064 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5065 mSettings.writeLP();
5066 }
5067
5068 int retCode = 0;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005069 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5070 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005072 Log.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5074 return;
5075 }
5076 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005077 res.returnCode = setPermissionsLI(newPackage);
5078 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5079 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005081 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 }
5083 if(res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5084 if (mInstaller != null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005085 mInstaller.rmdex(newPackage.mScanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 }
5087 }
5088
5089 synchronized (mPackages) {
5090 grantPermissionsLP(newPackage, true);
5091 res.name = pkgName;
5092 res.uid = newPackage.applicationInfo.uid;
5093 res.pkg = newPackage;
5094 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005095 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5097 //to update install status
5098 mSettings.writeLP();
5099 }
5100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005101
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 private void installPackageLI(InstallArgs args,
5103 boolean newInstall, PackageInstalledInfo res) {
5104 int pFlags = args.flags;
5105 String installerPackageName = args.installerPackageName;
5106 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005107 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
5108 boolean onSd = ((pFlags & PackageManager.INSTALL_ON_SDCARD) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005109 boolean replace = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005110 int scanMode = SCAN_MONITOR | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
5111 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005112 // Result object to be returned
5113 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5114
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005115 // Retrieve PackageSettings and parse package
5116 int parseFlags = PackageParser.PARSE_CHATTY |
5117 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5118 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5119 parseFlags |= mDefParseFlags;
5120 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5121 pp.setSeparateProcesses(mSeparateProcesses);
5122 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5123 null, mMetrics, parseFlags);
5124 if (pkg == null) {
5125 res.returnCode = pp.getParseError();
5126 return;
5127 }
5128 String pkgName = res.name = pkg.packageName;
5129 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5130 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5131 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5132 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005133 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005134 }
5135 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5136 res.returnCode = pp.getParseError();
5137 return;
5138 }
5139 // Some preinstall checks
5140 if (forwardLocked && onSd) {
5141 // Make sure forward locked apps can only be installed
5142 // on internal storage
5143 Log.w(TAG, "Cannot install protected apps on sdcard");
5144 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5145 return;
5146 }
5147 // Get rid of all references to package scan path via parser.
5148 pp = null;
5149 String oldCodePath = null;
5150 boolean systemApp = false;
5151 synchronized (mPackages) {
5152 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005153 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5154 String oldName = mSettings.mRenamedPackages.get(pkgName);
5155 if (oldName != null && oldName.equals(pkg.mOriginalPackage)
5156 && mPackages.containsKey(oldName)) {
5157 // This package is derived from an original package,
5158 // and this device has been updating from that original
5159 // name. We must continue using the original name, so
5160 // rename the new package here.
5161 pkg.setPackageName(pkg.mOriginalPackage);
5162 pkgName = pkg.packageName;
5163 replace = true;
5164 } else if (mPackages.containsKey(pkgName)) {
5165 // This package, under its official name, already exists
5166 // on the device; we should replace it.
5167 replace = true;
5168 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005169 }
5170 PackageSetting ps = mSettings.mPackages.get(pkgName);
5171 if (ps != null) {
5172 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5173 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5174 systemApp = (ps.pkg.applicationInfo.flags &
5175 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005176 }
5177 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005179
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005180 if (systemApp && onSd) {
5181 // Disable updates to system apps on sdcard
5182 Log.w(TAG, "Cannot install updates to system apps on sdcard");
5183 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5184 return;
5185 }
5186 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5187 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5188 return;
5189 }
5190 // Set application objects path explicitly after the rename
5191 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005192 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005193 replacePackageLI(pkg, parseFlags, scanMode,
5194 installerPackageName, res);
5195 } else {
5196 installNewPackageLI(pkg, parseFlags, scanMode,
5197 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 }
5199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005200
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005201 private int setPermissionsLI(PackageParser.Package newPackage) {
5202 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 int retCode = 0;
5204 // TODO Gross hack but fix later. Ideally move this to be a post installation
5205 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005206 if ((newPackage.applicationInfo.flags
5207 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
5208 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 try {
5210 extractPublicFiles(newPackage, destResourceFile);
5211 } catch (IOException e) {
5212 Log.e(TAG, "Couldn't create a new zip file for the public parts of a" +
5213 " forward-locked app.");
5214 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5215 } finally {
5216 //TODO clean up the extracted public files
5217 }
5218 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005219 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005220 newPackage.applicationInfo.uid);
5221 } else {
5222 final int filePermissions =
5223 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005224 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 newPackage.applicationInfo.uid);
5226 }
5227 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005228 // The permissions on the resource file was set when it was copied for
5229 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 if (retCode != 0) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005233 Log.e(TAG, "Couldn't set new package file permissions for " +
5234 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005236 // TODO Define new internal error
5237 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005238 }
5239 return PackageManager.INSTALL_SUCCEEDED;
5240 }
5241
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005242 private boolean isForwardLocked(PackageParser.Package pkg) {
5243 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 }
5245
5246 private void extractPublicFiles(PackageParser.Package newPackage,
5247 File publicZipFile) throws IOException {
5248 final ZipOutputStream publicZipOutStream =
5249 new ZipOutputStream(new FileOutputStream(publicZipFile));
5250 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5251
5252 // Copy manifest, resources.arsc and res directory to public zip
5253
5254 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5255 while (privateZipEntries.hasMoreElements()) {
5256 final ZipEntry zipEntry = privateZipEntries.nextElement();
5257 final String zipEntryName = zipEntry.getName();
5258 if ("AndroidManifest.xml".equals(zipEntryName)
5259 || "resources.arsc".equals(zipEntryName)
5260 || zipEntryName.startsWith("res/")) {
5261 try {
5262 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5263 } catch (IOException e) {
5264 try {
5265 publicZipOutStream.close();
5266 throw e;
5267 } finally {
5268 publicZipFile.delete();
5269 }
5270 }
5271 }
5272 }
5273
5274 publicZipOutStream.close();
5275 FileUtils.setPermissions(
5276 publicZipFile.getAbsolutePath(),
5277 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5278 -1, -1);
5279 }
5280
5281 private static void copyZipEntry(ZipEntry zipEntry,
5282 ZipFile inZipFile,
5283 ZipOutputStream outZipStream) throws IOException {
5284 byte[] buffer = new byte[4096];
5285 int num;
5286
5287 ZipEntry newEntry;
5288 if (zipEntry.getMethod() == ZipEntry.STORED) {
5289 // Preserve the STORED method of the input entry.
5290 newEntry = new ZipEntry(zipEntry);
5291 } else {
5292 // Create a new entry so that the compressed len is recomputed.
5293 newEntry = new ZipEntry(zipEntry.getName());
5294 }
5295 outZipStream.putNextEntry(newEntry);
5296
5297 InputStream data = inZipFile.getInputStream(zipEntry);
5298 while ((num = data.read(buffer)) > 0) {
5299 outZipStream.write(buffer, 0, num);
5300 }
5301 outZipStream.flush();
5302 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 private void deleteTempPackageFiles() {
5305 FilenameFilter filter = new FilenameFilter() {
5306 public boolean accept(File dir, String name) {
5307 return name.startsWith("vmdl") && name.endsWith(".tmp");
5308 }
5309 };
5310 String tmpFilesList[] = mAppInstallDir.list(filter);
5311 if(tmpFilesList == null) {
5312 return;
5313 }
5314 for(int i = 0; i < tmpFilesList.length; i++) {
5315 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5316 tmpFile.delete();
5317 }
5318 }
5319
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005320 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 File tmpPackageFile;
5322 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005323 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005324 } catch (IOException e) {
5325 Log.e(TAG, "Couldn't create temp file for downloaded package file.");
5326 return null;
5327 }
5328 try {
5329 FileUtils.setPermissions(
5330 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5331 -1, -1);
5332 } catch (IOException e) {
5333 Log.e(TAG, "Trouble getting the canoncical path for a temp file.");
5334 return null;
5335 }
5336 return tmpPackageFile;
5337 }
5338
5339 public void deletePackage(final String packageName,
5340 final IPackageDeleteObserver observer,
5341 final int flags) {
5342 mContext.enforceCallingOrSelfPermission(
5343 android.Manifest.permission.DELETE_PACKAGES, null);
5344 // Queue up an async operation since the package deletion may take a little while.
5345 mHandler.post(new Runnable() {
5346 public void run() {
5347 mHandler.removeCallbacks(this);
5348 final boolean succeded = deletePackageX(packageName, true, true, flags);
5349 if (observer != null) {
5350 try {
5351 observer.packageDeleted(succeded);
5352 } catch (RemoteException e) {
5353 Log.i(TAG, "Observer no longer exists.");
5354 } //end catch
5355 } //end if
5356 } //end run
5357 });
5358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 /**
5361 * This method is an internal method that could be get invoked either
5362 * to delete an installed package or to clean up a failed installation.
5363 * After deleting an installed package, a broadcast is sent to notify any
5364 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005365 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 * installation wouldn't have sent the initial broadcast either
5367 * The key steps in deleting a package are
5368 * deleting the package information in internal structures like mPackages,
5369 * deleting the packages base directories through installd
5370 * updating mSettings to reflect current status
5371 * persisting settings for later use
5372 * sending a broadcast if necessary
5373 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5375 boolean deleteCodeAndResources, int flags) {
5376 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005377 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378
5379 synchronized (mInstallLock) {
5380 res = deletePackageLI(packageName, deleteCodeAndResources, flags, info);
5381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07005384 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
5385 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
5386
5387 // If the removed package was a system update, the old system packaged
5388 // was re-enabled; we need to broadcast this information
5389 if (systemUpdate) {
5390 Bundle extras = new Bundle(1);
5391 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
5392 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5393
5394 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras);
5395 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras);
5396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005398 // Delete the resources here after sending the broadcast to let
5399 // other processes clean up before deleting resources.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005400 if (info.args != null) {
5401 synchronized (mInstallLock) {
5402 info.args.doPostDeleteLI(deleteCodeAndResources);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005403 }
5404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 return res;
5406 }
5407
5408 static class PackageRemovedInfo {
5409 String removedPackage;
5410 int uid = -1;
5411 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07005412 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005413 // Clean up resources deleted packages.
5414 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07005415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 void sendBroadcast(boolean fullRemove, boolean replacing) {
5417 Bundle extras = new Bundle(1);
5418 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
5419 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
5420 if (replacing) {
5421 extras.putBoolean(Intent.EXTRA_REPLACING, true);
5422 }
5423 if (removedPackage != null) {
5424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras);
5425 }
5426 if (removedUid >= 0) {
5427 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras);
5428 }
5429 }
5430 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 /*
5433 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
5434 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005435 * 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 -08005436 * delete a partially installed application.
5437 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005438 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 int flags) {
5440 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005441 if (outInfo != null) {
5442 outInfo.removedPackage = packageName;
5443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 removePackageLI(p, true);
5445 // Retrieve object to delete permissions for shared user later on
5446 PackageSetting deletedPs;
5447 synchronized (mPackages) {
5448 deletedPs = mSettings.mPackages.get(packageName);
5449 }
5450 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005451 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005453 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 if (retCode < 0) {
5455 Log.w(TAG, "Couldn't remove app data or cache directory for package: "
5456 + packageName + ", retcode=" + retCode);
5457 // we don't consider this to be a failure of the core package deletion
5458 }
5459 } else {
5460 //for emulator
5461 PackageParser.Package pkg = mPackages.get(packageName);
5462 File dataDir = new File(pkg.applicationInfo.dataDir);
5463 dataDir.delete();
5464 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005465 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 synchronized (mPackages) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005467 if (outInfo != null) {
5468 outInfo.removedUid = mSettings.removePackageLP(packageName);
5469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 }
5471 }
5472 synchronized (mPackages) {
5473 if ( (deletedPs != null) && (deletedPs.sharedUser != null)) {
5474 // remove permissions associated with package
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07005475 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 }
5477 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08005478 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 }
5480 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 /*
5483 * Tries to delete system package.
5484 */
5485 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005486 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 ApplicationInfo applicationInfo = p.applicationInfo;
5488 //applicable for non-partially installed applications only
5489 if (applicationInfo == null) {
5490 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5491 return false;
5492 }
5493 PackageSetting ps = null;
5494 // Confirm if the system package has been updated
5495 // An updated system app can be deleted. This will also have to restore
5496 // the system pkg from system partition
5497 synchronized (mPackages) {
5498 ps = mSettings.getDisabledSystemPkg(p.packageName);
5499 }
5500 if (ps == null) {
5501 Log.w(TAG, "Attempt to delete system package "+ p.packageName);
5502 return false;
5503 } else {
5504 Log.i(TAG, "Deleting system pkg from data partition");
5505 }
5506 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07005507 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005508 boolean deleteCodeAndResources = false;
5509 if (ps.versionCode < p.mVersionCode) {
5510 // Delete code and resources for downgrades
5511 deleteCodeAndResources = true;
5512 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5513 flags &= ~PackageManager.DONT_DELETE_DATA;
5514 }
5515 } else {
5516 // Preserve data by setting flag
5517 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
5518 flags |= PackageManager.DONT_DELETE_DATA;
5519 }
5520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
5522 if (!ret) {
5523 return false;
5524 }
5525 synchronized (mPackages) {
5526 // Reinstate the old system package
5527 mSettings.enableSystemPackageLP(p.packageName);
5528 }
5529 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005530 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005532 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 if (newPkg == null) {
5535 Log.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
5536 return false;
5537 }
5538 synchronized (mPackages) {
Suchi Amalapurapu701f5162009-06-03 15:47:55 -07005539 grantPermissionsLP(newPkg, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 mSettings.writeLP();
5541 }
5542 return true;
5543 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 private boolean deleteInstalledPackageLI(PackageParser.Package p,
5546 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5547 ApplicationInfo applicationInfo = p.applicationInfo;
5548 if (applicationInfo == null) {
5549 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5550 return false;
5551 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07005552 if (outInfo != null) {
5553 outInfo.uid = applicationInfo.uid;
5554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555
5556 // Delete package data from internal structures and also remove data if flag is set
5557 removePackageDataLI(p, outInfo, flags);
5558
5559 // Delete application code and resources
5560 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005561 // TODO can pick up from PackageSettings as well
5562 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_ON_SDCARD)!=0) ?
5563 PackageManager.INSTALL_ON_SDCARD : 0;
5564 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
5565 PackageManager.INSTALL_FORWARD_LOCK : 0;
5566 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005567 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 }
5569 return true;
5570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 /*
5573 * This method handles package deletion in general
5574 */
5575 private boolean deletePackageLI(String packageName,
5576 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
5577 if (packageName == null) {
5578 Log.w(TAG, "Attempt to delete null packageName.");
5579 return false;
5580 }
5581 PackageParser.Package p;
5582 boolean dataOnly = false;
5583 synchronized (mPackages) {
5584 p = mPackages.get(packageName);
5585 if (p == null) {
5586 //this retrieves partially installed apps
5587 dataOnly = true;
5588 PackageSetting ps = mSettings.mPackages.get(packageName);
5589 if (ps == null) {
5590 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5591 return false;
5592 }
5593 p = ps.pkg;
5594 }
5595 }
5596 if (p == null) {
5597 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5598 return false;
5599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 if (dataOnly) {
5602 // Delete application data first
5603 removePackageDataLI(p, outInfo, flags);
5604 return true;
5605 }
5606 // At this point the package should have ApplicationInfo associated with it
5607 if (p.applicationInfo == null) {
5608 Log.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
5609 return false;
5610 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005611 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
5613 Log.i(TAG, "Removing system package:"+p.packageName);
5614 // When an updated system application is deleted we delete the existing resources as well and
5615 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005616 ret = deleteSystemPackageLI(p, flags, outInfo);
5617 } else {
5618 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005619 // Kill application pre-emptively especially for apps on sd.
5620 killApplication(packageName, p.applicationInfo.uid);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005621 ret = deleteInstalledPackageLI (p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005623 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 public void clearApplicationUserData(final String packageName,
5627 final IPackageDataObserver observer) {
5628 mContext.enforceCallingOrSelfPermission(
5629 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
5630 // Queue up an async operation since the package deletion may take a little while.
5631 mHandler.post(new Runnable() {
5632 public void run() {
5633 mHandler.removeCallbacks(this);
5634 final boolean succeeded;
5635 synchronized (mInstallLock) {
5636 succeeded = clearApplicationUserDataLI(packageName);
5637 }
5638 if (succeeded) {
5639 // invoke DeviceStorageMonitor's update method to clear any notifications
5640 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
5641 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
5642 if (dsm != null) {
5643 dsm.updateMemory();
5644 }
5645 }
5646 if(observer != null) {
5647 try {
5648 observer.onRemoveCompleted(packageName, succeeded);
5649 } catch (RemoteException e) {
5650 Log.i(TAG, "Observer no longer exists.");
5651 }
5652 } //end if observer
5653 } //end run
5654 });
5655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 private boolean clearApplicationUserDataLI(String packageName) {
5658 if (packageName == null) {
5659 Log.w(TAG, "Attempt to delete null packageName.");
5660 return false;
5661 }
5662 PackageParser.Package p;
5663 boolean dataOnly = false;
5664 synchronized (mPackages) {
5665 p = mPackages.get(packageName);
5666 if(p == null) {
5667 dataOnly = true;
5668 PackageSetting ps = mSettings.mPackages.get(packageName);
5669 if((ps == null) || (ps.pkg == null)) {
5670 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5671 return false;
5672 }
5673 p = ps.pkg;
5674 }
5675 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005676 boolean useEncryptedFSDir = false;
5677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 if(!dataOnly) {
5679 //need to check this only for fully installed applications
5680 if (p == null) {
5681 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5682 return false;
5683 }
5684 final ApplicationInfo applicationInfo = p.applicationInfo;
5685 if (applicationInfo == null) {
5686 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5687 return false;
5688 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005689 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 }
5691 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005692 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 if (retCode < 0) {
5694 Log.w(TAG, "Couldn't remove cache files for package: "
5695 + packageName);
5696 return false;
5697 }
5698 }
5699 return true;
5700 }
5701
5702 public void deleteApplicationCacheFiles(final String packageName,
5703 final IPackageDataObserver observer) {
5704 mContext.enforceCallingOrSelfPermission(
5705 android.Manifest.permission.DELETE_CACHE_FILES, null);
5706 // Queue up an async operation since the package deletion may take a little while.
5707 mHandler.post(new Runnable() {
5708 public void run() {
5709 mHandler.removeCallbacks(this);
5710 final boolean succeded;
5711 synchronized (mInstallLock) {
5712 succeded = deleteApplicationCacheFilesLI(packageName);
5713 }
5714 if(observer != null) {
5715 try {
5716 observer.onRemoveCompleted(packageName, succeded);
5717 } catch (RemoteException e) {
5718 Log.i(TAG, "Observer no longer exists.");
5719 }
5720 } //end if observer
5721 } //end run
5722 });
5723 }
5724
5725 private boolean deleteApplicationCacheFilesLI(String packageName) {
5726 if (packageName == null) {
5727 Log.w(TAG, "Attempt to delete null packageName.");
5728 return false;
5729 }
5730 PackageParser.Package p;
5731 synchronized (mPackages) {
5732 p = mPackages.get(packageName);
5733 }
5734 if (p == null) {
5735 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5736 return false;
5737 }
5738 final ApplicationInfo applicationInfo = p.applicationInfo;
5739 if (applicationInfo == null) {
5740 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5741 return false;
5742 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005743 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08005745 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 if (retCode < 0) {
5747 Log.w(TAG, "Couldn't remove cache files for package: "
5748 + packageName);
5749 return false;
5750 }
5751 }
5752 return true;
5753 }
5754
5755 public void getPackageSizeInfo(final String packageName,
5756 final IPackageStatsObserver observer) {
5757 mContext.enforceCallingOrSelfPermission(
5758 android.Manifest.permission.GET_PACKAGE_SIZE, null);
5759 // Queue up an async operation since the package deletion may take a little while.
5760 mHandler.post(new Runnable() {
5761 public void run() {
5762 mHandler.removeCallbacks(this);
5763 PackageStats lStats = new PackageStats(packageName);
5764 final boolean succeded;
5765 synchronized (mInstallLock) {
5766 succeded = getPackageSizeInfoLI(packageName, lStats);
5767 }
5768 if(observer != null) {
5769 try {
5770 observer.onGetStatsCompleted(lStats, succeded);
5771 } catch (RemoteException e) {
5772 Log.i(TAG, "Observer no longer exists.");
5773 }
5774 } //end if observer
5775 } //end run
5776 });
5777 }
5778
5779 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
5780 if (packageName == null) {
5781 Log.w(TAG, "Attempt to get size of null packageName.");
5782 return false;
5783 }
5784 PackageParser.Package p;
5785 boolean dataOnly = false;
5786 synchronized (mPackages) {
5787 p = mPackages.get(packageName);
5788 if(p == null) {
5789 dataOnly = true;
5790 PackageSetting ps = mSettings.mPackages.get(packageName);
5791 if((ps == null) || (ps.pkg == null)) {
5792 Log.w(TAG, "Package named '" + packageName +"' doesn't exist.");
5793 return false;
5794 }
5795 p = ps.pkg;
5796 }
5797 }
5798 String publicSrcDir = null;
5799 if(!dataOnly) {
5800 final ApplicationInfo applicationInfo = p.applicationInfo;
5801 if (applicationInfo == null) {
5802 Log.w(TAG, "Package " + packageName + " has no applicationInfo.");
5803 return false;
5804 }
5805 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
5806 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08005807 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 if (mInstaller != null) {
5809 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08005810 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005811 if (res < 0) {
5812 return false;
5813 } else {
5814 return true;
5815 }
5816 }
5817 return true;
5818 }
5819
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 public void addPackageToPreferred(String packageName) {
5822 mContext.enforceCallingOrSelfPermission(
5823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005824 Log.w(TAG, "addPackageToPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 }
5826
5827 public void removePackageFromPreferred(String packageName) {
5828 mContext.enforceCallingOrSelfPermission(
5829 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005830 Log.w(TAG, "removePackageFromPreferred: no longer implemented");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
5832
5833 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08005834 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
5836
5837 public void addPreferredActivity(IntentFilter filter, int match,
5838 ComponentName[] set, ComponentName activity) {
5839 mContext.enforceCallingOrSelfPermission(
5840 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5841
5842 synchronized (mPackages) {
5843 Log.i(TAG, "Adding preferred activity " + activity + ":");
5844 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5845 mSettings.mPreferredActivities.addFilter(
5846 new PreferredActivity(filter, match, set, activity));
5847 mSettings.writeLP();
5848 }
5849 }
5850
Satish Sampath8dbe6122009-06-02 23:35:54 +01005851 public void replacePreferredActivity(IntentFilter filter, int match,
5852 ComponentName[] set, ComponentName activity) {
5853 mContext.enforceCallingOrSelfPermission(
5854 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5855 if (filter.countActions() != 1) {
5856 throw new IllegalArgumentException(
5857 "replacePreferredActivity expects filter to have only 1 action.");
5858 }
5859 if (filter.countCategories() != 1) {
5860 throw new IllegalArgumentException(
5861 "replacePreferredActivity expects filter to have only 1 category.");
5862 }
5863 if (filter.countDataAuthorities() != 0
5864 || filter.countDataPaths() != 0
5865 || filter.countDataSchemes() != 0
5866 || filter.countDataTypes() != 0) {
5867 throw new IllegalArgumentException(
5868 "replacePreferredActivity expects filter to have no data authorities, " +
5869 "paths, schemes or types.");
5870 }
5871 synchronized (mPackages) {
5872 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5873 String action = filter.getAction(0);
5874 String category = filter.getCategory(0);
5875 while (it.hasNext()) {
5876 PreferredActivity pa = it.next();
5877 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
5878 it.remove();
5879 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
5880 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
5881 }
5882 }
5883 addPreferredActivity(filter, match, set, activity);
5884 }
5885 }
5886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 public void clearPackagePreferredActivities(String packageName) {
5888 mContext.enforceCallingOrSelfPermission(
5889 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
5890
5891 synchronized (mPackages) {
5892 if (clearPackagePreferredActivitiesLP(packageName)) {
5893 mSettings.writeLP();
5894 }
5895 }
5896 }
5897
5898 boolean clearPackagePreferredActivitiesLP(String packageName) {
5899 boolean changed = false;
5900 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5901 while (it.hasNext()) {
5902 PreferredActivity pa = it.next();
5903 if (pa.mActivity.getPackageName().equals(packageName)) {
5904 it.remove();
5905 changed = true;
5906 }
5907 }
5908 return changed;
5909 }
5910
5911 public int getPreferredActivities(List<IntentFilter> outFilters,
5912 List<ComponentName> outActivities, String packageName) {
5913
5914 int num = 0;
5915 synchronized (mPackages) {
5916 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
5917 while (it.hasNext()) {
5918 PreferredActivity pa = it.next();
5919 if (packageName == null
5920 || pa.mActivity.getPackageName().equals(packageName)) {
5921 if (outFilters != null) {
5922 outFilters.add(new IntentFilter(pa));
5923 }
5924 if (outActivities != null) {
5925 outActivities.add(pa.mActivity);
5926 }
5927 }
5928 }
5929 }
5930
5931 return num;
5932 }
5933
5934 public void setApplicationEnabledSetting(String appPackageName,
5935 int newState, int flags) {
5936 setEnabledSetting(appPackageName, null, newState, flags);
5937 }
5938
5939 public void setComponentEnabledSetting(ComponentName componentName,
5940 int newState, int flags) {
5941 setEnabledSetting(componentName.getPackageName(),
5942 componentName.getClassName(), newState, flags);
5943 }
5944
5945 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005946 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
5948 || newState == COMPONENT_ENABLED_STATE_ENABLED
5949 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
5950 throw new IllegalArgumentException("Invalid new component state: "
5951 + newState);
5952 }
5953 PackageSetting pkgSetting;
5954 final int uid = Binder.getCallingUid();
5955 final int permission = mContext.checkCallingPermission(
5956 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
5957 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005958 boolean sendNow = false;
5959 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005960 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08005962 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005964 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005966 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005968 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 }
5970 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005971 "Unknown component: " + packageName
5972 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 }
5974 if (!allowedByPermission && (uid != pkgSetting.userId)) {
5975 throw new SecurityException(
5976 "Permission Denial: attempt to change component state from pid="
5977 + Binder.getCallingPid()
5978 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
5979 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005980 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 // We're dealing with an application/package level state change
5982 pkgSetting.enabled = newState;
5983 } else {
5984 // We're dealing with a component level state change
5985 switch (newState) {
5986 case COMPONENT_ENABLED_STATE_ENABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005987 pkgSetting.enableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005988 break;
5989 case COMPONENT_ENABLED_STATE_DISABLED:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005990 pkgSetting.disableComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 break;
5992 case COMPONENT_ENABLED_STATE_DEFAULT:
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005993 pkgSetting.restoreComponentLP(className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 break;
5995 default:
5996 Log.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07005997 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 }
5999 }
6000 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006001 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006002 components = mPendingBroadcasts.get(packageName);
6003 boolean newPackage = components == null;
6004 if (newPackage) {
6005 components = new ArrayList<String>();
6006 }
6007 if (!components.contains(componentName)) {
6008 components.add(componentName);
6009 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006010 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6011 sendNow = true;
6012 // Purge entry from pending broadcast list if another one exists already
6013 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006014 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006015 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006016 if (newPackage) {
6017 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006018 }
6019 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6020 // Schedule a message
6021 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6022 }
6023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 long callingId = Binder.clearCallingIdentity();
6027 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006028 if (sendNow) {
6029 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006030 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 } finally {
6033 Binder.restoreCallingIdentity(callingId);
6034 }
6035 }
6036
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006037 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006038 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6039 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6040 + " components=" + componentNames);
6041 Bundle extras = new Bundle(4);
6042 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6043 String nameList[] = new String[componentNames.size()];
6044 componentNames.toArray(nameList);
6045 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006046 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6047 extras.putInt(Intent.EXTRA_UID, packageUid);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006048 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006049 }
6050
Jacek Surazski65e13172009-04-28 15:26:38 +02006051 public String getInstallerPackageName(String packageName) {
6052 synchronized (mPackages) {
6053 PackageSetting pkg = mSettings.mPackages.get(packageName);
6054 if (pkg == null) {
6055 throw new IllegalArgumentException("Unknown package: " + packageName);
6056 }
6057 return pkg.installerPackageName;
6058 }
6059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 public int getApplicationEnabledSetting(String appPackageName) {
6062 synchronized (mPackages) {
6063 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6064 if (pkg == null) {
6065 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6066 }
6067 return pkg.enabled;
6068 }
6069 }
6070
6071 public int getComponentEnabledSetting(ComponentName componentName) {
6072 synchronized (mPackages) {
6073 final String packageNameStr = componentName.getPackageName();
6074 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6075 if (pkg == null) {
6076 throw new IllegalArgumentException("Unknown component: " + componentName);
6077 }
6078 final String classNameStr = componentName.getClassName();
6079 return pkg.currentEnabledStateLP(classNameStr);
6080 }
6081 }
6082
6083 public void enterSafeMode() {
6084 if (!mSystemReady) {
6085 mSafeMode = true;
6086 }
6087 }
6088
6089 public void systemReady() {
6090 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006091
6092 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006093 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006094 mContext.getContentResolver(),
6095 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006096 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006097 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006098 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 }
6101
6102 public boolean isSafeMode() {
6103 return mSafeMode;
6104 }
6105
6106 public boolean hasSystemUidErrors() {
6107 return mHasSystemUidErrors;
6108 }
6109
6110 static String arrayToString(int[] array) {
6111 StringBuffer buf = new StringBuffer(128);
6112 buf.append('[');
6113 if (array != null) {
6114 for (int i=0; i<array.length; i++) {
6115 if (i > 0) buf.append(", ");
6116 buf.append(array[i]);
6117 }
6118 }
6119 buf.append(']');
6120 return buf.toString();
6121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 @Override
6124 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6125 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6126 != PackageManager.PERMISSION_GRANTED) {
6127 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6128 + Binder.getCallingPid()
6129 + ", uid=" + Binder.getCallingUid()
6130 + " without permission "
6131 + android.Manifest.permission.DUMP);
6132 return;
6133 }
6134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 synchronized (mPackages) {
6136 pw.println("Activity Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006137 mActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 pw.println(" ");
6139 pw.println("Receiver Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006140 mReceivers.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 pw.println(" ");
6142 pw.println("Service Resolver Table:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006143 mServices.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 pw.println(" ");
6145 pw.println("Preferred Activities:");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006146 mSettings.mPreferredActivities.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 pw.println(" ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 pw.println("Permissions:");
6149 {
6150 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006151 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6152 pw.print(Integer.toHexString(System.identityHashCode(p)));
6153 pw.println("):");
6154 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6155 pw.print(" uid="); pw.print(p.uid);
6156 pw.print(" gids="); pw.print(arrayToString(p.gids));
6157 pw.print(" type="); pw.println(p.type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 }
6159 }
6160 pw.println(" ");
6161 pw.println("Packages:");
6162 {
6163 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006164 pw.print(" Package [");
6165 pw.print(ps.realName != null ? ps.realName : ps.name);
6166 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006167 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6168 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006169 if (ps.realName != null) {
6170 pw.print(" compat name="); pw.println(ps.name);
6171 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006172 pw.print(" userId="); pw.print(ps.userId);
6173 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6174 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6175 pw.print(" pkg="); pw.println(ps.pkg);
6176 pw.print(" codePath="); pw.println(ps.codePathString);
6177 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006179 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006180 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006181 pw.print(" supportsScreens=[");
6182 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006183 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006184 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006185 if (!first) pw.print(", ");
6186 first = false;
6187 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006189 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006190 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006191 if (!first) pw.print(", ");
6192 first = false;
6193 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006194 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006195 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006196 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006197 if (!first) pw.print(", ");
6198 first = false;
6199 pw.print("small");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006201 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006202 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006203 if (!first) pw.print(", ");
6204 first = false;
6205 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006206 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006207 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006208 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
6209 if (!first) pw.print(", ");
6210 first = false;
6211 pw.print("anyDensity");
6212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006214 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006215 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
6216 pw.print(" signatures="); pw.println(ps.signatures);
6217 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
6218 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
6219 pw.print(" installStatus="); pw.print(ps.installStatus);
6220 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221 if (ps.disabledComponents.size() > 0) {
6222 pw.println(" disabledComponents:");
6223 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006224 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 }
6226 }
6227 if (ps.enabledComponents.size() > 0) {
6228 pw.println(" enabledComponents:");
6229 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006230 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 }
6232 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006233 if (ps.grantedPermissions.size() > 0) {
6234 pw.println(" grantedPermissions:");
6235 for (String s : ps.grantedPermissions) {
6236 pw.print(" "); pw.println(s);
6237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006239 if (ps.loadedPermissions.size() > 0) {
6240 pw.println(" loadedPermissions:");
6241 for (String s : ps.loadedPermissions) {
6242 pw.print(" "); pw.println(s);
6243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 }
6245 }
6246 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006247 if (mSettings.mRenamedPackages.size() > 0) {
6248 pw.println(" ");
6249 pw.println("Renamed packages:");
6250 for (HashMap.Entry<String, String> e
6251 : mSettings.mRenamedPackages.entrySet()) {
6252 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
6253 pw.println(e.getValue());
6254 }
6255 }
6256 if (mSettings.mDisabledSysPackages.size() > 0) {
6257 pw.println(" ");
6258 pw.println("Hidden system packages:");
6259 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
6260 pw.print(" Package [");
6261 pw.print(ps.realName != null ? ps.realName : ps.name);
6262 pw.print("] (");
6263 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6264 pw.println("):");
6265 if (ps.realName != null) {
6266 pw.print(" compat name="); pw.println(ps.name);
6267 }
6268 pw.print(" userId="); pw.println(ps.userId);
6269 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6270 pw.print(" codePath="); pw.println(ps.codePathString);
6271 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
6272 }
6273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 pw.println(" ");
6275 pw.println("Shared Users:");
6276 {
6277 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006278 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
6279 pw.print(Integer.toHexString(System.identityHashCode(su)));
6280 pw.println("):");
6281 pw.print(" userId="); pw.print(su.userId);
6282 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 pw.println(" grantedPermissions:");
6284 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006285 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
6287 pw.println(" loadedPermissions:");
6288 for (String s : su.loadedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006289 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
6291 }
6292 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 pw.println(" ");
6295 pw.println("Settings parse messages:");
6296 pw.println(mSettings.mReadMessages.toString());
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006297
6298 pw.println(" ");
6299 pw.println("Package warning messages:");
6300 File fname = getSettingsProblemFile();
6301 FileInputStream in;
6302 try {
6303 in = new FileInputStream(fname);
6304 int avail = in.available();
6305 byte[] data = new byte[avail];
6306 in.read(data);
6307 pw.println(new String(data));
6308 } catch (FileNotFoundException e) {
6309 } catch (IOException e) {
6310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006312
6313 synchronized (mProviders) {
6314 pw.println(" ");
6315 pw.println("Registered ContentProviders:");
6316 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006317 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05006318 pw.println(p.toString());
6319 }
6320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 }
6322
6323 static final class BasePermission {
6324 final static int TYPE_NORMAL = 0;
6325 final static int TYPE_BUILTIN = 1;
6326 final static int TYPE_DYNAMIC = 2;
6327
6328 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006329 String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 final int type;
6331 PackageParser.Permission perm;
6332 PermissionInfo pendingInfo;
6333 int uid;
6334 int[] gids;
6335
6336 BasePermission(String _name, String _sourcePackage, int _type) {
6337 name = _name;
6338 sourcePackage = _sourcePackage;
6339 type = _type;
6340 }
6341 }
6342
6343 static class PackageSignatures {
6344 private Signature[] mSignatures;
6345
6346 PackageSignatures(Signature[] sigs) {
6347 assignSignatures(sigs);
6348 }
6349
6350 PackageSignatures() {
6351 }
6352
6353 void writeXml(XmlSerializer serializer, String tagName,
6354 ArrayList<Signature> pastSignatures) throws IOException {
6355 if (mSignatures == null) {
6356 return;
6357 }
6358 serializer.startTag(null, tagName);
6359 serializer.attribute(null, "count",
6360 Integer.toString(mSignatures.length));
6361 for (int i=0; i<mSignatures.length; i++) {
6362 serializer.startTag(null, "cert");
6363 final Signature sig = mSignatures[i];
6364 final int sigHash = sig.hashCode();
6365 final int numPast = pastSignatures.size();
6366 int j;
6367 for (j=0; j<numPast; j++) {
6368 Signature pastSig = pastSignatures.get(j);
6369 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
6370 serializer.attribute(null, "index", Integer.toString(j));
6371 break;
6372 }
6373 }
6374 if (j >= numPast) {
6375 pastSignatures.add(sig);
6376 serializer.attribute(null, "index", Integer.toString(numPast));
6377 serializer.attribute(null, "key", sig.toCharsString());
6378 }
6379 serializer.endTag(null, "cert");
6380 }
6381 serializer.endTag(null, tagName);
6382 }
6383
6384 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
6385 throws IOException, XmlPullParserException {
6386 String countStr = parser.getAttributeValue(null, "count");
6387 if (countStr == null) {
6388 reportSettingsProblem(Log.WARN,
6389 "Error in package manager settings: <signatures> has"
6390 + " no count at " + parser.getPositionDescription());
6391 XmlUtils.skipCurrentTag(parser);
6392 }
6393 final int count = Integer.parseInt(countStr);
6394 mSignatures = new Signature[count];
6395 int pos = 0;
6396
6397 int outerDepth = parser.getDepth();
6398 int type;
6399 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6400 && (type != XmlPullParser.END_TAG
6401 || parser.getDepth() > outerDepth)) {
6402 if (type == XmlPullParser.END_TAG
6403 || type == XmlPullParser.TEXT) {
6404 continue;
6405 }
6406
6407 String tagName = parser.getName();
6408 if (tagName.equals("cert")) {
6409 if (pos < count) {
6410 String index = parser.getAttributeValue(null, "index");
6411 if (index != null) {
6412 try {
6413 int idx = Integer.parseInt(index);
6414 String key = parser.getAttributeValue(null, "key");
6415 if (key == null) {
6416 if (idx >= 0 && idx < pastSignatures.size()) {
6417 Signature sig = pastSignatures.get(idx);
6418 if (sig != null) {
6419 mSignatures[pos] = pastSignatures.get(idx);
6420 pos++;
6421 } else {
6422 reportSettingsProblem(Log.WARN,
6423 "Error in package manager settings: <cert> "
6424 + "index " + index + " is not defined at "
6425 + parser.getPositionDescription());
6426 }
6427 } else {
6428 reportSettingsProblem(Log.WARN,
6429 "Error in package manager settings: <cert> "
6430 + "index " + index + " is out of bounds at "
6431 + parser.getPositionDescription());
6432 }
6433 } else {
6434 while (pastSignatures.size() <= idx) {
6435 pastSignatures.add(null);
6436 }
6437 Signature sig = new Signature(key);
6438 pastSignatures.set(idx, sig);
6439 mSignatures[pos] = sig;
6440 pos++;
6441 }
6442 } catch (NumberFormatException e) {
6443 reportSettingsProblem(Log.WARN,
6444 "Error in package manager settings: <cert> "
6445 + "index " + index + " is not a number at "
6446 + parser.getPositionDescription());
6447 }
6448 } else {
6449 reportSettingsProblem(Log.WARN,
6450 "Error in package manager settings: <cert> has"
6451 + " no index at " + parser.getPositionDescription());
6452 }
6453 } else {
6454 reportSettingsProblem(Log.WARN,
6455 "Error in package manager settings: too "
6456 + "many <cert> tags, expected " + count
6457 + " at " + parser.getPositionDescription());
6458 }
6459 } else {
6460 reportSettingsProblem(Log.WARN,
6461 "Unknown element under <cert>: "
6462 + parser.getName());
6463 }
6464 XmlUtils.skipCurrentTag(parser);
6465 }
6466
6467 if (pos < count) {
6468 // Should never happen -- there is an error in the written
6469 // settings -- but if it does we don't want to generate
6470 // a bad array.
6471 Signature[] newSigs = new Signature[pos];
6472 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
6473 mSignatures = newSigs;
6474 }
6475 }
6476
6477 /**
6478 * If any of the given 'sigs' is contained in the existing signatures,
6479 * then completely replace the current signatures with the ones in
6480 * 'sigs'. This is used for updating an existing package to a newly
6481 * installed version.
6482 */
6483 boolean updateSignatures(Signature[] sigs, boolean update) {
6484 if (mSignatures == null) {
6485 if (update) {
6486 assignSignatures(sigs);
6487 }
6488 return true;
6489 }
6490 if (sigs == null) {
6491 return false;
6492 }
6493
6494 for (int i=0; i<sigs.length; i++) {
6495 Signature sig = sigs[i];
6496 for (int j=0; j<mSignatures.length; j++) {
6497 if (mSignatures[j].equals(sig)) {
6498 if (update) {
6499 assignSignatures(sigs);
6500 }
6501 return true;
6502 }
6503 }
6504 }
6505 return false;
6506 }
6507
6508 /**
6509 * If any of the given 'sigs' is contained in the existing signatures,
6510 * then add in any new signatures found in 'sigs'. This is used for
6511 * including a new package into an existing shared user id.
6512 */
6513 boolean mergeSignatures(Signature[] sigs, boolean update) {
6514 if (mSignatures == null) {
6515 if (update) {
6516 assignSignatures(sigs);
6517 }
6518 return true;
6519 }
6520 if (sigs == null) {
6521 return false;
6522 }
6523
6524 Signature[] added = null;
6525 int addedCount = 0;
6526 boolean haveMatch = false;
6527 for (int i=0; i<sigs.length; i++) {
6528 Signature sig = sigs[i];
6529 boolean found = false;
6530 for (int j=0; j<mSignatures.length; j++) {
6531 if (mSignatures[j].equals(sig)) {
6532 found = true;
6533 haveMatch = true;
6534 break;
6535 }
6536 }
6537
6538 if (!found) {
6539 if (added == null) {
6540 added = new Signature[sigs.length];
6541 }
6542 added[i] = sig;
6543 addedCount++;
6544 }
6545 }
6546
6547 if (!haveMatch) {
6548 // Nothing matched -- reject the new signatures.
6549 return false;
6550 }
6551 if (added == null) {
6552 // Completely matched -- nothing else to do.
6553 return true;
6554 }
6555
6556 // Add additional signatures in.
6557 if (update) {
6558 Signature[] total = new Signature[addedCount+mSignatures.length];
6559 System.arraycopy(mSignatures, 0, total, 0, mSignatures.length);
6560 int j = mSignatures.length;
6561 for (int i=0; i<added.length; i++) {
6562 if (added[i] != null) {
6563 total[j] = added[i];
6564 j++;
6565 }
6566 }
6567 mSignatures = total;
6568 }
6569 return true;
6570 }
6571
6572 private void assignSignatures(Signature[] sigs) {
6573 if (sigs == null) {
6574 mSignatures = null;
6575 return;
6576 }
6577 mSignatures = new Signature[sigs.length];
6578 for (int i=0; i<sigs.length; i++) {
6579 mSignatures[i] = sigs[i];
6580 }
6581 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 @Override
6584 public String toString() {
6585 StringBuffer buf = new StringBuffer(128);
6586 buf.append("PackageSignatures{");
6587 buf.append(Integer.toHexString(System.identityHashCode(this)));
6588 buf.append(" [");
6589 if (mSignatures != null) {
6590 for (int i=0; i<mSignatures.length; i++) {
6591 if (i > 0) buf.append(", ");
6592 buf.append(Integer.toHexString(
6593 System.identityHashCode(mSignatures[i])));
6594 }
6595 }
6596 buf.append("]}");
6597 return buf.toString();
6598 }
6599 }
6600
6601 static class PreferredActivity extends IntentFilter {
6602 final int mMatch;
6603 final String[] mSetPackages;
6604 final String[] mSetClasses;
6605 final String[] mSetComponents;
6606 final ComponentName mActivity;
6607 final String mShortActivity;
6608 String mParseError;
6609
6610 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
6611 ComponentName activity) {
6612 super(filter);
6613 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
6614 mActivity = activity;
6615 mShortActivity = activity.flattenToShortString();
6616 mParseError = null;
6617 if (set != null) {
6618 final int N = set.length;
6619 String[] myPackages = new String[N];
6620 String[] myClasses = new String[N];
6621 String[] myComponents = new String[N];
6622 for (int i=0; i<N; i++) {
6623 ComponentName cn = set[i];
6624 if (cn == null) {
6625 mSetPackages = null;
6626 mSetClasses = null;
6627 mSetComponents = null;
6628 return;
6629 }
6630 myPackages[i] = cn.getPackageName().intern();
6631 myClasses[i] = cn.getClassName().intern();
6632 myComponents[i] = cn.flattenToShortString().intern();
6633 }
6634 mSetPackages = myPackages;
6635 mSetClasses = myClasses;
6636 mSetComponents = myComponents;
6637 } else {
6638 mSetPackages = null;
6639 mSetClasses = null;
6640 mSetComponents = null;
6641 }
6642 }
6643
6644 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
6645 IOException {
6646 mShortActivity = parser.getAttributeValue(null, "name");
6647 mActivity = ComponentName.unflattenFromString(mShortActivity);
6648 if (mActivity == null) {
6649 mParseError = "Bad activity name " + mShortActivity;
6650 }
6651 String matchStr = parser.getAttributeValue(null, "match");
6652 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
6653 String setCountStr = parser.getAttributeValue(null, "set");
6654 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
6655
6656 String[] myPackages = setCount > 0 ? new String[setCount] : null;
6657 String[] myClasses = setCount > 0 ? new String[setCount] : null;
6658 String[] myComponents = setCount > 0 ? new String[setCount] : null;
6659
6660 int setPos = 0;
6661
6662 int outerDepth = parser.getDepth();
6663 int type;
6664 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
6665 && (type != XmlPullParser.END_TAG
6666 || parser.getDepth() > outerDepth)) {
6667 if (type == XmlPullParser.END_TAG
6668 || type == XmlPullParser.TEXT) {
6669 continue;
6670 }
6671
6672 String tagName = parser.getName();
6673 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
6674 // + parser.getDepth() + " tag=" + tagName);
6675 if (tagName.equals("set")) {
6676 String name = parser.getAttributeValue(null, "name");
6677 if (name == null) {
6678 if (mParseError == null) {
6679 mParseError = "No name in set tag in preferred activity "
6680 + mShortActivity;
6681 }
6682 } else if (setPos >= setCount) {
6683 if (mParseError == null) {
6684 mParseError = "Too many set tags in preferred activity "
6685 + mShortActivity;
6686 }
6687 } else {
6688 ComponentName cn = ComponentName.unflattenFromString(name);
6689 if (cn == null) {
6690 if (mParseError == null) {
6691 mParseError = "Bad set name " + name + " in preferred activity "
6692 + mShortActivity;
6693 }
6694 } else {
6695 myPackages[setPos] = cn.getPackageName();
6696 myClasses[setPos] = cn.getClassName();
6697 myComponents[setPos] = name;
6698 setPos++;
6699 }
6700 }
6701 XmlUtils.skipCurrentTag(parser);
6702 } else if (tagName.equals("filter")) {
6703 //Log.i(TAG, "Starting to parse filter...");
6704 readFromXml(parser);
6705 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
6706 // + parser.getDepth() + " tag=" + parser.getName());
6707 } else {
6708 reportSettingsProblem(Log.WARN,
6709 "Unknown element under <preferred-activities>: "
6710 + parser.getName());
6711 XmlUtils.skipCurrentTag(parser);
6712 }
6713 }
6714
6715 if (setPos != setCount) {
6716 if (mParseError == null) {
6717 mParseError = "Not enough set tags (expected " + setCount
6718 + " but found " + setPos + ") in " + mShortActivity;
6719 }
6720 }
6721
6722 mSetPackages = myPackages;
6723 mSetClasses = myClasses;
6724 mSetComponents = myComponents;
6725 }
6726
6727 public void writeToXml(XmlSerializer serializer) throws IOException {
6728 final int NS = mSetClasses != null ? mSetClasses.length : 0;
6729 serializer.attribute(null, "name", mShortActivity);
6730 serializer.attribute(null, "match", Integer.toHexString(mMatch));
6731 serializer.attribute(null, "set", Integer.toString(NS));
6732 for (int s=0; s<NS; s++) {
6733 serializer.startTag(null, "set");
6734 serializer.attribute(null, "name", mSetComponents[s]);
6735 serializer.endTag(null, "set");
6736 }
6737 serializer.startTag(null, "filter");
6738 super.writeToXml(serializer);
6739 serializer.endTag(null, "filter");
6740 }
6741
6742 boolean sameSet(List<ResolveInfo> query, int priority) {
6743 if (mSetPackages == null) return false;
6744 final int NQ = query.size();
6745 final int NS = mSetPackages.length;
6746 int numMatch = 0;
6747 for (int i=0; i<NQ; i++) {
6748 ResolveInfo ri = query.get(i);
6749 if (ri.priority != priority) continue;
6750 ActivityInfo ai = ri.activityInfo;
6751 boolean good = false;
6752 for (int j=0; j<NS; j++) {
6753 if (mSetPackages[j].equals(ai.packageName)
6754 && mSetClasses[j].equals(ai.name)) {
6755 numMatch++;
6756 good = true;
6757 break;
6758 }
6759 }
6760 if (!good) return false;
6761 }
6762 return numMatch == NS;
6763 }
6764 }
6765
6766 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07006767 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 HashSet<String> grantedPermissions = new HashSet<String>();
6770 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 HashSet<String> loadedPermissions = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08006775 this.pkgFlags = (pkgFlags & ApplicationInfo.FLAG_SYSTEM) |
6776 (pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) |
6777 (pkgFlags & ApplicationInfo.FLAG_ON_SDCARD);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 }
6779 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 /**
6782 * Settings base class for pending and resolved classes.
6783 */
6784 static class PackageSettingBase extends GrantedPermissions {
6785 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006786 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07006787 File codePath;
6788 String codePathString;
6789 File resourcePath;
6790 String resourcePathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006791 private long timeStamp;
6792 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006793 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006795 boolean uidError;
6796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 PackageSignatures signatures = new PackageSignatures();
6798
6799 boolean permissionsFixed;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 /* Explicitly disabled components */
6802 HashSet<String> disabledComponents = new HashSet<String>(0);
6803 /* Explicitly enabled components */
6804 HashSet<String> enabledComponents = new HashSet<String>(0);
6805 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
6806 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006807
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006808 PackageSettingBase origPackage;
6809
Jacek Surazski65e13172009-04-28 15:26:38 +02006810 /* package name of the app that installed this package */
6811 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006812
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006813 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006814 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 super(pkgFlags);
6816 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006817 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006818 init(codePath, resourcePath, pVersionCode);
6819 }
6820
6821 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006822 this.codePath = codePath;
6823 this.codePathString = codePath.toString();
6824 this.resourcePath = resourcePath;
6825 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006826 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08006828
Jacek Surazski65e13172009-04-28 15:26:38 +02006829 public void setInstallerPackageName(String packageName) {
6830 installerPackageName = packageName;
6831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006832
Jacek Surazski65e13172009-04-28 15:26:38 +02006833 String getInstallerPackageName() {
6834 return installerPackageName;
6835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 public void setInstallStatus(int newStatus) {
6838 installStatus = newStatus;
6839 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 public int getInstallStatus() {
6842 return installStatus;
6843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 public void setTimeStamp(long newStamp) {
6846 if (newStamp != timeStamp) {
6847 timeStamp = newStamp;
6848 timeStampString = Long.toString(newStamp);
6849 }
6850 }
6851
6852 public void setTimeStamp(long newStamp, String newStampStr) {
6853 timeStamp = newStamp;
6854 timeStampString = newStampStr;
6855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 public long getTimeStamp() {
6858 return timeStamp;
6859 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 public String getTimeStampStr() {
6862 return timeStampString;
6863 }
6864
6865 public void copyFrom(PackageSettingBase base) {
6866 grantedPermissions = base.grantedPermissions;
6867 gids = base.gids;
6868 loadedPermissions = base.loadedPermissions;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870 timeStamp = base.timeStamp;
6871 timeStampString = base.timeStampString;
6872 signatures = base.signatures;
6873 permissionsFixed = base.permissionsFixed;
6874 disabledComponents = base.disabledComponents;
6875 enabledComponents = base.enabledComponents;
6876 enabled = base.enabled;
6877 installStatus = base.installStatus;
6878 }
6879
6880 void enableComponentLP(String componentClassName) {
6881 disabledComponents.remove(componentClassName);
6882 enabledComponents.add(componentClassName);
6883 }
6884
6885 void disableComponentLP(String componentClassName) {
6886 enabledComponents.remove(componentClassName);
6887 disabledComponents.add(componentClassName);
6888 }
6889
6890 void restoreComponentLP(String componentClassName) {
6891 enabledComponents.remove(componentClassName);
6892 disabledComponents.remove(componentClassName);
6893 }
6894
6895 int currentEnabledStateLP(String componentName) {
6896 if (enabledComponents.contains(componentName)) {
6897 return COMPONENT_ENABLED_STATE_ENABLED;
6898 } else if (disabledComponents.contains(componentName)) {
6899 return COMPONENT_ENABLED_STATE_DISABLED;
6900 } else {
6901 return COMPONENT_ENABLED_STATE_DEFAULT;
6902 }
6903 }
6904 }
6905
6906 /**
6907 * Settings data for a particular package we know about.
6908 */
6909 static final class PackageSetting extends PackageSettingBase {
6910 int userId;
6911 PackageParser.Package pkg;
6912 SharedUserSetting sharedUser;
6913
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006914 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006915 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006916 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 @Override
6920 public String toString() {
6921 return "PackageSetting{"
6922 + Integer.toHexString(System.identityHashCode(this))
6923 + " " + name + "/" + userId + "}";
6924 }
6925 }
6926
6927 /**
6928 * Settings data for a particular shared user ID we know about.
6929 */
6930 static final class SharedUserSetting extends GrantedPermissions {
6931 final String name;
6932 int userId;
6933 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
6934 final PackageSignatures signatures = new PackageSignatures();
6935
6936 SharedUserSetting(String _name, int _pkgFlags) {
6937 super(_pkgFlags);
6938 name = _name;
6939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006941 @Override
6942 public String toString() {
6943 return "SharedUserSetting{"
6944 + Integer.toHexString(System.identityHashCode(this))
6945 + " " + name + "/" + userId + "}";
6946 }
6947 }
6948
6949 /**
6950 * Holds information about dynamic settings.
6951 */
6952 private static final class Settings {
6953 private final File mSettingsFilename;
6954 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08006955 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956 private final HashMap<String, PackageSetting> mPackages =
6957 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 // List of replaced system applications
6959 final HashMap<String, PackageSetting> mDisabledSysPackages =
6960 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006961
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 // The user's preferred activities associated with particular intent
6963 // filters.
6964 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
6965 new IntentResolver<PreferredActivity, PreferredActivity>() {
6966 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006967 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006968 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006969 out.print(prefix); out.print(
6970 Integer.toHexString(System.identityHashCode(filter)));
6971 out.print(' ');
6972 out.print(filter.mActivity.flattenToShortString());
6973 out.print(" match=0x");
6974 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006976 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006977 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006978 out.print(prefix); out.print(" ");
6979 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 }
6981 }
6982 }
6983 };
6984 private final HashMap<String, SharedUserSetting> mSharedUsers =
6985 new HashMap<String, SharedUserSetting>();
6986 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
6987 private final SparseArray<Object> mOtherUserIds =
6988 new SparseArray<Object>();
6989
6990 // For reading/writing settings file.
6991 private final ArrayList<Signature> mPastSignatures =
6992 new ArrayList<Signature>();
6993
6994 // Mapping from permission names to info about them.
6995 final HashMap<String, BasePermission> mPermissions =
6996 new HashMap<String, BasePermission>();
6997
6998 // Mapping from permission tree names to info about them.
6999 final HashMap<String, BasePermission> mPermissionTrees =
7000 new HashMap<String, BasePermission>();
7001
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007002 // Packages that have been uninstalled and still need their external
7003 // storage data deleted.
7004 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7005
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007006 // Packages that have been renamed since they were first installed.
7007 // Keys are the new names of the packages, values are the original
7008 // names. The packages appear everwhere else under their original
7009 // names.
7010 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 private final StringBuilder mReadMessages = new StringBuilder();
7013
7014 private static final class PendingPackage extends PackageSettingBase {
7015 final int sharedId;
7016
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007017 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007018 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007019 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 this.sharedId = sharedId;
7021 }
7022 }
7023 private final ArrayList<PendingPackage> mPendingPackages
7024 = new ArrayList<PendingPackage>();
7025
7026 Settings() {
7027 File dataDir = Environment.getDataDirectory();
7028 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007029 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7030 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007032 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 FileUtils.setPermissions(systemDir.toString(),
7034 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7035 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7036 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007037 FileUtils.setPermissions(systemSecureDir.toString(),
7038 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7039 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7040 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 mSettingsFilename = new File(systemDir, "packages.xml");
7042 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007043 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 }
7045
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007046 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007047 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 int pkgFlags, boolean create, boolean add) {
7049 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007050 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007051 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 return p;
7053 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007054
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007055 PackageSetting peekPackageLP(String name) {
7056 return mPackages.get(name);
7057 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 PackageSetting p = mPackages.get(name);
7059 if (p != null && p.codePath.getPath().equals(codePath)) {
7060 return p;
7061 }
7062 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007063 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 void setInstallStatus(String pkgName, int status) {
7067 PackageSetting p = mPackages.get(pkgName);
7068 if(p != null) {
7069 if(p.getInstallStatus() != status) {
7070 p.setInstallStatus(status);
7071 }
7072 }
7073 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007074
Jacek Surazski65e13172009-04-28 15:26:38 +02007075 void setInstallerPackageName(String pkgName,
7076 String installerPkgName) {
7077 PackageSetting p = mPackages.get(pkgName);
7078 if(p != null) {
7079 p.setInstallerPackageName(installerPkgName);
7080 }
7081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007082
Jacek Surazski65e13172009-04-28 15:26:38 +02007083 String getInstallerPackageName(String pkgName) {
7084 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007085 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007086 }
7087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 int getInstallStatus(String pkgName) {
7089 PackageSetting p = mPackages.get(pkgName);
7090 if(p != null) {
7091 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007093 return -1;
7094 }
7095
7096 SharedUserSetting getSharedUserLP(String name,
7097 int pkgFlags, boolean create) {
7098 SharedUserSetting s = mSharedUsers.get(name);
7099 if (s == null) {
7100 if (!create) {
7101 return null;
7102 }
7103 s = new SharedUserSetting(name, pkgFlags);
7104 if (MULTIPLE_APPLICATION_UIDS) {
7105 s.userId = newUserIdLP(s);
7106 } else {
7107 s.userId = FIRST_APPLICATION_UID;
7108 }
7109 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7110 // < 0 means we couldn't assign a userid; fall out and return
7111 // s, which is currently null
7112 if (s.userId >= 0) {
7113 mSharedUsers.put(name, s);
7114 }
7115 }
7116
7117 return s;
7118 }
7119
7120 int disableSystemPackageLP(String name) {
7121 PackageSetting p = mPackages.get(name);
7122 if(p == null) {
7123 Log.w(TAG, "Package:"+name+" is not an installed package");
7124 return -1;
7125 }
7126 PackageSetting dp = mDisabledSysPackages.get(name);
7127 // always make sure the system package code and resource paths dont change
7128 if(dp == null) {
7129 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7130 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7131 }
7132 mDisabledSysPackages.put(name, p);
7133 }
7134 return removePackageLP(name);
7135 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 PackageSetting enableSystemPackageLP(String name) {
7138 PackageSetting p = mDisabledSysPackages.get(name);
7139 if(p == null) {
7140 Log.w(TAG, "Package:"+name+" is not disabled");
7141 return null;
7142 }
7143 // Reset flag in ApplicationInfo object
7144 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7145 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7146 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007147 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007148 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 mDisabledSysPackages.remove(name);
7150 return ret;
7151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007152
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007153 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007154 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 PackageSetting p = mPackages.get(name);
7156 if (p != null) {
7157 if (p.userId == uid) {
7158 return p;
7159 }
7160 reportSettingsProblem(Log.ERROR,
7161 "Adding duplicate package, keeping first: " + name);
7162 return null;
7163 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007164 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007165 p.userId = uid;
7166 if (addUserIdLP(uid, p, name)) {
7167 mPackages.put(name, p);
7168 return p;
7169 }
7170 return null;
7171 }
7172
7173 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7174 SharedUserSetting s = mSharedUsers.get(name);
7175 if (s != null) {
7176 if (s.userId == uid) {
7177 return s;
7178 }
7179 reportSettingsProblem(Log.ERROR,
7180 "Adding duplicate shared user, keeping first: " + name);
7181 return null;
7182 }
7183 s = new SharedUserSetting(name, pkgFlags);
7184 s.userId = uid;
7185 if (addUserIdLP(uid, s, name)) {
7186 mSharedUsers.put(name, s);
7187 return s;
7188 }
7189 return null;
7190 }
7191
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007192 // Transfer ownership of permissions from one package to another.
7193 private void transferPermissions(String origPkg, String newPkg) {
7194 // Transfer ownership of permissions to the new package.
7195 for (int i=0; i<2; i++) {
7196 HashMap<String, BasePermission> permissions =
7197 i == 0 ? mPermissionTrees : mPermissions;
7198 for (BasePermission bp : permissions.values()) {
7199 if (origPkg.equals(bp.sourcePackage)) {
7200 if (DEBUG_UPGRADE) Log.v(TAG,
7201 "Moving permission " + bp.name
7202 + " from pkg " + bp.sourcePackage
7203 + " to " + newPkg);
7204 bp.sourcePackage = newPkg;
7205 bp.perm = null;
7206 if (bp.pendingInfo != null) {
7207 bp.sourcePackage = newPkg;
7208 }
7209 bp.uid = 0;
7210 bp.gids = null;
7211 }
7212 }
7213 }
7214 }
7215
7216 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007217 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007218 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 PackageSetting p = mPackages.get(name);
7220 if (p != null) {
7221 if (!p.codePath.equals(codePath)) {
7222 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007223 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007224 // This is an updated system app with versions in both system
7225 // and data partition. Just let the most recent version
7226 // take precedence.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007227 Log.w(TAG, "Trying to update system app code path from " +
7228 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007229 } else {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007230 // Let the app continue with previous uid if code path changes.
The Android Open Source Projectba87e3e2009-03-13 13:04:22 -07007231 reportSettingsProblem(Log.WARN,
7232 "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007233 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007235 }
7236 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 reportSettingsProblem(Log.WARN,
7238 "Package " + name + " shared user changed from "
7239 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
7240 + " to "
7241 + (sharedUser != null ? sharedUser.name : "<nothing>")
7242 + "; replacing with new");
7243 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007244 } else {
7245 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7246 // If what we are scanning is a system package, then
7247 // make it so, regardless of whether it was previously
7248 // installed only in the data partition.
7249 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
7250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007251 }
7252 }
7253 if (p == null) {
7254 // Create a new PackageSettings entry. this can end up here because
7255 // of code path mismatch or user id mismatch of an updated system partition
7256 if (!create) {
7257 return null;
7258 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007259 if (origPackage != null) {
7260 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007261 p = new PackageSetting(origPackage.name, name, codePath,
7262 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007263 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
7264 + " is adopting original package " + origPackage.name);
7265 p.copyFrom(origPackage);
7266 p.sharedUser = origPackage.sharedUser;
7267 p.userId = origPackage.userId;
7268 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007269 mRenamedPackages.put(name, origPackage.name);
7270 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007271 // Update new package state.
7272 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007274 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007275 p.setTimeStamp(codePath.lastModified());
7276 p.sharedUser = sharedUser;
7277 if (sharedUser != null) {
7278 p.userId = sharedUser.userId;
7279 } else if (MULTIPLE_APPLICATION_UIDS) {
7280 // Clone the setting here for disabled system packages
7281 PackageSetting dis = mDisabledSysPackages.get(name);
7282 if (dis != null) {
7283 // For disabled packages a new setting is created
7284 // from the existing user id. This still has to be
7285 // added to list of user id's
7286 // Copy signatures from previous setting
7287 if (dis.signatures.mSignatures != null) {
7288 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
7289 }
7290 p.userId = dis.userId;
7291 // Clone permissions
7292 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
7293 p.loadedPermissions = new HashSet<String>(dis.loadedPermissions);
7294 // Clone component info
7295 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
7296 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
7297 // Add new setting to list of user ids
7298 addUserIdLP(p.userId, p, name);
7299 } else {
7300 // Assign new user id
7301 p.userId = newUserIdLP(p);
7302 }
7303 } else {
7304 p.userId = FIRST_APPLICATION_UID;
7305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 }
7307 if (p.userId < 0) {
7308 reportSettingsProblem(Log.WARN,
7309 "Package " + name + " could not be assigned a valid uid");
7310 return null;
7311 }
7312 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007313 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007315 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 }
7317 }
7318 return p;
7319 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007320
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007321 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007322 p.pkg = pkg;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007323 String codePath = pkg.applicationInfo.sourceDir;
7324 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007325 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007326 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007327 Log.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007328 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007329 p.codePath = new File(codePath);
7330 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007331 }
7332 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007333 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007334 Log.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007335 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08007336 p.resourcePath = new File(resourcePath);
7337 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007338 }
7339 // Update version code if needed
7340 if (pkg.mVersionCode != p.versionCode) {
7341 p.versionCode = pkg.mVersionCode;
7342 }
7343 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
7344 }
7345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 // Utility method that adds a PackageSetting to mPackages and
7347 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007348 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007349 SharedUserSetting sharedUser) {
7350 mPackages.put(name, p);
7351 if (sharedUser != null) {
7352 if (p.sharedUser != null && p.sharedUser != sharedUser) {
7353 reportSettingsProblem(Log.ERROR,
7354 "Package " + p.name + " was user "
7355 + p.sharedUser + " but is now " + sharedUser
7356 + "; I am not changing its files so it will probably fail!");
7357 p.sharedUser.packages.remove(p);
7358 } else if (p.userId != sharedUser.userId) {
7359 reportSettingsProblem(Log.ERROR,
7360 "Package " + p.name + " was user id " + p.userId
7361 + " but is now user " + sharedUser
7362 + " with id " + sharedUser.userId
7363 + "; I am not changing its files so it will probably fail!");
7364 }
7365
7366 sharedUser.packages.add(p);
7367 p.sharedUser = sharedUser;
7368 p.userId = sharedUser.userId;
7369 }
7370 }
7371
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007372 /*
7373 * Update the shared user setting when a package using
7374 * specifying the shared user id is removed. The gids
7375 * associated with each permission of the deleted package
7376 * are removed from the shared user's gid list only if its
7377 * not in use by other permissions of packages in the
7378 * shared user setting.
7379 */
7380 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
7382 Log.i(TAG, "Trying to update info for null package. Just ignoring");
7383 return;
7384 }
7385 // No sharedUserId
7386 if (deletedPs.sharedUser == null) {
7387 return;
7388 }
7389 SharedUserSetting sus = deletedPs.sharedUser;
7390 // Update permissions
7391 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
7392 boolean used = false;
7393 if (!sus.grantedPermissions.contains (eachPerm)) {
7394 continue;
7395 }
7396 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007397 if (pkg.pkg != null &&
7398 !pkg.pkg.packageName.equalsIgnoreCase(deletedPs.pkg.packageName) &&
7399 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 used = true;
7401 break;
7402 }
7403 }
7404 if (!used) {
7405 // can safely delete this permission from list
7406 sus.grantedPermissions.remove(eachPerm);
7407 sus.loadedPermissions.remove(eachPerm);
7408 }
7409 }
7410 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007411 int newGids[] = globalGids;
7412 for (String eachPerm : sus.grantedPermissions) {
7413 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07007414 if (bp != null) {
7415 newGids = appendInts(newGids, bp.gids);
7416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007417 }
7418 sus.gids = newGids;
7419 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07007420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 private int removePackageLP(String name) {
7422 PackageSetting p = mPackages.get(name);
7423 if (p != null) {
7424 mPackages.remove(name);
7425 if (p.sharedUser != null) {
7426 p.sharedUser.packages.remove(p);
7427 if (p.sharedUser.packages.size() == 0) {
7428 mSharedUsers.remove(p.sharedUser.name);
7429 removeUserIdLP(p.sharedUser.userId);
7430 return p.sharedUser.userId;
7431 }
7432 } else {
7433 removeUserIdLP(p.userId);
7434 return p.userId;
7435 }
7436 }
7437 return -1;
7438 }
7439
7440 private boolean addUserIdLP(int uid, Object obj, Object name) {
7441 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
7442 return false;
7443 }
7444
7445 if (uid >= FIRST_APPLICATION_UID) {
7446 int N = mUserIds.size();
7447 final int index = uid - FIRST_APPLICATION_UID;
7448 while (index >= N) {
7449 mUserIds.add(null);
7450 N++;
7451 }
7452 if (mUserIds.get(index) != null) {
7453 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007454 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007455 + " name=" + name);
7456 return false;
7457 }
7458 mUserIds.set(index, obj);
7459 } else {
7460 if (mOtherUserIds.get(uid) != null) {
7461 reportSettingsProblem(Log.ERROR,
7462 "Adding duplicate shared id: " + uid
7463 + " name=" + name);
7464 return false;
7465 }
7466 mOtherUserIds.put(uid, obj);
7467 }
7468 return true;
7469 }
7470
7471 public Object getUserIdLP(int uid) {
7472 if (uid >= FIRST_APPLICATION_UID) {
7473 int N = mUserIds.size();
7474 final int index = uid - FIRST_APPLICATION_UID;
7475 return index < N ? mUserIds.get(index) : null;
7476 } else {
7477 return mOtherUserIds.get(uid);
7478 }
7479 }
7480
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08007481 private Set<String> findPackagesWithFlag(int flag) {
7482 Set<String> ret = new HashSet<String>();
7483 for (PackageSetting ps : mPackages.values()) {
7484 // Has to match atleast all the flag bits set on flag
7485 if ((ps.pkgFlags & flag) == flag) {
7486 ret.add(ps.name);
7487 }
7488 }
7489 return ret;
7490 }
7491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007492 private void removeUserIdLP(int uid) {
7493 if (uid >= FIRST_APPLICATION_UID) {
7494 int N = mUserIds.size();
7495 final int index = uid - FIRST_APPLICATION_UID;
7496 if (index < N) mUserIds.set(index, null);
7497 } else {
7498 mOtherUserIds.remove(uid);
7499 }
7500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 void writeLP() {
7503 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
7504
7505 // Keep the old settings around until we know the new ones have
7506 // been successfully written.
7507 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007508 // Presence of backup settings file indicates that we failed
7509 // to persist settings earlier. So preserve the older
7510 // backup for future reference since the current settings
7511 // might have been corrupted.
7512 if (!mBackupSettingsFilename.exists()) {
7513 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
7514 Log.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
7515 return;
7516 }
7517 } else {
7518 Log.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07007519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 }
7521
7522 mPastSignatures.clear();
7523
7524 try {
7525 FileOutputStream str = new FileOutputStream(mSettingsFilename);
7526
7527 //XmlSerializer serializer = XmlUtils.serializerInstance();
7528 XmlSerializer serializer = new FastXmlSerializer();
7529 serializer.setOutput(str, "utf-8");
7530 serializer.startDocument(null, true);
7531 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
7532
7533 serializer.startTag(null, "packages");
7534
7535 serializer.startTag(null, "permission-trees");
7536 for (BasePermission bp : mPermissionTrees.values()) {
7537 writePermission(serializer, bp);
7538 }
7539 serializer.endTag(null, "permission-trees");
7540
7541 serializer.startTag(null, "permissions");
7542 for (BasePermission bp : mPermissions.values()) {
7543 writePermission(serializer, bp);
7544 }
7545 serializer.endTag(null, "permissions");
7546
7547 for (PackageSetting pkg : mPackages.values()) {
7548 writePackage(serializer, pkg);
7549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007551 for (PackageSetting pkg : mDisabledSysPackages.values()) {
7552 writeDisabledSysPackage(serializer, pkg);
7553 }
7554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 serializer.startTag(null, "preferred-activities");
7556 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
7557 serializer.startTag(null, "item");
7558 pa.writeToXml(serializer);
7559 serializer.endTag(null, "item");
7560 }
7561 serializer.endTag(null, "preferred-activities");
7562
7563 for (SharedUserSetting usr : mSharedUsers.values()) {
7564 serializer.startTag(null, "shared-user");
7565 serializer.attribute(null, "name", usr.name);
7566 serializer.attribute(null, "userId",
7567 Integer.toString(usr.userId));
7568 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
7569 serializer.startTag(null, "perms");
7570 for (String name : usr.grantedPermissions) {
7571 serializer.startTag(null, "item");
7572 serializer.attribute(null, "name", name);
7573 serializer.endTag(null, "item");
7574 }
7575 serializer.endTag(null, "perms");
7576 serializer.endTag(null, "shared-user");
7577 }
7578
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007579 if (mPackagesToBeCleaned.size() > 0) {
7580 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
7581 serializer.startTag(null, "cleaning-package");
7582 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
7583 serializer.endTag(null, "cleaning-package");
7584 }
7585 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007586
7587 if (mRenamedPackages.size() > 0) {
7588 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
7589 serializer.startTag(null, "renamed-package");
7590 serializer.attribute(null, "new", e.getKey());
7591 serializer.attribute(null, "old", e.getValue());
7592 serializer.endTag(null, "renamed-package");
7593 }
7594 }
7595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 serializer.endTag(null, "packages");
7597
7598 serializer.endDocument();
7599
7600 str.flush();
7601 str.close();
7602
7603 // New settings successfully written, old ones are no longer
7604 // needed.
7605 mBackupSettingsFilename.delete();
7606 FileUtils.setPermissions(mSettingsFilename.toString(),
7607 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7608 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7609 |FileUtils.S_IROTH,
7610 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007611
7612 // Write package list file now, use a JournaledFile.
7613 //
7614 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
7615 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
7616
7617 str = new FileOutputStream(journal.chooseForWrite());
7618 try {
7619 StringBuilder sb = new StringBuilder();
7620 for (PackageSetting pkg : mPackages.values()) {
7621 ApplicationInfo ai = pkg.pkg.applicationInfo;
7622 String dataPath = ai.dataDir;
7623 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
7624
7625 // Avoid any application that has a space in its path
7626 // or that is handled by the system.
7627 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
7628 continue;
7629
7630 // we store on each line the following information for now:
7631 //
7632 // pkgName - package name
7633 // userId - application-specific user id
7634 // debugFlag - 0 or 1 if the package is debuggable.
7635 // dataPath - path to package's data path
7636 //
7637 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
7638 //
7639 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
7640 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
7641 // system/core/run-as/run-as.c
7642 //
7643 sb.setLength(0);
7644 sb.append(ai.packageName);
7645 sb.append(" ");
7646 sb.append((int)ai.uid);
7647 sb.append(isDebug ? " 1 " : " 0 ");
7648 sb.append(dataPath);
7649 sb.append("\n");
7650 str.write(sb.toString().getBytes());
7651 }
7652 str.flush();
7653 str.close();
7654 journal.commit();
7655 }
7656 catch (Exception e) {
7657 journal.rollback();
7658 }
7659
7660 FileUtils.setPermissions(mPackageListFilename.toString(),
7661 FileUtils.S_IRUSR|FileUtils.S_IWUSR
7662 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
7663 |FileUtils.S_IROTH,
7664 -1, -1);
7665
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007666 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667
7668 } catch(XmlPullParserException e) {
7669 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 -08007670 } catch(java.io.IOException e) {
7671 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 -08007672 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007673 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07007674 if (mSettingsFilename.exists()) {
7675 if (!mSettingsFilename.delete()) {
7676 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
7677 }
7678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 //Debug.stopMethodTracing();
7680 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007681
7682 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007683 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007684 serializer.startTag(null, "updated-package");
7685 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007686 if (pkg.realName != null) {
7687 serializer.attribute(null, "realName", pkg.realName);
7688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 serializer.attribute(null, "codePath", pkg.codePathString);
7690 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007691 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7693 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7694 }
7695 if (pkg.sharedUser == null) {
7696 serializer.attribute(null, "userId",
7697 Integer.toString(pkg.userId));
7698 } else {
7699 serializer.attribute(null, "sharedUserId",
7700 Integer.toString(pkg.userId));
7701 }
7702 serializer.startTag(null, "perms");
7703 if (pkg.sharedUser == null) {
7704 // If this is a shared user, the permissions will
7705 // be written there. We still need to write an
7706 // empty permissions list so permissionsFixed will
7707 // be set.
7708 for (final String name : pkg.grantedPermissions) {
7709 BasePermission bp = mPermissions.get(name);
7710 if ((bp != null) && (bp.perm != null) && (bp.perm.info != null)) {
7711 // We only need to write signature or system permissions but this wont
7712 // match the semantics of grantedPermissions. So write all permissions.
7713 serializer.startTag(null, "item");
7714 serializer.attribute(null, "name", name);
7715 serializer.endTag(null, "item");
7716 }
7717 }
7718 }
7719 serializer.endTag(null, "perms");
7720 serializer.endTag(null, "updated-package");
7721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007722
7723 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007724 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 serializer.startTag(null, "package");
7726 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007727 if (pkg.realName != null) {
7728 serializer.attribute(null, "realName", pkg.realName);
7729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 serializer.attribute(null, "codePath", pkg.codePathString);
7731 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
7732 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
7733 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08007734 serializer.attribute(null, "flags",
7735 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007737 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 if (pkg.sharedUser == null) {
7739 serializer.attribute(null, "userId",
7740 Integer.toString(pkg.userId));
7741 } else {
7742 serializer.attribute(null, "sharedUserId",
7743 Integer.toString(pkg.userId));
7744 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007745 if (pkg.uidError) {
7746 serializer.attribute(null, "uidError", "true");
7747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
7749 serializer.attribute(null, "enabled",
7750 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
7751 ? "true" : "false");
7752 }
7753 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
7754 serializer.attribute(null, "installStatus", "false");
7755 }
Jacek Surazski65e13172009-04-28 15:26:38 +02007756 if (pkg.installerPackageName != null) {
7757 serializer.attribute(null, "installer", pkg.installerPackageName);
7758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
7760 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7761 serializer.startTag(null, "perms");
7762 if (pkg.sharedUser == null) {
7763 // If this is a shared user, the permissions will
7764 // be written there. We still need to write an
7765 // empty permissions list so permissionsFixed will
7766 // be set.
7767 for (final String name : pkg.grantedPermissions) {
7768 serializer.startTag(null, "item");
7769 serializer.attribute(null, "name", name);
7770 serializer.endTag(null, "item");
7771 }
7772 }
7773 serializer.endTag(null, "perms");
7774 }
7775 if (pkg.disabledComponents.size() > 0) {
7776 serializer.startTag(null, "disabled-components");
7777 for (final String name : pkg.disabledComponents) {
7778 serializer.startTag(null, "item");
7779 serializer.attribute(null, "name", name);
7780 serializer.endTag(null, "item");
7781 }
7782 serializer.endTag(null, "disabled-components");
7783 }
7784 if (pkg.enabledComponents.size() > 0) {
7785 serializer.startTag(null, "enabled-components");
7786 for (final String name : pkg.enabledComponents) {
7787 serializer.startTag(null, "item");
7788 serializer.attribute(null, "name", name);
7789 serializer.endTag(null, "item");
7790 }
7791 serializer.endTag(null, "enabled-components");
7792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 serializer.endTag(null, "package");
7795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 void writePermission(XmlSerializer serializer, BasePermission bp)
7798 throws XmlPullParserException, java.io.IOException {
7799 if (bp.type != BasePermission.TYPE_BUILTIN
7800 && bp.sourcePackage != null) {
7801 serializer.startTag(null, "item");
7802 serializer.attribute(null, "name", bp.name);
7803 serializer.attribute(null, "package", bp.sourcePackage);
7804 if (DEBUG_SETTINGS) Log.v(TAG,
7805 "Writing perm: name=" + bp.name + " type=" + bp.type);
7806 if (bp.type == BasePermission.TYPE_DYNAMIC) {
7807 PermissionInfo pi = bp.perm != null ? bp.perm.info
7808 : bp.pendingInfo;
7809 if (pi != null) {
7810 serializer.attribute(null, "type", "dynamic");
7811 if (pi.icon != 0) {
7812 serializer.attribute(null, "icon",
7813 Integer.toString(pi.icon));
7814 }
7815 if (pi.nonLocalizedLabel != null) {
7816 serializer.attribute(null, "label",
7817 pi.nonLocalizedLabel.toString());
7818 }
7819 if (pi.protectionLevel !=
7820 PermissionInfo.PROTECTION_NORMAL) {
7821 serializer.attribute(null, "protection",
7822 Integer.toString(pi.protectionLevel));
7823 }
7824 }
7825 }
7826 serializer.endTag(null, "item");
7827 }
7828 }
7829
7830 String getReadMessagesLP() {
7831 return mReadMessages.toString();
7832 }
7833
Oscar Montemayora8529f62009-11-18 10:14:20 -08007834 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
7836 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007837 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 while(its.hasNext()) {
7839 String key = its.next();
7840 PackageSetting ps = mPackages.get(key);
7841 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08007842 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 }
7844 }
7845 return ret;
7846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 boolean readLP() {
7849 FileInputStream str = null;
7850 if (mBackupSettingsFilename.exists()) {
7851 try {
7852 str = new FileInputStream(mBackupSettingsFilename);
7853 mReadMessages.append("Reading from backup settings file\n");
7854 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07007855 if (mSettingsFilename.exists()) {
7856 // If both the backup and settings file exist, we
7857 // ignore the settings since it might have been
7858 // corrupted.
7859 Log.w(TAG, "Cleaning up settings file " + mSettingsFilename);
7860 mSettingsFilename.delete();
7861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 } catch (java.io.IOException e) {
7863 // We'll try for the normal settings file.
7864 }
7865 }
7866
7867 mPastSignatures.clear();
7868
7869 try {
7870 if (str == null) {
7871 if (!mSettingsFilename.exists()) {
7872 mReadMessages.append("No settings file found\n");
7873 Log.i(TAG, "No current settings file!");
7874 return false;
7875 }
7876 str = new FileInputStream(mSettingsFilename);
7877 }
7878 XmlPullParser parser = Xml.newPullParser();
7879 parser.setInput(str, null);
7880
7881 int type;
7882 while ((type=parser.next()) != XmlPullParser.START_TAG
7883 && type != XmlPullParser.END_DOCUMENT) {
7884 ;
7885 }
7886
7887 if (type != XmlPullParser.START_TAG) {
7888 mReadMessages.append("No start tag found in settings file\n");
7889 Log.e(TAG, "No start tag found in package manager settings");
7890 return false;
7891 }
7892
7893 int outerDepth = parser.getDepth();
7894 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7895 && (type != XmlPullParser.END_TAG
7896 || parser.getDepth() > outerDepth)) {
7897 if (type == XmlPullParser.END_TAG
7898 || type == XmlPullParser.TEXT) {
7899 continue;
7900 }
7901
7902 String tagName = parser.getName();
7903 if (tagName.equals("package")) {
7904 readPackageLP(parser);
7905 } else if (tagName.equals("permissions")) {
7906 readPermissionsLP(mPermissions, parser);
7907 } else if (tagName.equals("permission-trees")) {
7908 readPermissionsLP(mPermissionTrees, parser);
7909 } else if (tagName.equals("shared-user")) {
7910 readSharedUserLP(parser);
7911 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08007912 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 } else if (tagName.equals("preferred-activities")) {
7914 readPreferredActivitiesLP(parser);
7915 } else if(tagName.equals("updated-package")) {
7916 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007917 } else if (tagName.equals("cleaning-package")) {
7918 String name = parser.getAttributeValue(null, "name");
7919 if (name != null) {
7920 mPackagesToBeCleaned.add(name);
7921 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007922 } else if (tagName.equals("renamed-package")) {
7923 String nname = parser.getAttributeValue(null, "new");
7924 String oname = parser.getAttributeValue(null, "old");
7925 if (nname != null && oname != null) {
7926 mRenamedPackages.put(nname, oname);
7927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 } else {
7929 Log.w(TAG, "Unknown element under <packages>: "
7930 + parser.getName());
7931 XmlUtils.skipCurrentTag(parser);
7932 }
7933 }
7934
7935 str.close();
7936
7937 } catch(XmlPullParserException e) {
7938 mReadMessages.append("Error reading: " + e.toString());
7939 Log.e(TAG, "Error reading package manager settings", e);
7940
7941 } catch(java.io.IOException e) {
7942 mReadMessages.append("Error reading: " + e.toString());
7943 Log.e(TAG, "Error reading package manager settings", e);
7944
7945 }
7946
7947 int N = mPendingPackages.size();
7948 for (int i=0; i<N; i++) {
7949 final PendingPackage pp = mPendingPackages.get(i);
7950 Object idObj = getUserIdLP(pp.sharedId);
7951 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007952 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007954 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 if (p == null) {
7956 Log.w(TAG, "Unable to create application package for "
7957 + pp.name);
7958 continue;
7959 }
7960 p.copyFrom(pp);
7961 } else if (idObj != null) {
7962 String msg = "Bad package setting: package " + pp.name
7963 + " has shared uid " + pp.sharedId
7964 + " that is not a shared uid\n";
7965 mReadMessages.append(msg);
7966 Log.e(TAG, msg);
7967 } else {
7968 String msg = "Bad package setting: package " + pp.name
7969 + " has shared uid " + pp.sharedId
7970 + " that is not defined\n";
7971 mReadMessages.append(msg);
7972 Log.e(TAG, msg);
7973 }
7974 }
7975 mPendingPackages.clear();
7976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 mReadMessages.append("Read completed successfully: "
7978 + mPackages.size() + " packages, "
7979 + mSharedUsers.size() + " shared uids\n");
7980
7981 return true;
7982 }
7983
7984 private int readInt(XmlPullParser parser, String ns, String name,
7985 int defValue) {
7986 String v = parser.getAttributeValue(ns, name);
7987 try {
7988 if (v == null) {
7989 return defValue;
7990 }
7991 return Integer.parseInt(v);
7992 } catch (NumberFormatException e) {
7993 reportSettingsProblem(Log.WARN,
7994 "Error in package manager settings: attribute " +
7995 name + " has bad integer value " + v + " at "
7996 + parser.getPositionDescription());
7997 }
7998 return defValue;
7999 }
8000
8001 private void readPermissionsLP(HashMap<String, BasePermission> out,
8002 XmlPullParser parser)
8003 throws IOException, XmlPullParserException {
8004 int outerDepth = parser.getDepth();
8005 int type;
8006 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8007 && (type != XmlPullParser.END_TAG
8008 || parser.getDepth() > outerDepth)) {
8009 if (type == XmlPullParser.END_TAG
8010 || type == XmlPullParser.TEXT) {
8011 continue;
8012 }
8013
8014 String tagName = parser.getName();
8015 if (tagName.equals("item")) {
8016 String name = parser.getAttributeValue(null, "name");
8017 String sourcePackage = parser.getAttributeValue(null, "package");
8018 String ptype = parser.getAttributeValue(null, "type");
8019 if (name != null && sourcePackage != null) {
8020 boolean dynamic = "dynamic".equals(ptype);
8021 BasePermission bp = new BasePermission(name, sourcePackage,
8022 dynamic
8023 ? BasePermission.TYPE_DYNAMIC
8024 : BasePermission.TYPE_NORMAL);
8025 if (dynamic) {
8026 PermissionInfo pi = new PermissionInfo();
8027 pi.packageName = sourcePackage.intern();
8028 pi.name = name.intern();
8029 pi.icon = readInt(parser, null, "icon", 0);
8030 pi.nonLocalizedLabel = parser.getAttributeValue(
8031 null, "label");
8032 pi.protectionLevel = readInt(parser, null, "protection",
8033 PermissionInfo.PROTECTION_NORMAL);
8034 bp.pendingInfo = pi;
8035 }
8036 out.put(bp.name, bp);
8037 } else {
8038 reportSettingsProblem(Log.WARN,
8039 "Error in package manager settings: permissions has"
8040 + " no name at " + parser.getPositionDescription());
8041 }
8042 } else {
8043 reportSettingsProblem(Log.WARN,
8044 "Unknown element reading permissions: "
8045 + parser.getName() + " at "
8046 + parser.getPositionDescription());
8047 }
8048 XmlUtils.skipCurrentTag(parser);
8049 }
8050 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008053 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008054 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008055 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 String codePathStr = parser.getAttributeValue(null, "codePath");
8057 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008058 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 resourcePathStr = codePathStr;
8060 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008061 String version = parser.getAttributeValue(null, "version");
8062 int versionCode = 0;
8063 if (version != null) {
8064 try {
8065 versionCode = Integer.parseInt(version);
8066 } catch (NumberFormatException e) {
8067 }
8068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 int pkgFlags = 0;
8071 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008072 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008073 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008074 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 String timeStampStr = parser.getAttributeValue(null, "ts");
8076 if (timeStampStr != null) {
8077 try {
8078 long timeStamp = Long.parseLong(timeStampStr);
8079 ps.setTimeStamp(timeStamp, timeStampStr);
8080 } catch (NumberFormatException e) {
8081 }
8082 }
8083 String idStr = parser.getAttributeValue(null, "userId");
8084 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8085 if(ps.userId <= 0) {
8086 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8087 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8088 }
8089 int outerDepth = parser.getDepth();
8090 int type;
8091 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8092 && (type != XmlPullParser.END_TAG
8093 || parser.getDepth() > outerDepth)) {
8094 if (type == XmlPullParser.END_TAG
8095 || type == XmlPullParser.TEXT) {
8096 continue;
8097 }
8098
8099 String tagName = parser.getName();
8100 if (tagName.equals("perms")) {
8101 readGrantedPermissionsLP(parser,
8102 ps.grantedPermissions);
8103 } else {
8104 reportSettingsProblem(Log.WARN,
8105 "Unknown element under <updated-package>: "
8106 + parser.getName());
8107 XmlUtils.skipCurrentTag(parser);
8108 }
8109 }
8110 mDisabledSysPackages.put(name, ps);
8111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 private void readPackageLP(XmlPullParser parser)
8114 throws XmlPullParserException, IOException {
8115 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008116 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 String idStr = null;
8118 String sharedIdStr = null;
8119 String codePathStr = null;
8120 String resourcePathStr = null;
8121 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008122 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008123 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008124 int pkgFlags = 0;
8125 String timeStampStr;
8126 long timeStamp = 0;
8127 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008128 String version = null;
8129 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 try {
8131 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008132 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008134 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8136 codePathStr = parser.getAttributeValue(null, "codePath");
8137 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008138 version = parser.getAttributeValue(null, "version");
8139 if (version != null) {
8140 try {
8141 versionCode = Integer.parseInt(version);
8142 } catch (NumberFormatException e) {
8143 }
8144 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008145 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008146
8147 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008149 try {
8150 pkgFlags = Integer.parseInt(systemStr);
8151 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008152 }
8153 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008154 // For backward compatibility
8155 systemStr = parser.getAttributeValue(null, "system");
8156 if (systemStr != null) {
8157 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8158 } else {
8159 // Old settings that don't specify system... just treat
8160 // them as system, good enough.
8161 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 }
8164 timeStampStr = parser.getAttributeValue(null, "ts");
8165 if (timeStampStr != null) {
8166 try {
8167 timeStamp = Long.parseLong(timeStampStr);
8168 } catch (NumberFormatException e) {
8169 }
8170 }
8171 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8172 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8173 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8174 if (resourcePathStr == null) {
8175 resourcePathStr = codePathStr;
8176 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008177 if (realName != null) {
8178 realName = realName.intern();
8179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 if (name == null) {
8181 reportSettingsProblem(Log.WARN,
8182 "Error in package manager settings: <package> has no name at "
8183 + parser.getPositionDescription());
8184 } else if (codePathStr == null) {
8185 reportSettingsProblem(Log.WARN,
8186 "Error in package manager settings: <package> has no codePath at "
8187 + parser.getPositionDescription());
8188 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008189 packageSetting = addPackageLP(name.intern(), realName,
8190 new File(codePathStr), new File(resourcePathStr),
8191 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8193 + ": userId=" + userId + " pkg=" + packageSetting);
8194 if (packageSetting == null) {
8195 reportSettingsProblem(Log.ERROR,
8196 "Failure adding uid " + userId
8197 + " while parsing settings at "
8198 + parser.getPositionDescription());
8199 } else {
8200 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8201 }
8202 } else if (sharedIdStr != null) {
8203 userId = sharedIdStr != null
8204 ? Integer.parseInt(sharedIdStr) : 0;
8205 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008206 packageSetting = new PendingPackage(name.intern(), realName,
8207 new File(codePathStr), new File(resourcePathStr),
8208 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 packageSetting.setTimeStamp(timeStamp, timeStampStr);
8210 mPendingPackages.add((PendingPackage) packageSetting);
8211 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
8212 + ": sharedUserId=" + userId + " pkg="
8213 + packageSetting);
8214 } else {
8215 reportSettingsProblem(Log.WARN,
8216 "Error in package manager settings: package "
8217 + name + " has bad sharedId " + sharedIdStr
8218 + " at " + parser.getPositionDescription());
8219 }
8220 } else {
8221 reportSettingsProblem(Log.WARN,
8222 "Error in package manager settings: package "
8223 + name + " has bad userId " + idStr + " at "
8224 + parser.getPositionDescription());
8225 }
8226 } catch (NumberFormatException e) {
8227 reportSettingsProblem(Log.WARN,
8228 "Error in package manager settings: package "
8229 + name + " has bad userId " + idStr + " at "
8230 + parser.getPositionDescription());
8231 }
8232 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008233 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02008234 packageSetting.installerPackageName = installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008235 final String enabledStr = parser.getAttributeValue(null, "enabled");
8236 if (enabledStr != null) {
8237 if (enabledStr.equalsIgnoreCase("true")) {
8238 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
8239 } else if (enabledStr.equalsIgnoreCase("false")) {
8240 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
8241 } else if (enabledStr.equalsIgnoreCase("default")) {
8242 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8243 } else {
8244 reportSettingsProblem(Log.WARN,
8245 "Error in package manager settings: package "
8246 + name + " has bad enabled value: " + idStr
8247 + " at " + parser.getPositionDescription());
8248 }
8249 } else {
8250 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
8251 }
8252 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
8253 if (installStatusStr != null) {
8254 if (installStatusStr.equalsIgnoreCase("false")) {
8255 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
8256 } else {
8257 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
8258 }
8259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 int outerDepth = parser.getDepth();
8262 int type;
8263 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8264 && (type != XmlPullParser.END_TAG
8265 || parser.getDepth() > outerDepth)) {
8266 if (type == XmlPullParser.END_TAG
8267 || type == XmlPullParser.TEXT) {
8268 continue;
8269 }
8270
8271 String tagName = parser.getName();
8272 if (tagName.equals("disabled-components")) {
8273 readDisabledComponentsLP(packageSetting, parser);
8274 } else if (tagName.equals("enabled-components")) {
8275 readEnabledComponentsLP(packageSetting, parser);
8276 } else if (tagName.equals("sigs")) {
8277 packageSetting.signatures.readXml(parser, mPastSignatures);
8278 } else if (tagName.equals("perms")) {
8279 readGrantedPermissionsLP(parser,
8280 packageSetting.loadedPermissions);
8281 packageSetting.permissionsFixed = true;
8282 } else {
8283 reportSettingsProblem(Log.WARN,
8284 "Unknown element under <package>: "
8285 + parser.getName());
8286 XmlUtils.skipCurrentTag(parser);
8287 }
8288 }
8289 } else {
8290 XmlUtils.skipCurrentTag(parser);
8291 }
8292 }
8293
8294 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
8295 XmlPullParser parser)
8296 throws IOException, XmlPullParserException {
8297 int outerDepth = parser.getDepth();
8298 int type;
8299 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8300 && (type != XmlPullParser.END_TAG
8301 || parser.getDepth() > outerDepth)) {
8302 if (type == XmlPullParser.END_TAG
8303 || type == XmlPullParser.TEXT) {
8304 continue;
8305 }
8306
8307 String tagName = parser.getName();
8308 if (tagName.equals("item")) {
8309 String name = parser.getAttributeValue(null, "name");
8310 if (name != null) {
8311 packageSetting.disabledComponents.add(name.intern());
8312 } else {
8313 reportSettingsProblem(Log.WARN,
8314 "Error in package manager settings: <disabled-components> has"
8315 + " no name at " + parser.getPositionDescription());
8316 }
8317 } else {
8318 reportSettingsProblem(Log.WARN,
8319 "Unknown element under <disabled-components>: "
8320 + parser.getName());
8321 }
8322 XmlUtils.skipCurrentTag(parser);
8323 }
8324 }
8325
8326 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
8327 XmlPullParser parser)
8328 throws IOException, XmlPullParserException {
8329 int outerDepth = parser.getDepth();
8330 int type;
8331 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8332 && (type != XmlPullParser.END_TAG
8333 || parser.getDepth() > outerDepth)) {
8334 if (type == XmlPullParser.END_TAG
8335 || type == XmlPullParser.TEXT) {
8336 continue;
8337 }
8338
8339 String tagName = parser.getName();
8340 if (tagName.equals("item")) {
8341 String name = parser.getAttributeValue(null, "name");
8342 if (name != null) {
8343 packageSetting.enabledComponents.add(name.intern());
8344 } else {
8345 reportSettingsProblem(Log.WARN,
8346 "Error in package manager settings: <enabled-components> has"
8347 + " no name at " + parser.getPositionDescription());
8348 }
8349 } else {
8350 reportSettingsProblem(Log.WARN,
8351 "Unknown element under <enabled-components>: "
8352 + parser.getName());
8353 }
8354 XmlUtils.skipCurrentTag(parser);
8355 }
8356 }
8357
8358 private void readSharedUserLP(XmlPullParser parser)
8359 throws XmlPullParserException, IOException {
8360 String name = null;
8361 String idStr = null;
8362 int pkgFlags = 0;
8363 SharedUserSetting su = null;
8364 try {
8365 name = parser.getAttributeValue(null, "name");
8366 idStr = parser.getAttributeValue(null, "userId");
8367 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8368 if ("true".equals(parser.getAttributeValue(null, "system"))) {
8369 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8370 }
8371 if (name == null) {
8372 reportSettingsProblem(Log.WARN,
8373 "Error in package manager settings: <shared-user> has no name at "
8374 + parser.getPositionDescription());
8375 } else if (userId == 0) {
8376 reportSettingsProblem(Log.WARN,
8377 "Error in package manager settings: shared-user "
8378 + name + " has bad userId " + idStr + " at "
8379 + parser.getPositionDescription());
8380 } else {
8381 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
8382 reportSettingsProblem(Log.ERROR,
8383 "Occurred while parsing settings at "
8384 + parser.getPositionDescription());
8385 }
8386 }
8387 } catch (NumberFormatException e) {
8388 reportSettingsProblem(Log.WARN,
8389 "Error in package manager settings: package "
8390 + name + " has bad userId " + idStr + " at "
8391 + parser.getPositionDescription());
8392 };
8393
8394 if (su != null) {
8395 int outerDepth = parser.getDepth();
8396 int type;
8397 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8398 && (type != XmlPullParser.END_TAG
8399 || parser.getDepth() > outerDepth)) {
8400 if (type == XmlPullParser.END_TAG
8401 || type == XmlPullParser.TEXT) {
8402 continue;
8403 }
8404
8405 String tagName = parser.getName();
8406 if (tagName.equals("sigs")) {
8407 su.signatures.readXml(parser, mPastSignatures);
8408 } else if (tagName.equals("perms")) {
8409 readGrantedPermissionsLP(parser, su.loadedPermissions);
8410 } else {
8411 reportSettingsProblem(Log.WARN,
8412 "Unknown element under <shared-user>: "
8413 + parser.getName());
8414 XmlUtils.skipCurrentTag(parser);
8415 }
8416 }
8417
8418 } else {
8419 XmlUtils.skipCurrentTag(parser);
8420 }
8421 }
8422
8423 private void readGrantedPermissionsLP(XmlPullParser parser,
8424 HashSet<String> outPerms) throws IOException, XmlPullParserException {
8425 int outerDepth = parser.getDepth();
8426 int type;
8427 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8428 && (type != XmlPullParser.END_TAG
8429 || parser.getDepth() > outerDepth)) {
8430 if (type == XmlPullParser.END_TAG
8431 || type == XmlPullParser.TEXT) {
8432 continue;
8433 }
8434
8435 String tagName = parser.getName();
8436 if (tagName.equals("item")) {
8437 String name = parser.getAttributeValue(null, "name");
8438 if (name != null) {
8439 outPerms.add(name.intern());
8440 } else {
8441 reportSettingsProblem(Log.WARN,
8442 "Error in package manager settings: <perms> has"
8443 + " no name at " + parser.getPositionDescription());
8444 }
8445 } else {
8446 reportSettingsProblem(Log.WARN,
8447 "Unknown element under <perms>: "
8448 + parser.getName());
8449 }
8450 XmlUtils.skipCurrentTag(parser);
8451 }
8452 }
8453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 private void readPreferredActivitiesLP(XmlPullParser parser)
8455 throws XmlPullParserException, IOException {
8456 int outerDepth = parser.getDepth();
8457 int type;
8458 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8459 && (type != XmlPullParser.END_TAG
8460 || parser.getDepth() > outerDepth)) {
8461 if (type == XmlPullParser.END_TAG
8462 || type == XmlPullParser.TEXT) {
8463 continue;
8464 }
8465
8466 String tagName = parser.getName();
8467 if (tagName.equals("item")) {
8468 PreferredActivity pa = new PreferredActivity(parser);
8469 if (pa.mParseError == null) {
8470 mPreferredActivities.addFilter(pa);
8471 } else {
8472 reportSettingsProblem(Log.WARN,
8473 "Error in package manager settings: <preferred-activity> "
8474 + pa.mParseError + " at "
8475 + parser.getPositionDescription());
8476 }
8477 } else {
8478 reportSettingsProblem(Log.WARN,
8479 "Unknown element under <preferred-activities>: "
8480 + parser.getName());
8481 XmlUtils.skipCurrentTag(parser);
8482 }
8483 }
8484 }
8485
8486 // Returns -1 if we could not find an available UserId to assign
8487 private int newUserIdLP(Object obj) {
8488 // Let's be stupidly inefficient for now...
8489 final int N = mUserIds.size();
8490 for (int i=0; i<N; i++) {
8491 if (mUserIds.get(i) == null) {
8492 mUserIds.set(i, obj);
8493 return FIRST_APPLICATION_UID + i;
8494 }
8495 }
8496
8497 // None left?
8498 if (N >= MAX_APPLICATION_UIDS) {
8499 return -1;
8500 }
8501
8502 mUserIds.add(obj);
8503 return FIRST_APPLICATION_UID + N;
8504 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008505
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 public PackageSetting getDisabledSystemPkg(String name) {
8507 synchronized(mPackages) {
8508 PackageSetting ps = mDisabledSysPackages.get(name);
8509 return ps;
8510 }
8511 }
8512
8513 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
8514 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
8515 if (Config.LOGV) {
8516 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
8517 + " componentName = " + componentInfo.name);
8518 Log.v(TAG, "enabledComponents: "
8519 + Arrays.toString(packageSettings.enabledComponents.toArray()));
8520 Log.v(TAG, "disabledComponents: "
8521 + Arrays.toString(packageSettings.disabledComponents.toArray()));
8522 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008523 if (packageSettings == null) {
8524 if (false) {
8525 Log.w(TAG, "WAITING FOR DEBUGGER");
8526 Debug.waitForDebugger();
8527 Log.i(TAG, "We will crash!");
8528 }
8529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 return ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0)
8531 || ((componentInfo.enabled
8532 && ((packageSettings.enabled == COMPONENT_ENABLED_STATE_ENABLED)
8533 || (componentInfo.applicationInfo.enabled
8534 && packageSettings.enabled != COMPONENT_ENABLED_STATE_DISABLED))
8535 && !packageSettings.disabledComponents.contains(componentInfo.name))
8536 || packageSettings.enabledComponents.contains(componentInfo.name));
8537 }
8538 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008539
8540 // ------- apps on sdcard specific code -------
8541 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008542 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08008543 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008544 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008545 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008546
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008547
8548 static MountService getMountService() {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008549 return (MountService) ServiceManager.getService("mount");
8550 }
8551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008552 private String getEncryptKey() {
8553 try {
8554 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8555 if (sdEncKey == null) {
8556 sdEncKey = SystemKeyStore.getInstance().
8557 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8558 if (sdEncKey == null) {
8559 Log.e(TAG, "Failed to create encryption keys");
8560 return null;
8561 }
8562 }
8563 return sdEncKey;
8564 } catch (NoSuchAlgorithmException nsae) {
8565 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8566 return null;
8567 }
8568 }
8569
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008570 private String createSdDir(File tmpPackageFile, String pkgName) {
8571 // Create mount point via MountService
8572 MountService mountService = getMountService();
8573 long len = tmpPackageFile.length();
8574 int mbLen = (int) (len/(1024*1024));
8575 if ((len - (mbLen * 1024 * 1024)) > 0) {
8576 mbLen++;
8577 }
8578 if (DEBUG_SD_INSTALL) Log.i(TAG, "mbLen="+mbLen);
8579 String cachePath = null;
Oscar Montemayord02546b2010-01-14 16:38:40 -08008580 String sdEncKey;
8581 try {
8582 sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8583 if (sdEncKey == null) {
8584 sdEncKey = SystemKeyStore.getInstance().
8585 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
8586 if (sdEncKey == null) {
8587 Log.e(TAG, "Failed to create encryption keys for package: " + pkgName + ".");
8588 return null;
8589 }
8590 }
8591 } catch (NoSuchAlgorithmException nsae) {
8592 Log.e(TAG, "Failed to create encryption keys with exception: " + nsae);
8593 return null;
8594 }
San Mehatbe16cb12010-01-29 05:35:35 -08008595
8596 int rc = mountService.createSecureContainer(
8597 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008598 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008599 Log.e(TAG, String.format("Failed to create container (%d)", rc));
8600
8601 rc = mountService.destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008602 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008603 Log.e(TAG, String.format("Failed to cleanup container (%d)", rc));
8604 return null;
8605 }
8606 rc = mountService.createSecureContainer(
8607 pkgName, mbLen, "vfat", sdEncKey, Process.SYSTEM_UID);
San Mehatb1043402010-02-05 08:26:50 -08008608 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008609 Log.e(TAG, String.format("Failed to create container (2nd try) (%d)", rc));
8610 return null;
8611 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008612 }
San Mehatbe16cb12010-01-29 05:35:35 -08008613
8614 cachePath = mountService.getSecureContainerPath(pkgName);
8615 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install " + pkgName + ", cachePath =" + cachePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008616 return cachePath;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008617 }
8618
8619 private String mountSdDir(String pkgName, int ownerUid) {
Oscar Montemayord02546b2010-01-14 16:38:40 -08008620 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
8621 if (sdEncKey == null) {
8622 Log.e(TAG, "Failed to retrieve encryption keys to mount package code: " + pkgName + ".");
8623 return null;
8624 }
San Mehatbe16cb12010-01-29 05:35:35 -08008625
8626 int rc = getMountService().mountSecureContainer(pkgName, sdEncKey, ownerUid);
8627
San Mehatb1043402010-02-05 08:26:50 -08008628 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008629 Log.i(TAG, "Failed to mount container for pkg : " + pkgName + " rc : " + rc);
8630 return null;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008631 }
San Mehatbe16cb12010-01-29 05:35:35 -08008632
8633 return getMountService().getSecureContainerPath(pkgName);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008634 }
8635
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008636 private boolean unMountSdDir(String pkgName) {
8637 // STOPSHIP unmount directory
San Mehatbe16cb12010-01-29 05:35:35 -08008638 int rc = getMountService().unmountSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008639 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008640 Log.e(TAG, "Failed to unmount : " + pkgName + " with rc " + rc);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008641 return false;
8642 }
San Mehatbe16cb12010-01-29 05:35:35 -08008643 return true;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008644 }
8645
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008646 private boolean renameSdDir(String oldId, String newId) {
8647 try {
8648 getMountService().renameSecureContainer(oldId, newId);
8649 return true;
8650 } catch (IllegalStateException e) {
8651 Log.i(TAG, "Failed ot rename " + oldId + " to " + newId +
8652 " with exception : " + e);
8653 }
8654 return false;
8655 }
8656
8657 private String getSdDir(String pkgName) {
8658 return getMountService().getSecureContainerPath(pkgName);
8659 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008660
San Mehatbe16cb12010-01-29 05:35:35 -08008661 private boolean finalizeSdDir(String pkgName) {
8662 int rc = getMountService().finalizeSecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008663 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008664 Log.i(TAG, "Failed to finalize container for pkg : " + pkgName);
8665 return false;
8666 }
8667 return true;
8668 }
8669
8670 private boolean destroySdDir(String pkgName) {
8671 int rc = getMountService().destroySecureContainer(pkgName);
San Mehatb1043402010-02-05 08:26:50 -08008672 if (rc != StorageResultCode.OperationSucceeded) {
San Mehatbe16cb12010-01-29 05:35:35 -08008673 Log.i(TAG, "Failed to destroy container for pkg : " + pkgName);
8674 return false;
8675 }
8676 return true;
8677 }
8678
8679 static String[] getSecureContainerList() {
8680 String[] list = getMountService().getSecureContainerList();
8681 return list.length == 0 ? null : list;
8682 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008683
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008684 static boolean isContainerMounted(String cid) {
8685 // STOPSHIP
8686 // New api from MountService
8687 try {
8688 return (getMountService().getSecureContainerPath(cid) != null);
8689 } catch (IllegalStateException e) {
8690 }
8691 return false;
8692 }
8693
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008694 static String getTempContainerId() {
8695 String prefix = "smdl1tmp";
8696 int tmpIdx = 1;
8697 String list[] = getSecureContainerList();
8698 if (list != null) {
8699 int idx = 0;
8700 int idList[] = new int[MAX_CONTAINERS];
8701 boolean neverFound = true;
8702 for (String name : list) {
8703 // Ignore null entries
8704 if (name == null) {
8705 continue;
8706 }
8707 int sidx = name.indexOf(prefix);
8708 if (sidx == -1) {
8709 // Not a temp file. just ignore
8710 continue;
8711 }
8712 String subStr = name.substring(sidx + prefix.length());
8713 idList[idx] = -1;
8714 if (subStr != null) {
8715 try {
8716 int cid = Integer.parseInt(subStr);
8717 idList[idx++] = cid;
8718 neverFound = false;
8719 } catch (NumberFormatException e) {
8720 }
8721 }
8722 }
8723 if (!neverFound) {
8724 // Sort idList
8725 Arrays.sort(idList);
8726 for (int j = 1; j <= idList.length; j++) {
8727 if (idList[j-1] != j) {
8728 tmpIdx = j;
8729 break;
8730 }
8731 }
8732 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008733 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08008734 return prefix + tmpIdx;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008735 }
8736
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008737 public void updateExternalMediaStatus(final boolean mediaStatus) {
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008738 synchronized (mPackages) {
8739 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
8740 mediaStatus+", mMediaMounted=" + mMediaMounted);
8741 if (mediaStatus == mMediaMounted) {
8742 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008743 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008744 mMediaMounted = mediaStatus;
8745 // Queue up an async operation since the package installation may take a little while.
8746 mHandler.post(new Runnable() {
8747 public void run() {
8748 mHandler.removeCallbacks(this);
8749 updateExternalMediaStatusInner(mediaStatus);
8750 }
8751 });
8752 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008753 }
8754
8755 void updateExternalMediaStatusInner(boolean mediaStatus) {
8756 final String list[] = getSecureContainerList();
8757 if (list == null || list.length == 0) {
8758 return;
8759 }
8760 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
8761 int uidList[] = new int[list.length];
8762 int num = 0;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008763 synchronized (mPackages) {
8764 Set<String> appList = mSettings.findPackagesWithFlag(ApplicationInfo.FLAG_ON_SDCARD);
8765 for (String cid : list) {
8766 SdInstallArgs args = new SdInstallArgs(cid);
8767 String removeEntry = null;
8768 for (String app : appList) {
8769 if (args.matchContainer(app)) {
8770 removeEntry = app;
8771 break;
8772 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008773 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008774 if (removeEntry == null) {
8775 // No matching app on device. Skip entry or may be cleanup?
8776 // Ignore default package
8777 continue;
8778 }
8779 appList.remove(removeEntry);
8780 PackageSetting ps = mSettings.mPackages.get(removeEntry);
8781 processCids.put(args, ps.codePathString);
8782 int uid = ps.userId;
8783 if (uid != -1) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008784 uidList[num++] = uid;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008785 }
8786 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008787 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008788 int uidArr[] = null;
8789 if (num > 0) {
8790 // Sort uid list
8791 Arrays.sort(uidList, 0, num);
8792 // Throw away duplicates
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008793 uidArr = new int[num];
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008794 uidArr[0] = uidList[0];
8795 int di = 0;
8796 for (int i = 1; i < num; i++) {
8797 if (uidList[i-1] != uidList[i]) {
8798 uidArr[di++] = uidList[i];
8799 }
8800 }
8801 if (true) {
8802 for (int j = 0; j < num; j++) {
8803 Log.i(TAG, "uidArr[" + j + "]=" + uidArr[j]);
8804 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008805 }
8806 }
8807 if (mediaStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008808 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008809 loadMediaPackages(processCids, uidArr);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008810 startCleaningPackages();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008811 } else {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008812 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008813 unloadMediaPackages(processCids, uidArr);
8814 }
8815 }
8816
8817 private void sendResourcesChangedBroadcast(boolean mediaStatus,
8818 ArrayList<String> pkgList, int uidArr[]) {
8819 int size = pkgList.size();
8820 if (size > 0) {
8821 // Send broadcasts here
8822 Bundle extras = new Bundle();
8823 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
8824 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008825 if (uidArr != null) {
8826 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
8827 }
8828 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
8829 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008830 sendPackageBroadcast(action, null, extras);
8831 }
8832 }
8833
8834 void loadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
8835 ArrayList<String> pkgList = new ArrayList<String>();
8836 Set<SdInstallArgs> keys = processCids.keySet();
8837 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008838 String codePath = processCids.get(args);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008839 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to install pkg : "
8840 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008841 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008842 Log.e(TAG, "Failed to install package: " + codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008843 continue;
8844 }
8845 // Parse package
8846 int parseFlags = PackageParser.PARSE_CHATTY |
8847 PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
8848 PackageParser pp = new PackageParser(codePath);
8849 pp.setSeparateProcesses(mSeparateProcesses);
8850 final PackageParser.Package pkg = pp.parsePackage(new File(codePath),
8851 codePath, mMetrics, parseFlags);
8852 if (pkg == null) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008853 Log.e(TAG, "Trying to install pkg : "
8854 + args.cid + " from " + args.cachePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008855 continue;
8856 }
8857 setApplicationInfoPaths(pkg, codePath, codePath);
8858 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
8859 synchronized (mInstallLock) {
8860 // Scan the package
8861 if (scanPackageLI(pkg, parseFlags, SCAN_MONITOR) != null) {
8862 synchronized (mPackages) {
8863 // Grant permissions
8864 grantPermissionsLP(pkg, false);
8865 // Persist settings
8866 mSettings.writeLP();
8867 retCode = PackageManager.INSTALL_SUCCEEDED;
8868 pkgList.add(pkg.packageName);
8869 }
8870 } else {
8871 Log.i(TAG, "Failed to install package: " + pkg.packageName + " from sdcard");
8872 }
8873 }
8874 args.doPostInstall(retCode);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008875 }
8876 // Send broadcasts first
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008877 if (pkgList.size() > 0) {
8878 sendResourcesChangedBroadcast(true, pkgList, uidArr);
8879 Runtime.getRuntime().gc();
8880 // If something failed do we clean up here or next install?
8881 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008882 }
8883
8884 void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids, int uidArr[]) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008885 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008886 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008887 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008888 Set<SdInstallArgs> keys = processCids.keySet();
8889 for (SdInstallArgs args : keys) {
8890 String cid = args.cid;
8891 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008892 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008893 // Delete package internally
8894 PackageRemovedInfo outInfo = new PackageRemovedInfo();
8895 synchronized (mInstallLock) {
8896 boolean res = deletePackageLI(pkgName, false,
8897 PackageManager.DONT_DELETE_DATA, outInfo);
8898 if (res) {
8899 pkgList.add(pkgName);
8900 } else {
8901 Log.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008902 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008903 }
8904 }
8905 }
8906 // Send broadcasts
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008907 if (pkgList.size() > 0) {
8908 sendResourcesChangedBroadcast(false, pkgList, uidArr);
8909 Runtime.getRuntime().gc();
8910 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008911 // Do clean up. Just unmount
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08008912 for (SdInstallArgs args : failedList) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008913 synchronized (mInstallLock) {
8914 args.doPostDeleteLI(false);
8915 }
8916 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918}