ContextImpl.java revision ff17024e583b170312d82089fd358d278ce16c9a
1/*
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 android.app;
18
19import android.app.usage.IUsageStatsManager;
20import android.app.usage.UsageStatsManager;
21import android.appwidget.AppWidgetManager;
22import android.os.Build;
23
24import android.service.persistentdata.IPersistentDataBlockService;
25import android.service.persistentdata.PersistentDataBlockManager;
26import com.android.internal.appwidget.IAppWidgetService;
27import com.android.internal.policy.PolicyManager;
28import com.android.internal.util.Preconditions;
29
30import android.bluetooth.BluetoothManager;
31import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentProvider;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.ContextWrapper;
37import android.content.IContentProvider;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.IIntentReceiver;
41import android.content.IntentSender;
42import android.content.IRestrictionsManager;
43import android.content.ReceiverCallNotAllowedException;
44import android.content.RestrictionsManager;
45import android.content.ServiceConnection;
46import android.content.SharedPreferences;
47import android.content.pm.ApplicationInfo;
48import android.content.pm.ILauncherApps;
49import android.content.pm.IPackageManager;
50import android.content.pm.LauncherApps;
51import android.content.pm.PackageManager;
52import android.content.pm.PackageManager.NameNotFoundException;
53import android.content.res.AssetManager;
54import android.content.res.CompatibilityInfo;
55import android.content.res.Configuration;
56import android.content.res.Resources;
57import android.database.DatabaseErrorHandler;
58import android.database.sqlite.SQLiteDatabase;
59import android.database.sqlite.SQLiteDatabase.CursorFactory;
60import android.graphics.Bitmap;
61import android.graphics.drawable.Drawable;
62import android.hardware.ConsumerIrManager;
63import android.hardware.ISerialManager;
64import android.hardware.SerialManager;
65import android.hardware.SystemSensorManager;
66import android.hardware.hdmi.HdmiControlManager;
67import android.hardware.hdmi.IHdmiControlService;
68import android.hardware.camera2.CameraManager;
69import android.hardware.display.DisplayManager;
70import android.hardware.input.InputManager;
71import android.hardware.usb.IUsbManager;
72import android.hardware.usb.UsbManager;
73import android.location.CountryDetector;
74import android.location.ICountryDetector;
75import android.location.ILocationManager;
76import android.location.LocationManager;
77import android.media.AudioManager;
78import android.media.MediaRouter;
79import android.media.projection.MediaProjectionManager;
80import android.media.session.MediaSessionManager;
81import android.media.tv.ITvInputManager;
82import android.media.tv.TvInputManager;
83import android.net.ConnectivityManager;
84import android.net.IConnectivityManager;
85import android.net.EthernetManager;
86import android.net.IEthernetManager;
87import android.net.INetworkPolicyManager;
88import android.net.NetworkPolicyManager;
89import android.net.NetworkScoreManager;
90import android.net.Uri;
91import android.net.nsd.INsdManager;
92import android.net.nsd.NsdManager;
93import android.net.wifi.IWifiManager;
94import android.net.wifi.WifiManager;
95import android.net.wifi.p2p.IWifiP2pManager;
96import android.net.wifi.p2p.WifiP2pManager;
97import android.net.wifi.IWifiScanner;
98import android.net.wifi.WifiScanner;
99import android.net.wifi.IRttManager;
100import android.net.wifi.RttManager;
101import android.nfc.NfcManager;
102import android.os.BatteryManager;
103import android.os.Binder;
104import android.os.Bundle;
105import android.os.Debug;
106import android.os.DropBoxManager;
107import android.os.Environment;
108import android.os.FileUtils;
109import android.os.Handler;
110import android.os.IBinder;
111import android.os.IPowerManager;
112import android.os.IUserManager;
113import android.os.Looper;
114import android.os.PowerManager;
115import android.os.Process;
116import android.os.RemoteException;
117import android.os.ServiceManager;
118import android.os.UserHandle;
119import android.os.SystemVibrator;
120import android.os.UserManager;
121import android.os.storage.IMountService;
122import android.os.storage.StorageManager;
123import android.print.IPrintManager;
124import android.print.PrintManager;
125import android.service.fingerprint.IFingerprintService;
126import android.service.fingerprint.FingerprintManager;
127import android.telecom.TelecomManager;
128import android.telephony.TelephonyManager;
129import android.content.ClipboardManager;
130import android.util.AndroidRuntimeException;
131import android.util.ArrayMap;
132import android.util.Log;
133import android.util.Slog;
134import android.view.DisplayAdjustments;
135import android.view.ContextThemeWrapper;
136import android.view.Display;
137import android.view.WindowManagerImpl;
138import android.view.accessibility.AccessibilityManager;
139import android.view.accessibility.CaptioningManager;
140import android.view.inputmethod.InputMethodManager;
141import android.view.textservice.TextServicesManager;
142import android.accounts.AccountManager;
143import android.accounts.IAccountManager;
144import android.app.admin.DevicePolicyManager;
145import android.app.job.IJobScheduler;
146import android.app.trust.TrustManager;
147
148import com.android.internal.annotations.GuardedBy;
149import com.android.internal.app.IAppOpsService;
150import com.android.internal.os.IDropBoxManagerService;
151
152import java.io.File;
153import java.io.FileInputStream;
154import java.io.FileNotFoundException;
155import java.io.FileOutputStream;
156import java.io.IOException;
157import java.io.InputStream;
158import java.util.ArrayList;
159import java.util.HashMap;
160
161class ReceiverRestrictedContext extends ContextWrapper {
162    ReceiverRestrictedContext(Context base) {
163        super(base);
164    }
165
166    @Override
167    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
168        return registerReceiver(receiver, filter, null, null);
169    }
170
171    @Override
172    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
173            String broadcastPermission, Handler scheduler) {
174        if (receiver == null) {
175            // Allow retrieving current sticky broadcast; this is safe since we
176            // aren't actually registering a receiver.
177            return super.registerReceiver(null, filter, broadcastPermission, scheduler);
178        } else {
179            throw new ReceiverCallNotAllowedException(
180                    "BroadcastReceiver components are not allowed to register to receive intents");
181        }
182    }
183
184    @Override
185    public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
186            IntentFilter filter, String broadcastPermission, Handler scheduler) {
187        if (receiver == null) {
188            // Allow retrieving current sticky broadcast; this is safe since we
189            // aren't actually registering a receiver.
190            return super.registerReceiverAsUser(null, user, filter, broadcastPermission, scheduler);
191        } else {
192            throw new ReceiverCallNotAllowedException(
193                    "BroadcastReceiver components are not allowed to register to receive intents");
194        }
195    }
196
197    @Override
198    public boolean bindService(Intent service, ServiceConnection conn, int flags) {
199        throw new ReceiverCallNotAllowedException(
200                "BroadcastReceiver components are not allowed to bind to services");
201    }
202}
203
204/**
205 * Common implementation of Context API, which provides the base
206 * context object for Activity and other application components.
207 */
208class ContextImpl extends Context {
209    private final static String TAG = "ContextImpl";
210    private final static boolean DEBUG = false;
211
212    /**
213     * Map from package name, to preference name, to cached preferences.
214     */
215    private static ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>> sSharedPrefs;
216
217    final ActivityThread mMainThread;
218    final LoadedApk mPackageInfo;
219
220    private final IBinder mActivityToken;
221
222    private final UserHandle mUser;
223
224    private final ApplicationContentResolver mContentResolver;
225
226    private final String mBasePackageName;
227    private final String mOpPackageName;
228
229    private final ResourcesManager mResourcesManager;
230    private final Resources mResources;
231    private final Display mDisplay; // may be null if default display
232    private final DisplayAdjustments mDisplayAdjustments = new DisplayAdjustments();
233    private final Configuration mOverrideConfiguration;
234
235    private final boolean mRestricted;
236
237    private Context mOuterContext;
238    private int mThemeResource = 0;
239    private Resources.Theme mTheme = null;
240    private PackageManager mPackageManager;
241    private Context mReceiverRestrictedContext = null;
242
243    private final Object mSync = new Object();
244
245    @GuardedBy("mSync")
246    private File mDatabasesDir;
247    @GuardedBy("mSync")
248    private File mPreferencesDir;
249    @GuardedBy("mSync")
250    private File mFilesDir;
251    @GuardedBy("mSync")
252    private File mNoBackupFilesDir;
253    @GuardedBy("mSync")
254    private File mCacheDir;
255    @GuardedBy("mSync")
256    private File mCodeCacheDir;
257
258    @GuardedBy("mSync")
259    private File[] mExternalObbDirs;
260    @GuardedBy("mSync")
261    private File[] mExternalFilesDirs;
262    @GuardedBy("mSync")
263    private File[] mExternalCacheDirs;
264    @GuardedBy("mSync")
265    private File[] mExternalMediaDirs;
266
267    private static final String[] EMPTY_FILE_LIST = {};
268
269    /**
270     * Override this class when the system service constructor needs a
271     * ContextImpl.  Else, use StaticServiceFetcher below.
272     */
273    /*package*/ static class ServiceFetcher {
274        int mContextCacheIndex = -1;
275
276        /**
277         * Main entrypoint; only override if you don't need caching.
278         */
279        public Object getService(ContextImpl ctx) {
280            ArrayList<Object> cache = ctx.mServiceCache;
281            Object service;
282            synchronized (cache) {
283                if (cache.size() == 0) {
284                    // Initialize the cache vector on first access.
285                    // At this point sNextPerContextServiceCacheIndex
286                    // is the number of potential services that are
287                    // cached per-Context.
288                    for (int i = 0; i < sNextPerContextServiceCacheIndex; i++) {
289                        cache.add(null);
290                    }
291                } else {
292                    service = cache.get(mContextCacheIndex);
293                    if (service != null) {
294                        return service;
295                    }
296                }
297                service = createService(ctx);
298                cache.set(mContextCacheIndex, service);
299                return service;
300            }
301        }
302
303        /**
304         * Override this to create a new per-Context instance of the
305         * service.  getService() will handle locking and caching.
306         */
307        public Object createService(ContextImpl ctx) {
308            throw new RuntimeException("Not implemented");
309        }
310    }
311
312    /**
313     * Override this class for services to be cached process-wide.
314     */
315    abstract static class StaticServiceFetcher extends ServiceFetcher {
316        private Object mCachedInstance;
317
318        @Override
319        public final Object getService(ContextImpl unused) {
320            synchronized (StaticServiceFetcher.this) {
321                Object service = mCachedInstance;
322                if (service != null) {
323                    return service;
324                }
325                return mCachedInstance = createStaticService();
326            }
327        }
328
329        public abstract Object createStaticService();
330    }
331
332    private static final HashMap<String, ServiceFetcher> SYSTEM_SERVICE_MAP =
333            new HashMap<String, ServiceFetcher>();
334
335    private static int sNextPerContextServiceCacheIndex = 0;
336    private static void registerService(String serviceName, ServiceFetcher fetcher) {
337        if (!(fetcher instanceof StaticServiceFetcher)) {
338            fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
339        }
340        SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
341    }
342
343    // This one's defined separately and given a variable name so it
344    // can be re-used by getWallpaperManager(), avoiding a HashMap
345    // lookup.
346    private static ServiceFetcher WALLPAPER_FETCHER = new ServiceFetcher() {
347            public Object createService(ContextImpl ctx) {
348                return new WallpaperManager(ctx.getOuterContext(),
349                        ctx.mMainThread.getHandler());
350            }};
351
352    static {
353        registerService(ACCESSIBILITY_SERVICE, new ServiceFetcher() {
354                public Object getService(ContextImpl ctx) {
355                    return AccessibilityManager.getInstance(ctx);
356                }});
357
358        registerService(CAPTIONING_SERVICE, new ServiceFetcher() {
359                public Object getService(ContextImpl ctx) {
360                    return new CaptioningManager(ctx);
361                }});
362
363        registerService(ACCOUNT_SERVICE, new ServiceFetcher() {
364                public Object createService(ContextImpl ctx) {
365                    IBinder b = ServiceManager.getService(ACCOUNT_SERVICE);
366                    IAccountManager service = IAccountManager.Stub.asInterface(b);
367                    return new AccountManager(ctx, service);
368                }});
369
370        registerService(ACTIVITY_SERVICE, new ServiceFetcher() {
371                public Object createService(ContextImpl ctx) {
372                    return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());
373                }});
374
375        registerService(ALARM_SERVICE, new ServiceFetcher() {
376                public Object createService(ContextImpl ctx) {
377                    IBinder b = ServiceManager.getService(ALARM_SERVICE);
378                    IAlarmManager service = IAlarmManager.Stub.asInterface(b);
379                    return new AlarmManager(service, ctx);
380                }});
381
382        registerService(AUDIO_SERVICE, new ServiceFetcher() {
383                public Object createService(ContextImpl ctx) {
384                    return new AudioManager(ctx);
385                }});
386
387        registerService(MEDIA_ROUTER_SERVICE, new ServiceFetcher() {
388                public Object createService(ContextImpl ctx) {
389                    return new MediaRouter(ctx);
390                }});
391
392        registerService(BLUETOOTH_SERVICE, new ServiceFetcher() {
393                public Object createService(ContextImpl ctx) {
394                    return new BluetoothManager(ctx);
395                }});
396
397        registerService(HDMI_CONTROL_SERVICE, new StaticServiceFetcher() {
398                public Object createStaticService() {
399                    IBinder b = ServiceManager.getService(HDMI_CONTROL_SERVICE);
400                    return new HdmiControlManager(IHdmiControlService.Stub.asInterface(b));
401                }});
402
403        registerService(CLIPBOARD_SERVICE, new ServiceFetcher() {
404                public Object createService(ContextImpl ctx) {
405                    return new ClipboardManager(ctx.getOuterContext(),
406                            ctx.mMainThread.getHandler());
407                }});
408
409        registerService(CONNECTIVITY_SERVICE, new ServiceFetcher() {
410                public Object createService(ContextImpl ctx) {
411                    IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE);
412                    return new ConnectivityManager(IConnectivityManager.Stub.asInterface(b));
413                }});
414
415        registerService(COUNTRY_DETECTOR, new StaticServiceFetcher() {
416                public Object createStaticService() {
417                    IBinder b = ServiceManager.getService(COUNTRY_DETECTOR);
418                    return new CountryDetector(ICountryDetector.Stub.asInterface(b));
419                }});
420
421        registerService(DEVICE_POLICY_SERVICE, new ServiceFetcher() {
422                public Object createService(ContextImpl ctx) {
423                    return DevicePolicyManager.create(ctx, ctx.mMainThread.getHandler());
424                }});
425
426        registerService(DOWNLOAD_SERVICE, new ServiceFetcher() {
427                public Object createService(ContextImpl ctx) {
428                    return new DownloadManager(ctx.getContentResolver(), ctx.getPackageName());
429                }});
430
431        registerService(BATTERY_SERVICE, new ServiceFetcher() {
432                public Object createService(ContextImpl ctx) {
433                    return new BatteryManager();
434                }});
435
436        registerService(NFC_SERVICE, new ServiceFetcher() {
437                public Object createService(ContextImpl ctx) {
438                    return new NfcManager(ctx);
439                }});
440
441        registerService(DROPBOX_SERVICE, new StaticServiceFetcher() {
442                public Object createStaticService() {
443                    return createDropBoxManager();
444                }});
445
446        registerService(INPUT_SERVICE, new StaticServiceFetcher() {
447                public Object createStaticService() {
448                    return InputManager.getInstance();
449                }});
450
451        registerService(DISPLAY_SERVICE, new ServiceFetcher() {
452                @Override
453                public Object createService(ContextImpl ctx) {
454                    return new DisplayManager(ctx.getOuterContext());
455                }});
456
457        registerService(INPUT_METHOD_SERVICE, new StaticServiceFetcher() {
458                public Object createStaticService() {
459                    return InputMethodManager.getInstance();
460                }});
461
462        registerService(TEXT_SERVICES_MANAGER_SERVICE, new ServiceFetcher() {
463                public Object createService(ContextImpl ctx) {
464                    return TextServicesManager.getInstance();
465                }});
466
467        registerService(KEYGUARD_SERVICE, new ServiceFetcher() {
468                public Object getService(ContextImpl ctx) {
469                    // TODO: why isn't this caching it?  It wasn't
470                    // before, so I'm preserving the old behavior and
471                    // using getService(), instead of createService()
472                    // which would do the caching.
473                    return new KeyguardManager();
474                }});
475
476        registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
477                public Object createService(ContextImpl ctx) {
478                    return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
479                }});
480
481        registerService(LOCATION_SERVICE, new ServiceFetcher() {
482                public Object createService(ContextImpl ctx) {
483                    IBinder b = ServiceManager.getService(LOCATION_SERVICE);
484                    return new LocationManager(ctx, ILocationManager.Stub.asInterface(b));
485                }});
486
487        registerService(NETWORK_POLICY_SERVICE, new ServiceFetcher() {
488            @Override
489            public Object createService(ContextImpl ctx) {
490                return new NetworkPolicyManager(INetworkPolicyManager.Stub.asInterface(
491                        ServiceManager.getService(NETWORK_POLICY_SERVICE)));
492            }
493        });
494
495        registerService(NOTIFICATION_SERVICE, new ServiceFetcher() {
496                public Object createService(ContextImpl ctx) {
497                    final Context outerContext = ctx.getOuterContext();
498                    return new NotificationManager(
499                        new ContextThemeWrapper(outerContext,
500                                Resources.selectSystemTheme(0,
501                                        outerContext.getApplicationInfo().targetSdkVersion,
502                                        com.android.internal.R.style.Theme_Dialog,
503                                        com.android.internal.R.style.Theme_Holo_Dialog,
504                                        com.android.internal.R.style.Theme_DeviceDefault_Dialog,
505                                        com.android.internal.R.style.Theme_DeviceDefault_Light_Dialog)),
506                        ctx.mMainThread.getHandler());
507                }});
508
509        registerService(NSD_SERVICE, new ServiceFetcher() {
510                @Override
511                public Object createService(ContextImpl ctx) {
512                    IBinder b = ServiceManager.getService(NSD_SERVICE);
513                    INsdManager service = INsdManager.Stub.asInterface(b);
514                    return new NsdManager(ctx.getOuterContext(), service);
515                }});
516
517        // Note: this was previously cached in a static variable, but
518        // constructed using mMainThread.getHandler(), so converting
519        // it to be a regular Context-cached service...
520        registerService(POWER_SERVICE, new ServiceFetcher() {
521                public Object createService(ContextImpl ctx) {
522                    IBinder b = ServiceManager.getService(POWER_SERVICE);
523                    IPowerManager service = IPowerManager.Stub.asInterface(b);
524                    if (service == null) {
525                        Log.wtf(TAG, "Failed to get power manager service.");
526                    }
527                    return new PowerManager(ctx.getOuterContext(),
528                            service, ctx.mMainThread.getHandler());
529                }});
530
531        registerService(SEARCH_SERVICE, new ServiceFetcher() {
532                public Object createService(ContextImpl ctx) {
533                    return new SearchManager(ctx.getOuterContext(),
534                            ctx.mMainThread.getHandler());
535                }});
536
537        registerService(SENSOR_SERVICE, new ServiceFetcher() {
538                public Object createService(ContextImpl ctx) {
539                    return new SystemSensorManager(ctx.getOuterContext(),
540                      ctx.mMainThread.getHandler().getLooper());
541                }});
542
543        registerService(STATUS_BAR_SERVICE, new ServiceFetcher() {
544                public Object createService(ContextImpl ctx) {
545                    return new StatusBarManager(ctx.getOuterContext());
546                }});
547
548        registerService(STORAGE_SERVICE, new ServiceFetcher() {
549                public Object createService(ContextImpl ctx) {
550                    try {
551                        return new StorageManager(
552                                ctx.getContentResolver(), ctx.mMainThread.getHandler().getLooper());
553                    } catch (RemoteException rex) {
554                        Log.e(TAG, "Failed to create StorageManager", rex);
555                        return null;
556                    }
557                }});
558
559        registerService(TELEPHONY_SERVICE, new ServiceFetcher() {
560                public Object createService(ContextImpl ctx) {
561                    return new TelephonyManager(ctx.getOuterContext());
562                }});
563
564        registerService(TELECOM_SERVICE, new ServiceFetcher() {
565                public Object createService(ContextImpl ctx) {
566                    return new TelecomManager(ctx.getOuterContext());
567                }});
568
569        registerService(UI_MODE_SERVICE, new ServiceFetcher() {
570                public Object createService(ContextImpl ctx) {
571                    return new UiModeManager();
572                }});
573
574        registerService(USB_SERVICE, new ServiceFetcher() {
575                public Object createService(ContextImpl ctx) {
576                    IBinder b = ServiceManager.getService(USB_SERVICE);
577                    return new UsbManager(ctx, IUsbManager.Stub.asInterface(b));
578                }});
579
580        registerService(SERIAL_SERVICE, new ServiceFetcher() {
581                public Object createService(ContextImpl ctx) {
582                    IBinder b = ServiceManager.getService(SERIAL_SERVICE);
583                    return new SerialManager(ctx, ISerialManager.Stub.asInterface(b));
584                }});
585
586        registerService(VIBRATOR_SERVICE, new ServiceFetcher() {
587                public Object createService(ContextImpl ctx) {
588                    return new SystemVibrator(ctx);
589                }});
590
591        registerService(WALLPAPER_SERVICE, WALLPAPER_FETCHER);
592
593        registerService(WIFI_SERVICE, new ServiceFetcher() {
594                public Object createService(ContextImpl ctx) {
595                    IBinder b = ServiceManager.getService(WIFI_SERVICE);
596                    IWifiManager service = IWifiManager.Stub.asInterface(b);
597                    return new WifiManager(ctx.getOuterContext(), service);
598                }});
599
600        registerService(WIFI_P2P_SERVICE, new ServiceFetcher() {
601                public Object createService(ContextImpl ctx) {
602                    IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE);
603                    IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b);
604                    return new WifiP2pManager(service);
605                }});
606
607        registerService(WIFI_SCANNING_SERVICE, new ServiceFetcher() {
608            public Object createService(ContextImpl ctx) {
609                IBinder b = ServiceManager.getService(WIFI_SCANNING_SERVICE);
610                IWifiScanner service = IWifiScanner.Stub.asInterface(b);
611                return new WifiScanner(ctx.getOuterContext(), service);
612            }});
613
614        registerService(WIFI_RTT_SERVICE, new ServiceFetcher() {
615            public Object createService(ContextImpl ctx) {
616                IBinder b = ServiceManager.getService(WIFI_RTT_SERVICE);
617                IRttManager service = IRttManager.Stub.asInterface(b);
618                return new RttManager(ctx.getOuterContext(), service);
619            }});
620
621        registerService(ETHERNET_SERVICE, new ServiceFetcher() {
622                public Object createService(ContextImpl ctx) {
623                    IBinder b = ServiceManager.getService(ETHERNET_SERVICE);
624                    IEthernetManager service = IEthernetManager.Stub.asInterface(b);
625                    return new EthernetManager(ctx.getOuterContext(), service);
626                }});
627
628        registerService(WINDOW_SERVICE, new ServiceFetcher() {
629                Display mDefaultDisplay;
630                public Object getService(ContextImpl ctx) {
631                    Display display = ctx.mDisplay;
632                    if (display == null) {
633                        if (mDefaultDisplay == null) {
634                            DisplayManager dm = (DisplayManager)ctx.getOuterContext().
635                                    getSystemService(Context.DISPLAY_SERVICE);
636                            mDefaultDisplay = dm.getDisplay(Display.DEFAULT_DISPLAY);
637                        }
638                        display = mDefaultDisplay;
639                    }
640                    return new WindowManagerImpl(display);
641                }});
642
643        registerService(USER_SERVICE, new ServiceFetcher() {
644            public Object createService(ContextImpl ctx) {
645                IBinder b = ServiceManager.getService(USER_SERVICE);
646                IUserManager service = IUserManager.Stub.asInterface(b);
647                return new UserManager(ctx, service);
648            }});
649
650        registerService(APP_OPS_SERVICE, new ServiceFetcher() {
651            public Object createService(ContextImpl ctx) {
652                IBinder b = ServiceManager.getService(APP_OPS_SERVICE);
653                IAppOpsService service = IAppOpsService.Stub.asInterface(b);
654                return new AppOpsManager(ctx, service);
655            }});
656
657        registerService(CAMERA_SERVICE, new ServiceFetcher() {
658            public Object createService(ContextImpl ctx) {
659                return new CameraManager(ctx);
660            }
661        });
662
663        registerService(LAUNCHER_APPS_SERVICE, new ServiceFetcher() {
664            public Object createService(ContextImpl ctx) {
665                IBinder b = ServiceManager.getService(LAUNCHER_APPS_SERVICE);
666                ILauncherApps service = ILauncherApps.Stub.asInterface(b);
667                return new LauncherApps(ctx, service);
668            }
669        });
670
671        registerService(RESTRICTIONS_SERVICE, new ServiceFetcher() {
672            public Object createService(ContextImpl ctx) {
673                IBinder b = ServiceManager.getService(RESTRICTIONS_SERVICE);
674                IRestrictionsManager service = IRestrictionsManager.Stub.asInterface(b);
675                return new RestrictionsManager(ctx, service);
676            }
677        });
678        registerService(PRINT_SERVICE, new ServiceFetcher() {
679            public Object createService(ContextImpl ctx) {
680                IBinder iBinder = ServiceManager.getService(Context.PRINT_SERVICE);
681                IPrintManager service = IPrintManager.Stub.asInterface(iBinder);
682                return new PrintManager(ctx.getOuterContext(), service, UserHandle.myUserId(),
683                        UserHandle.getAppId(Process.myUid()));
684            }});
685
686        registerService(CONSUMER_IR_SERVICE, new ServiceFetcher() {
687            public Object createService(ContextImpl ctx) {
688                return new ConsumerIrManager(ctx);
689            }});
690
691        registerService(MEDIA_SESSION_SERVICE, new ServiceFetcher() {
692            public Object createService(ContextImpl ctx) {
693                return new MediaSessionManager(ctx);
694            }
695        });
696
697        registerService(TRUST_SERVICE, new ServiceFetcher() {
698            public Object createService(ContextImpl ctx) {
699                IBinder b = ServiceManager.getService(TRUST_SERVICE);
700                return new TrustManager(b);
701            }
702        });
703
704        registerService(FINGERPRINT_SERVICE, new ServiceFetcher() {
705            public Object createService(ContextImpl ctx) {
706                IBinder binder = ServiceManager.getService(FINGERPRINT_SERVICE);
707                IFingerprintService service = IFingerprintService.Stub.asInterface(binder);
708                return new FingerprintManager(ctx.getOuterContext(), service);
709            }
710        });
711
712        registerService(TV_INPUT_SERVICE, new ServiceFetcher() {
713            public Object createService(ContextImpl ctx) {
714                IBinder iBinder = ServiceManager.getService(TV_INPUT_SERVICE);
715                ITvInputManager service = ITvInputManager.Stub.asInterface(iBinder);
716                return new TvInputManager(service, UserHandle.myUserId());
717            }
718        });
719
720        registerService(NETWORK_SCORE_SERVICE, new ServiceFetcher() {
721            public Object createService(ContextImpl ctx) {
722                return new NetworkScoreManager(ctx);
723            }
724        });
725
726        registerService(USAGE_STATS_SERVICE, new ServiceFetcher() {
727            public Object createService(ContextImpl ctx) {
728                IBinder iBinder = ServiceManager.getService(USAGE_STATS_SERVICE);
729                IUsageStatsManager service = IUsageStatsManager.Stub.asInterface(iBinder);
730                return new UsageStatsManager(ctx.getOuterContext(), service);
731            }
732        });
733
734        registerService(JOB_SCHEDULER_SERVICE, new ServiceFetcher() {
735            public Object createService(ContextImpl ctx) {
736                IBinder b = ServiceManager.getService(JOB_SCHEDULER_SERVICE);
737                return new JobSchedulerImpl(IJobScheduler.Stub.asInterface(b));
738        }});
739
740        registerService(PERSISTENT_DATA_BLOCK_SERVICE, new ServiceFetcher() {
741            public Object createService(ContextImpl ctx) {
742                IBinder b = ServiceManager.getService(PERSISTENT_DATA_BLOCK_SERVICE);
743                IPersistentDataBlockService persistentDataBlockService =
744                        IPersistentDataBlockService.Stub.asInterface(b);
745                if (persistentDataBlockService != null) {
746                    return new PersistentDataBlockManager(persistentDataBlockService);
747                } else {
748                    // not supported
749                    return null;
750                }
751            }
752        });
753
754        registerService(MEDIA_PROJECTION_SERVICE, new ServiceFetcher() {
755                public Object createService(ContextImpl ctx) {
756                    return new MediaProjectionManager(ctx);
757                }
758        });
759
760        registerService(APPWIDGET_SERVICE, new ServiceFetcher() {
761            public Object createService(ContextImpl ctx) {
762                IBinder b = ServiceManager.getService(APPWIDGET_SERVICE);
763                return new AppWidgetManager(ctx, IAppWidgetService.Stub.asInterface(b));
764            }});
765    }
766
767    static ContextImpl getImpl(Context context) {
768        Context nextContext;
769        while ((context instanceof ContextWrapper) &&
770                (nextContext=((ContextWrapper)context).getBaseContext()) != null) {
771            context = nextContext;
772        }
773        return (ContextImpl)context;
774    }
775
776    // The system service cache for the system services that are
777    // cached per-ContextImpl.  Package-scoped to avoid accessor
778    // methods.
779    final ArrayList<Object> mServiceCache = new ArrayList<Object>();
780
781    @Override
782    public AssetManager getAssets() {
783        return getResources().getAssets();
784    }
785
786    @Override
787    public Resources getResources() {
788        return mResources;
789    }
790
791    @Override
792    public PackageManager getPackageManager() {
793        if (mPackageManager != null) {
794            return mPackageManager;
795        }
796
797        IPackageManager pm = ActivityThread.getPackageManager();
798        if (pm != null) {
799            // Doesn't matter if we make more than one instance.
800            return (mPackageManager = new ApplicationPackageManager(this, pm));
801        }
802
803        return null;
804    }
805
806    @Override
807    public ContentResolver getContentResolver() {
808        return mContentResolver;
809    }
810
811    @Override
812    public Looper getMainLooper() {
813        return mMainThread.getLooper();
814    }
815
816    @Override
817    public Context getApplicationContext() {
818        return (mPackageInfo != null) ?
819                mPackageInfo.getApplication() : mMainThread.getApplication();
820    }
821
822    @Override
823    public void setTheme(int resid) {
824        mThemeResource = resid;
825    }
826
827    @Override
828    public int getThemeResId() {
829        return mThemeResource;
830    }
831
832    @Override
833    public Resources.Theme getTheme() {
834        if (mTheme == null) {
835            mThemeResource = Resources.selectDefaultTheme(mThemeResource,
836                    getOuterContext().getApplicationInfo().targetSdkVersion);
837            mTheme = mResources.newTheme();
838            mTheme.applyStyle(mThemeResource, true);
839        }
840        return mTheme;
841    }
842
843    @Override
844    public ClassLoader getClassLoader() {
845        return mPackageInfo != null ?
846                mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
847    }
848
849    @Override
850    public String getPackageName() {
851        if (mPackageInfo != null) {
852            return mPackageInfo.getPackageName();
853        }
854        // No mPackageInfo means this is a Context for the system itself,
855        // and this here is its name.
856        return "android";
857    }
858
859    /** @hide */
860    @Override
861    public String getBasePackageName() {
862        return mBasePackageName != null ? mBasePackageName : getPackageName();
863    }
864
865    /** @hide */
866    @Override
867    public String getOpPackageName() {
868        return mOpPackageName != null ? mOpPackageName : getBasePackageName();
869    }
870
871    @Override
872    public ApplicationInfo getApplicationInfo() {
873        if (mPackageInfo != null) {
874            return mPackageInfo.getApplicationInfo();
875        }
876        throw new RuntimeException("Not supported in system context");
877    }
878
879    @Override
880    public String getPackageResourcePath() {
881        if (mPackageInfo != null) {
882            return mPackageInfo.getResDir();
883        }
884        throw new RuntimeException("Not supported in system context");
885    }
886
887    @Override
888    public String getPackageCodePath() {
889        if (mPackageInfo != null) {
890            return mPackageInfo.getAppDir();
891        }
892        throw new RuntimeException("Not supported in system context");
893    }
894
895    public File getSharedPrefsFile(String name) {
896        return makeFilename(getPreferencesDir(), name + ".xml");
897    }
898
899    @Override
900    public SharedPreferences getSharedPreferences(String name, int mode) {
901        SharedPreferencesImpl sp;
902        synchronized (ContextImpl.class) {
903            if (sSharedPrefs == null) {
904                sSharedPrefs = new ArrayMap<String, ArrayMap<String, SharedPreferencesImpl>>();
905            }
906
907            final String packageName = getPackageName();
908            ArrayMap<String, SharedPreferencesImpl> packagePrefs = sSharedPrefs.get(packageName);
909            if (packagePrefs == null) {
910                packagePrefs = new ArrayMap<String, SharedPreferencesImpl>();
911                sSharedPrefs.put(packageName, packagePrefs);
912            }
913
914            // At least one application in the world actually passes in a null
915            // name.  This happened to work because when we generated the file name
916            // we would stringify it to "null.xml".  Nice.
917            if (mPackageInfo.getApplicationInfo().targetSdkVersion <
918                    Build.VERSION_CODES.KITKAT) {
919                if (name == null) {
920                    name = "null";
921                }
922            }
923
924            sp = packagePrefs.get(name);
925            if (sp == null) {
926                File prefsFile = getSharedPrefsFile(name);
927                sp = new SharedPreferencesImpl(prefsFile, mode);
928                packagePrefs.put(name, sp);
929                return sp;
930            }
931        }
932        if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
933            getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
934            // If somebody else (some other process) changed the prefs
935            // file behind our back, we reload it.  This has been the
936            // historical (if undocumented) behavior.
937            sp.startReloadIfChangedUnexpectedly();
938        }
939        return sp;
940    }
941
942    private File getPreferencesDir() {
943        synchronized (mSync) {
944            if (mPreferencesDir == null) {
945                mPreferencesDir = new File(getDataDirFile(), "shared_prefs");
946            }
947            return mPreferencesDir;
948        }
949    }
950
951    @Override
952    public FileInputStream openFileInput(String name)
953        throws FileNotFoundException {
954        File f = makeFilename(getFilesDir(), name);
955        return new FileInputStream(f);
956    }
957
958    @Override
959    public FileOutputStream openFileOutput(String name, int mode)
960        throws FileNotFoundException {
961        final boolean append = (mode&MODE_APPEND) != 0;
962        File f = makeFilename(getFilesDir(), name);
963        try {
964            FileOutputStream fos = new FileOutputStream(f, append);
965            setFilePermissionsFromMode(f.getPath(), mode, 0);
966            return fos;
967        } catch (FileNotFoundException e) {
968        }
969
970        File parent = f.getParentFile();
971        parent.mkdir();
972        FileUtils.setPermissions(
973            parent.getPath(),
974            FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
975            -1, -1);
976        FileOutputStream fos = new FileOutputStream(f, append);
977        setFilePermissionsFromMode(f.getPath(), mode, 0);
978        return fos;
979    }
980
981    @Override
982    public boolean deleteFile(String name) {
983        File f = makeFilename(getFilesDir(), name);
984        return f.delete();
985    }
986
987    // Common-path handling of app data dir creation
988    private static File createFilesDirLocked(File file) {
989        if (!file.exists()) {
990            if (!file.mkdirs()) {
991                if (file.exists()) {
992                    // spurious failure; probably racing with another process for this app
993                    return file;
994                }
995                Log.w(TAG, "Unable to create files subdir " + file.getPath());
996                return null;
997            }
998            FileUtils.setPermissions(
999                    file.getPath(),
1000                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
1001                    -1, -1);
1002        }
1003        return file;
1004    }
1005
1006    @Override
1007    public File getFilesDir() {
1008        synchronized (mSync) {
1009            if (mFilesDir == null) {
1010                mFilesDir = new File(getDataDirFile(), "files");
1011            }
1012            return createFilesDirLocked(mFilesDir);
1013        }
1014    }
1015
1016    @Override
1017    public File getNoBackupFilesDir() {
1018        synchronized (mSync) {
1019            if (mNoBackupFilesDir == null) {
1020                mNoBackupFilesDir = new File(getDataDirFile(), "no_backup");
1021            }
1022            return createFilesDirLocked(mNoBackupFilesDir);
1023        }
1024    }
1025
1026    @Override
1027    public File getExternalFilesDir(String type) {
1028        // Operates on primary external storage
1029        return getExternalFilesDirs(type)[0];
1030    }
1031
1032    @Override
1033    public File[] getExternalFilesDirs(String type) {
1034        synchronized (mSync) {
1035            if (mExternalFilesDirs == null) {
1036                mExternalFilesDirs = Environment.buildExternalStorageAppFilesDirs(getPackageName());
1037            }
1038
1039            // Splice in requested type, if any
1040            File[] dirs = mExternalFilesDirs;
1041            if (type != null) {
1042                dirs = Environment.buildPaths(dirs, type);
1043            }
1044
1045            // Create dirs if needed
1046            return ensureDirsExistOrFilter(dirs);
1047        }
1048    }
1049
1050    @Override
1051    public File getObbDir() {
1052        // Operates on primary external storage
1053        return getObbDirs()[0];
1054    }
1055
1056    @Override
1057    public File[] getObbDirs() {
1058        synchronized (mSync) {
1059            if (mExternalObbDirs == null) {
1060                mExternalObbDirs = Environment.buildExternalStorageAppObbDirs(getPackageName());
1061            }
1062
1063            // Create dirs if needed
1064            return ensureDirsExistOrFilter(mExternalObbDirs);
1065        }
1066    }
1067
1068    @Override
1069    public File getCacheDir() {
1070        synchronized (mSync) {
1071            if (mCacheDir == null) {
1072                mCacheDir = new File(getDataDirFile(), "cache");
1073            }
1074            return createFilesDirLocked(mCacheDir);
1075        }
1076    }
1077
1078    @Override
1079    public File getCodeCacheDir() {
1080        synchronized (mSync) {
1081            if (mCodeCacheDir == null) {
1082                mCodeCacheDir = new File(getDataDirFile(), "code_cache");
1083            }
1084            return createFilesDirLocked(mCodeCacheDir);
1085        }
1086    }
1087
1088    @Override
1089    public File getExternalCacheDir() {
1090        // Operates on primary external storage
1091        return getExternalCacheDirs()[0];
1092    }
1093
1094    @Override
1095    public File[] getExternalCacheDirs() {
1096        synchronized (mSync) {
1097            if (mExternalCacheDirs == null) {
1098                mExternalCacheDirs = Environment.buildExternalStorageAppCacheDirs(getPackageName());
1099            }
1100
1101            // Create dirs if needed
1102            return ensureDirsExistOrFilter(mExternalCacheDirs);
1103        }
1104    }
1105
1106    @Override
1107    public File[] getExternalMediaDirs() {
1108        synchronized (mSync) {
1109            if (mExternalMediaDirs == null) {
1110                mExternalMediaDirs = Environment.buildExternalStorageAppMediaDirs(getPackageName());
1111            }
1112
1113            // Create dirs if needed
1114            return ensureDirsExistOrFilter(mExternalMediaDirs);
1115        }
1116    }
1117
1118    @Override
1119    public File getFileStreamPath(String name) {
1120        return makeFilename(getFilesDir(), name);
1121    }
1122
1123    @Override
1124    public String[] fileList() {
1125        final String[] list = getFilesDir().list();
1126        return (list != null) ? list : EMPTY_FILE_LIST;
1127    }
1128
1129    @Override
1130    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) {
1131        return openOrCreateDatabase(name, mode, factory, null);
1132    }
1133
1134    @Override
1135    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory,
1136            DatabaseErrorHandler errorHandler) {
1137        File f = validateFilePath(name, true);
1138        int flags = SQLiteDatabase.CREATE_IF_NECESSARY;
1139        if ((mode & MODE_ENABLE_WRITE_AHEAD_LOGGING) != 0) {
1140            flags |= SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING;
1141        }
1142        SQLiteDatabase db = SQLiteDatabase.openDatabase(f.getPath(), factory, flags, errorHandler);
1143        setFilePermissionsFromMode(f.getPath(), mode, 0);
1144        return db;
1145    }
1146
1147    @Override
1148    public boolean deleteDatabase(String name) {
1149        try {
1150            File f = validateFilePath(name, false);
1151            return SQLiteDatabase.deleteDatabase(f);
1152        } catch (Exception e) {
1153        }
1154        return false;
1155    }
1156
1157    @Override
1158    public File getDatabasePath(String name) {
1159        return validateFilePath(name, false);
1160    }
1161
1162    @Override
1163    public String[] databaseList() {
1164        final String[] list = getDatabasesDir().list();
1165        return (list != null) ? list : EMPTY_FILE_LIST;
1166    }
1167
1168
1169    private File getDatabasesDir() {
1170        synchronized (mSync) {
1171            if (mDatabasesDir == null) {
1172                mDatabasesDir = new File(getDataDirFile(), "databases");
1173            }
1174            if (mDatabasesDir.getPath().equals("databases")) {
1175                mDatabasesDir = new File("/data/system");
1176            }
1177            return mDatabasesDir;
1178        }
1179    }
1180
1181    @Override
1182    public Drawable getWallpaper() {
1183        return getWallpaperManager().getDrawable();
1184    }
1185
1186    @Override
1187    public Drawable peekWallpaper() {
1188        return getWallpaperManager().peekDrawable();
1189    }
1190
1191    @Override
1192    public int getWallpaperDesiredMinimumWidth() {
1193        return getWallpaperManager().getDesiredMinimumWidth();
1194    }
1195
1196    @Override
1197    public int getWallpaperDesiredMinimumHeight() {
1198        return getWallpaperManager().getDesiredMinimumHeight();
1199    }
1200
1201    @Override
1202    public void setWallpaper(Bitmap bitmap) throws IOException  {
1203        getWallpaperManager().setBitmap(bitmap);
1204    }
1205
1206    @Override
1207    public void setWallpaper(InputStream data) throws IOException {
1208        getWallpaperManager().setStream(data);
1209    }
1210
1211    @Override
1212    public void clearWallpaper() throws IOException {
1213        getWallpaperManager().clear();
1214    }
1215
1216    @Override
1217    public void startActivity(Intent intent) {
1218        warnIfCallingFromSystemProcess();
1219        startActivity(intent, null);
1220    }
1221
1222    /** @hide */
1223    @Override
1224    public void startActivityAsUser(Intent intent, UserHandle user) {
1225        startActivityAsUser(intent, null, user);
1226    }
1227
1228    @Override
1229    public void startActivity(Intent intent, Bundle options) {
1230        warnIfCallingFromSystemProcess();
1231        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1232            throw new AndroidRuntimeException(
1233                    "Calling startActivity() from outside of an Activity "
1234                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
1235                    + " Is this really what you want?");
1236        }
1237        mMainThread.getInstrumentation().execStartActivity(
1238            getOuterContext(), mMainThread.getApplicationThread(), null,
1239            (Activity)null, intent, -1, options);
1240    }
1241
1242    /** @hide */
1243    @Override
1244    public void startActivityAsUser(Intent intent, Bundle options, UserHandle user) {
1245        try {
1246            ActivityManagerNative.getDefault().startActivityAsUser(
1247                mMainThread.getApplicationThread(), getBasePackageName(), intent,
1248                intent.resolveTypeIfNeeded(getContentResolver()),
1249                null, null, 0, Intent.FLAG_ACTIVITY_NEW_TASK, null, options,
1250                user.getIdentifier());
1251        } catch (RemoteException re) {
1252        }
1253    }
1254
1255    @Override
1256    public void startActivities(Intent[] intents) {
1257        warnIfCallingFromSystemProcess();
1258        startActivities(intents, null);
1259    }
1260
1261    /** @hide */
1262    @Override
1263    public void startActivitiesAsUser(Intent[] intents, Bundle options, UserHandle userHandle) {
1264        if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1265            throw new AndroidRuntimeException(
1266                    "Calling startActivities() from outside of an Activity "
1267                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1268                    + " Is this really what you want?");
1269        }
1270        mMainThread.getInstrumentation().execStartActivitiesAsUser(
1271            getOuterContext(), mMainThread.getApplicationThread(), null,
1272            (Activity)null, intents, options, userHandle.getIdentifier());
1273    }
1274
1275    @Override
1276    public void startActivities(Intent[] intents, Bundle options) {
1277        warnIfCallingFromSystemProcess();
1278        if ((intents[0].getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
1279            throw new AndroidRuntimeException(
1280                    "Calling startActivities() from outside of an Activity "
1281                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag on first Intent."
1282                    + " Is this really what you want?");
1283        }
1284        mMainThread.getInstrumentation().execStartActivities(
1285            getOuterContext(), mMainThread.getApplicationThread(), null,
1286            (Activity)null, intents, options);
1287    }
1288
1289    @Override
1290    public void startIntentSender(IntentSender intent,
1291            Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags)
1292            throws IntentSender.SendIntentException {
1293        startIntentSender(intent, fillInIntent, flagsMask, flagsValues, extraFlags, null);
1294    }
1295
1296    @Override
1297    public void startIntentSender(IntentSender intent, Intent fillInIntent,
1298            int flagsMask, int flagsValues, int extraFlags, Bundle options)
1299            throws IntentSender.SendIntentException {
1300        try {
1301            String resolvedType = null;
1302            if (fillInIntent != null) {
1303                fillInIntent.migrateExtraStreamToClipData();
1304                fillInIntent.prepareToLeaveProcess();
1305                resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
1306            }
1307            int result = ActivityManagerNative.getDefault()
1308                .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
1309                        fillInIntent, resolvedType, null, null,
1310                        0, flagsMask, flagsValues, options);
1311            if (result == ActivityManager.START_CANCELED) {
1312                throw new IntentSender.SendIntentException();
1313            }
1314            Instrumentation.checkStartActivityResult(result, null);
1315        } catch (RemoteException e) {
1316        }
1317    }
1318
1319    @Override
1320    public void sendBroadcast(Intent intent) {
1321        warnIfCallingFromSystemProcess();
1322        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1323        try {
1324            intent.prepareToLeaveProcess();
1325            ActivityManagerNative.getDefault().broadcastIntent(
1326                mMainThread.getApplicationThread(), intent, resolvedType, null,
1327                Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, false,
1328                getUserId());
1329        } catch (RemoteException e) {
1330        }
1331    }
1332
1333    @Override
1334    public void sendBroadcast(Intent intent, String receiverPermission) {
1335        warnIfCallingFromSystemProcess();
1336        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1337        try {
1338            intent.prepareToLeaveProcess();
1339            ActivityManagerNative.getDefault().broadcastIntent(
1340                mMainThread.getApplicationThread(), intent, resolvedType, null,
1341                Activity.RESULT_OK, null, null, receiverPermission, AppOpsManager.OP_NONE,
1342                false, false, getUserId());
1343        } catch (RemoteException e) {
1344        }
1345    }
1346
1347    @Override
1348    public void sendBroadcast(Intent intent, String receiverPermission, int appOp) {
1349        warnIfCallingFromSystemProcess();
1350        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1351        try {
1352            intent.prepareToLeaveProcess();
1353            ActivityManagerNative.getDefault().broadcastIntent(
1354                mMainThread.getApplicationThread(), intent, resolvedType, null,
1355                Activity.RESULT_OK, null, null, receiverPermission, appOp, false, false,
1356                getUserId());
1357        } catch (RemoteException e) {
1358        }
1359    }
1360
1361    @Override
1362    public void sendOrderedBroadcast(Intent intent,
1363            String receiverPermission) {
1364        warnIfCallingFromSystemProcess();
1365        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1366        try {
1367            intent.prepareToLeaveProcess();
1368            ActivityManagerNative.getDefault().broadcastIntent(
1369                mMainThread.getApplicationThread(), intent, resolvedType, null,
1370                Activity.RESULT_OK, null, null, receiverPermission, AppOpsManager.OP_NONE, true, false,
1371                getUserId());
1372        } catch (RemoteException e) {
1373        }
1374    }
1375
1376    @Override
1377    public void sendOrderedBroadcast(Intent intent,
1378            String receiverPermission, BroadcastReceiver resultReceiver,
1379            Handler scheduler, int initialCode, String initialData,
1380            Bundle initialExtras) {
1381        sendOrderedBroadcast(intent, receiverPermission, AppOpsManager.OP_NONE,
1382                resultReceiver, scheduler, initialCode, initialData, initialExtras);
1383    }
1384
1385    @Override
1386    public void sendOrderedBroadcast(Intent intent,
1387            String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1388            Handler scheduler, int initialCode, String initialData,
1389            Bundle initialExtras) {
1390        warnIfCallingFromSystemProcess();
1391        IIntentReceiver rd = null;
1392        if (resultReceiver != null) {
1393            if (mPackageInfo != null) {
1394                if (scheduler == null) {
1395                    scheduler = mMainThread.getHandler();
1396                }
1397                rd = mPackageInfo.getReceiverDispatcher(
1398                    resultReceiver, getOuterContext(), scheduler,
1399                    mMainThread.getInstrumentation(), false);
1400            } else {
1401                if (scheduler == null) {
1402                    scheduler = mMainThread.getHandler();
1403                }
1404                rd = new LoadedApk.ReceiverDispatcher(
1405                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1406            }
1407        }
1408        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1409        try {
1410            intent.prepareToLeaveProcess();
1411            ActivityManagerNative.getDefault().broadcastIntent(
1412                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1413                initialCode, initialData, initialExtras, receiverPermission, appOp,
1414                    true, false, getUserId());
1415        } catch (RemoteException e) {
1416        }
1417    }
1418
1419    @Override
1420    public void sendBroadcastAsUser(Intent intent, UserHandle user) {
1421        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1422        try {
1423            intent.prepareToLeaveProcess();
1424            ActivityManagerNative.getDefault().broadcastIntent(mMainThread.getApplicationThread(),
1425                    intent, resolvedType, null, Activity.RESULT_OK, null, null, null,
1426                    AppOpsManager.OP_NONE, false, false, user.getIdentifier());
1427        } catch (RemoteException e) {
1428        }
1429    }
1430
1431    @Override
1432    public void sendBroadcastAsUser(Intent intent, UserHandle user,
1433            String receiverPermission) {
1434        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1435        try {
1436            intent.prepareToLeaveProcess();
1437            ActivityManagerNative.getDefault().broadcastIntent(
1438                mMainThread.getApplicationThread(), intent, resolvedType, null,
1439                Activity.RESULT_OK, null, null, receiverPermission, AppOpsManager.OP_NONE, false, false,
1440                user.getIdentifier());
1441        } catch (RemoteException e) {
1442        }
1443    }
1444
1445    @Override
1446    public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1447            String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler,
1448            int initialCode, String initialData, Bundle initialExtras) {
1449        sendOrderedBroadcastAsUser(intent, user, receiverPermission, AppOpsManager.OP_NONE,
1450                resultReceiver, scheduler, initialCode, initialData, initialExtras);
1451    }
1452
1453    @Override
1454    public void sendOrderedBroadcastAsUser(Intent intent, UserHandle user,
1455            String receiverPermission, int appOp, BroadcastReceiver resultReceiver,
1456            Handler scheduler,
1457            int initialCode, String initialData, Bundle initialExtras) {
1458        IIntentReceiver rd = null;
1459        if (resultReceiver != null) {
1460            if (mPackageInfo != null) {
1461                if (scheduler == null) {
1462                    scheduler = mMainThread.getHandler();
1463                }
1464                rd = mPackageInfo.getReceiverDispatcher(
1465                    resultReceiver, getOuterContext(), scheduler,
1466                    mMainThread.getInstrumentation(), false);
1467            } else {
1468                if (scheduler == null) {
1469                    scheduler = mMainThread.getHandler();
1470                }
1471                rd = new LoadedApk.ReceiverDispatcher(
1472                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1473            }
1474        }
1475        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1476        try {
1477            intent.prepareToLeaveProcess();
1478            ActivityManagerNative.getDefault().broadcastIntent(
1479                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1480                initialCode, initialData, initialExtras, receiverPermission,
1481                    appOp, true, false, user.getIdentifier());
1482        } catch (RemoteException e) {
1483        }
1484    }
1485
1486    @Override
1487    public void sendStickyBroadcast(Intent intent) {
1488        warnIfCallingFromSystemProcess();
1489        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1490        try {
1491            intent.prepareToLeaveProcess();
1492            ActivityManagerNative.getDefault().broadcastIntent(
1493                mMainThread.getApplicationThread(), intent, resolvedType, null,
1494                Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, true,
1495                getUserId());
1496        } catch (RemoteException e) {
1497        }
1498    }
1499
1500    @Override
1501    public void sendStickyOrderedBroadcast(Intent intent,
1502            BroadcastReceiver resultReceiver,
1503            Handler scheduler, int initialCode, String initialData,
1504            Bundle initialExtras) {
1505        warnIfCallingFromSystemProcess();
1506        IIntentReceiver rd = null;
1507        if (resultReceiver != null) {
1508            if (mPackageInfo != null) {
1509                if (scheduler == null) {
1510                    scheduler = mMainThread.getHandler();
1511                }
1512                rd = mPackageInfo.getReceiverDispatcher(
1513                    resultReceiver, getOuterContext(), scheduler,
1514                    mMainThread.getInstrumentation(), false);
1515            } else {
1516                if (scheduler == null) {
1517                    scheduler = mMainThread.getHandler();
1518                }
1519                rd = new LoadedApk.ReceiverDispatcher(
1520                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1521            }
1522        }
1523        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1524        try {
1525            intent.prepareToLeaveProcess();
1526            ActivityManagerNative.getDefault().broadcastIntent(
1527                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1528                initialCode, initialData, initialExtras, null,
1529                    AppOpsManager.OP_NONE, true, true, getUserId());
1530        } catch (RemoteException e) {
1531        }
1532    }
1533
1534    @Override
1535    public void removeStickyBroadcast(Intent intent) {
1536        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1537        if (resolvedType != null) {
1538            intent = new Intent(intent);
1539            intent.setDataAndType(intent.getData(), resolvedType);
1540        }
1541        try {
1542            intent.prepareToLeaveProcess();
1543            ActivityManagerNative.getDefault().unbroadcastIntent(
1544                    mMainThread.getApplicationThread(), intent, getUserId());
1545        } catch (RemoteException e) {
1546        }
1547    }
1548
1549    @Override
1550    public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
1551        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1552        try {
1553            intent.prepareToLeaveProcess();
1554            ActivityManagerNative.getDefault().broadcastIntent(
1555                mMainThread.getApplicationThread(), intent, resolvedType, null,
1556                Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, true, user.getIdentifier());
1557        } catch (RemoteException e) {
1558        }
1559    }
1560
1561    @Override
1562    public void sendStickyOrderedBroadcastAsUser(Intent intent,
1563            UserHandle user, BroadcastReceiver resultReceiver,
1564            Handler scheduler, int initialCode, String initialData,
1565            Bundle initialExtras) {
1566        IIntentReceiver rd = null;
1567        if (resultReceiver != null) {
1568            if (mPackageInfo != null) {
1569                if (scheduler == null) {
1570                    scheduler = mMainThread.getHandler();
1571                }
1572                rd = mPackageInfo.getReceiverDispatcher(
1573                    resultReceiver, getOuterContext(), scheduler,
1574                    mMainThread.getInstrumentation(), false);
1575            } else {
1576                if (scheduler == null) {
1577                    scheduler = mMainThread.getHandler();
1578                }
1579                rd = new LoadedApk.ReceiverDispatcher(
1580                        resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver();
1581            }
1582        }
1583        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1584        try {
1585            intent.prepareToLeaveProcess();
1586            ActivityManagerNative.getDefault().broadcastIntent(
1587                mMainThread.getApplicationThread(), intent, resolvedType, rd,
1588                initialCode, initialData, initialExtras, null,
1589                    AppOpsManager.OP_NONE, true, true, user.getIdentifier());
1590        } catch (RemoteException e) {
1591        }
1592    }
1593
1594    @Override
1595    public void removeStickyBroadcastAsUser(Intent intent, UserHandle user) {
1596        String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
1597        if (resolvedType != null) {
1598            intent = new Intent(intent);
1599            intent.setDataAndType(intent.getData(), resolvedType);
1600        }
1601        try {
1602            intent.prepareToLeaveProcess();
1603            ActivityManagerNative.getDefault().unbroadcastIntent(
1604                    mMainThread.getApplicationThread(), intent, user.getIdentifier());
1605        } catch (RemoteException e) {
1606        }
1607    }
1608
1609    @Override
1610    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
1611        return registerReceiver(receiver, filter, null, null);
1612    }
1613
1614    @Override
1615    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter,
1616            String broadcastPermission, Handler scheduler) {
1617        return registerReceiverInternal(receiver, getUserId(),
1618                filter, broadcastPermission, scheduler, getOuterContext());
1619    }
1620
1621    @Override
1622    public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
1623            IntentFilter filter, String broadcastPermission, Handler scheduler) {
1624        return registerReceiverInternal(receiver, user.getIdentifier(),
1625                filter, broadcastPermission, scheduler, getOuterContext());
1626    }
1627
1628    private Intent registerReceiverInternal(BroadcastReceiver receiver, int userId,
1629            IntentFilter filter, String broadcastPermission,
1630            Handler scheduler, Context context) {
1631        IIntentReceiver rd = null;
1632        if (receiver != null) {
1633            if (mPackageInfo != null && context != null) {
1634                if (scheduler == null) {
1635                    scheduler = mMainThread.getHandler();
1636                }
1637                rd = mPackageInfo.getReceiverDispatcher(
1638                    receiver, context, scheduler,
1639                    mMainThread.getInstrumentation(), true);
1640            } else {
1641                if (scheduler == null) {
1642                    scheduler = mMainThread.getHandler();
1643                }
1644                rd = new LoadedApk.ReceiverDispatcher(
1645                        receiver, context, scheduler, null, true).getIIntentReceiver();
1646            }
1647        }
1648        try {
1649            return ActivityManagerNative.getDefault().registerReceiver(
1650                    mMainThread.getApplicationThread(), mBasePackageName,
1651                    rd, filter, broadcastPermission, userId);
1652        } catch (RemoteException e) {
1653            return null;
1654        }
1655    }
1656
1657    @Override
1658    public void unregisterReceiver(BroadcastReceiver receiver) {
1659        if (mPackageInfo != null) {
1660            IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher(
1661                    getOuterContext(), receiver);
1662            try {
1663                ActivityManagerNative.getDefault().unregisterReceiver(rd);
1664            } catch (RemoteException e) {
1665            }
1666        } else {
1667            throw new RuntimeException("Not supported in system context");
1668        }
1669    }
1670
1671    private void validateServiceIntent(Intent service) {
1672        if (service.getComponent() == null && service.getPackage() == null) {
1673            if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1674                IllegalArgumentException ex = new IllegalArgumentException(
1675                        "Service Intent must be explicit: " + service);
1676                throw ex;
1677            } else {
1678                Log.w(TAG, "Implicit intents with startService are not safe: " + service
1679                        + " " + Debug.getCallers(2, 3));
1680            }
1681        }
1682    }
1683
1684    @Override
1685    public ComponentName startService(Intent service) {
1686        warnIfCallingFromSystemProcess();
1687        return startServiceCommon(service, mUser);
1688    }
1689
1690    @Override
1691    public boolean stopService(Intent service) {
1692        warnIfCallingFromSystemProcess();
1693        return stopServiceCommon(service, mUser);
1694    }
1695
1696    @Override
1697    public ComponentName startServiceAsUser(Intent service, UserHandle user) {
1698        return startServiceCommon(service, user);
1699    }
1700
1701    private ComponentName startServiceCommon(Intent service, UserHandle user) {
1702        try {
1703            validateServiceIntent(service);
1704            service.prepareToLeaveProcess();
1705            ComponentName cn = ActivityManagerNative.getDefault().startService(
1706                mMainThread.getApplicationThread(), service,
1707                service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
1708            if (cn != null) {
1709                if (cn.getPackageName().equals("!")) {
1710                    throw new SecurityException(
1711                            "Not allowed to start service " + service
1712                            + " without permission " + cn.getClassName());
1713                } else if (cn.getPackageName().equals("!!")) {
1714                    throw new SecurityException(
1715                            "Unable to start service " + service
1716                            + ": " + cn.getClassName());
1717                }
1718            }
1719            return cn;
1720        } catch (RemoteException e) {
1721            return null;
1722        }
1723    }
1724
1725    @Override
1726    public boolean stopServiceAsUser(Intent service, UserHandle user) {
1727        return stopServiceCommon(service, user);
1728    }
1729
1730    private boolean stopServiceCommon(Intent service, UserHandle user) {
1731        try {
1732            validateServiceIntent(service);
1733            service.prepareToLeaveProcess();
1734            int res = ActivityManagerNative.getDefault().stopService(
1735                mMainThread.getApplicationThread(), service,
1736                service.resolveTypeIfNeeded(getContentResolver()), user.getIdentifier());
1737            if (res < 0) {
1738                throw new SecurityException(
1739                        "Not allowed to stop service " + service);
1740            }
1741            return res != 0;
1742        } catch (RemoteException e) {
1743            return false;
1744        }
1745    }
1746
1747    @Override
1748    public boolean bindService(Intent service, ServiceConnection conn,
1749            int flags) {
1750        warnIfCallingFromSystemProcess();
1751        return bindServiceCommon(service, conn, flags, Process.myUserHandle());
1752    }
1753
1754    /** @hide */
1755    @Override
1756    public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
1757            UserHandle user) {
1758        return bindServiceCommon(service, conn, flags, user);
1759    }
1760
1761    private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
1762            UserHandle user) {
1763        IServiceConnection sd;
1764        if (conn == null) {
1765            throw new IllegalArgumentException("connection is null");
1766        }
1767        if (mPackageInfo != null) {
1768            sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
1769                    mMainThread.getHandler(), flags);
1770        } else {
1771            throw new RuntimeException("Not supported in system context");
1772        }
1773        validateServiceIntent(service);
1774        try {
1775            IBinder token = getActivityToken();
1776            if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
1777                    && mPackageInfo.getApplicationInfo().targetSdkVersion
1778                    < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
1779                flags |= BIND_WAIVE_PRIORITY;
1780            }
1781            service.prepareToLeaveProcess();
1782            int res = ActivityManagerNative.getDefault().bindService(
1783                mMainThread.getApplicationThread(), getActivityToken(),
1784                service, service.resolveTypeIfNeeded(getContentResolver()),
1785                sd, flags, user.getIdentifier());
1786            if (res < 0) {
1787                throw new SecurityException(
1788                        "Not allowed to bind to service " + service);
1789            }
1790            return res != 0;
1791        } catch (RemoteException e) {
1792            return false;
1793        }
1794    }
1795
1796    @Override
1797    public void unbindService(ServiceConnection conn) {
1798        if (conn == null) {
1799            throw new IllegalArgumentException("connection is null");
1800        }
1801        if (mPackageInfo != null) {
1802            IServiceConnection sd = mPackageInfo.forgetServiceDispatcher(
1803                    getOuterContext(), conn);
1804            try {
1805                ActivityManagerNative.getDefault().unbindService(sd);
1806            } catch (RemoteException e) {
1807            }
1808        } else {
1809            throw new RuntimeException("Not supported in system context");
1810        }
1811    }
1812
1813    @Override
1814    public boolean startInstrumentation(ComponentName className,
1815            String profileFile, Bundle arguments) {
1816        try {
1817            if (arguments != null) {
1818                arguments.setAllowFds(false);
1819            }
1820            return ActivityManagerNative.getDefault().startInstrumentation(
1821                    className, profileFile, 0, arguments, null, null, getUserId(),
1822                    null /* ABI override */);
1823        } catch (RemoteException e) {
1824            // System has crashed, nothing we can do.
1825        }
1826        return false;
1827    }
1828
1829    @Override
1830    public Object getSystemService(String name) {
1831        ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
1832        return fetcher == null ? null : fetcher.getService(this);
1833    }
1834
1835    private WallpaperManager getWallpaperManager() {
1836        return (WallpaperManager) WALLPAPER_FETCHER.getService(this);
1837    }
1838
1839    /* package */ static DropBoxManager createDropBoxManager() {
1840        IBinder b = ServiceManager.getService(DROPBOX_SERVICE);
1841        IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b);
1842        if (service == null) {
1843            // Don't return a DropBoxManager that will NPE upon use.
1844            // This also avoids caching a broken DropBoxManager in
1845            // getDropBoxManager during early boot, before the
1846            // DROPBOX_SERVICE is registered.
1847            return null;
1848        }
1849        return new DropBoxManager(service);
1850    }
1851
1852    @Override
1853    public int checkPermission(String permission, int pid, int uid) {
1854        if (permission == null) {
1855            throw new IllegalArgumentException("permission is null");
1856        }
1857
1858        try {
1859            return ActivityManagerNative.getDefault().checkPermission(
1860                    permission, pid, uid);
1861        } catch (RemoteException e) {
1862            return PackageManager.PERMISSION_DENIED;
1863        }
1864    }
1865
1866    /** @hide */
1867    @Override
1868    public int checkPermission(String permission, int pid, int uid, IBinder callerToken) {
1869        if (permission == null) {
1870            throw new IllegalArgumentException("permission is null");
1871        }
1872
1873        try {
1874            return ActivityManagerNative.getDefault().checkPermissionWithToken(
1875                    permission, pid, uid, callerToken);
1876        } catch (RemoteException e) {
1877            return PackageManager.PERMISSION_DENIED;
1878        }
1879    }
1880
1881    @Override
1882    public int checkCallingPermission(String permission) {
1883        if (permission == null) {
1884            throw new IllegalArgumentException("permission is null");
1885        }
1886
1887        int pid = Binder.getCallingPid();
1888        if (pid != Process.myPid()) {
1889            return checkPermission(permission, pid, Binder.getCallingUid());
1890        }
1891        return PackageManager.PERMISSION_DENIED;
1892    }
1893
1894    @Override
1895    public int checkCallingOrSelfPermission(String permission) {
1896        if (permission == null) {
1897            throw new IllegalArgumentException("permission is null");
1898        }
1899
1900        return checkPermission(permission, Binder.getCallingPid(),
1901                Binder.getCallingUid());
1902    }
1903
1904    private void enforce(
1905            String permission, int resultOfCheck,
1906            boolean selfToo, int uid, String message) {
1907        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
1908            throw new SecurityException(
1909                    (message != null ? (message + ": ") : "") +
1910                    (selfToo
1911                     ? "Neither user " + uid + " nor current process has "
1912                     : "uid " + uid + " does not have ") +
1913                    permission +
1914                    ".");
1915        }
1916    }
1917
1918    public void enforcePermission(
1919            String permission, int pid, int uid, String message) {
1920        enforce(permission,
1921                checkPermission(permission, pid, uid),
1922                false,
1923                uid,
1924                message);
1925    }
1926
1927    public void enforceCallingPermission(String permission, String message) {
1928        enforce(permission,
1929                checkCallingPermission(permission),
1930                false,
1931                Binder.getCallingUid(),
1932                message);
1933    }
1934
1935    public void enforceCallingOrSelfPermission(
1936            String permission, String message) {
1937        enforce(permission,
1938                checkCallingOrSelfPermission(permission),
1939                true,
1940                Binder.getCallingUid(),
1941                message);
1942    }
1943
1944    @Override
1945    public void grantUriPermission(String toPackage, Uri uri, int modeFlags) {
1946         try {
1947            ActivityManagerNative.getDefault().grantUriPermission(
1948                    mMainThread.getApplicationThread(), toPackage,
1949                    ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
1950        } catch (RemoteException e) {
1951        }
1952    }
1953
1954    @Override
1955    public void revokeUriPermission(Uri uri, int modeFlags) {
1956         try {
1957            ActivityManagerNative.getDefault().revokeUriPermission(
1958                    mMainThread.getApplicationThread(),
1959                    ContentProvider.getUriWithoutUserId(uri), modeFlags, resolveUserId(uri));
1960        } catch (RemoteException e) {
1961        }
1962    }
1963
1964    @Override
1965    public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
1966        try {
1967            return ActivityManagerNative.getDefault().checkUriPermission(
1968                    ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
1969                    resolveUserId(uri), null);
1970        } catch (RemoteException e) {
1971            return PackageManager.PERMISSION_DENIED;
1972        }
1973    }
1974
1975    /** @hide */
1976    @Override
1977    public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags, IBinder callerToken) {
1978        try {
1979            return ActivityManagerNative.getDefault().checkUriPermission(
1980                    ContentProvider.getUriWithoutUserId(uri), pid, uid, modeFlags,
1981                    resolveUserId(uri), callerToken);
1982        } catch (RemoteException e) {
1983            return PackageManager.PERMISSION_DENIED;
1984        }
1985    }
1986
1987    private int resolveUserId(Uri uri) {
1988        return ContentProvider.getUserIdFromUri(uri, getUserId());
1989    }
1990
1991    @Override
1992    public int checkCallingUriPermission(Uri uri, int modeFlags) {
1993        int pid = Binder.getCallingPid();
1994        if (pid != Process.myPid()) {
1995            return checkUriPermission(uri, pid,
1996                    Binder.getCallingUid(), modeFlags);
1997        }
1998        return PackageManager.PERMISSION_DENIED;
1999    }
2000
2001    @Override
2002    public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) {
2003        return checkUriPermission(uri, Binder.getCallingPid(),
2004                Binder.getCallingUid(), modeFlags);
2005    }
2006
2007    @Override
2008    public int checkUriPermission(Uri uri, String readPermission,
2009            String writePermission, int pid, int uid, int modeFlags) {
2010        if (DEBUG) {
2011            Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission="
2012                    + readPermission + " writePermission=" + writePermission
2013                    + " pid=" + pid + " uid=" + uid + " mode" + modeFlags);
2014        }
2015        if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2016            if (readPermission == null
2017                    || checkPermission(readPermission, pid, uid)
2018                    == PackageManager.PERMISSION_GRANTED) {
2019                return PackageManager.PERMISSION_GRANTED;
2020            }
2021        }
2022        if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2023            if (writePermission == null
2024                    || checkPermission(writePermission, pid, uid)
2025                    == PackageManager.PERMISSION_GRANTED) {
2026                return PackageManager.PERMISSION_GRANTED;
2027            }
2028        }
2029        return uri != null ? checkUriPermission(uri, pid, uid, modeFlags)
2030                : PackageManager.PERMISSION_DENIED;
2031    }
2032
2033    private String uriModeFlagToString(int uriModeFlags) {
2034        StringBuilder builder = new StringBuilder();
2035        if ((uriModeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
2036            builder.append("read and ");
2037        }
2038        if ((uriModeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
2039            builder.append("write and ");
2040        }
2041        if ((uriModeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0) {
2042            builder.append("persistable and ");
2043        }
2044        if ((uriModeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) {
2045            builder.append("prefix and ");
2046        }
2047
2048        if (builder.length() > 5) {
2049            builder.setLength(builder.length() - 5);
2050            return builder.toString();
2051        } else {
2052            throw new IllegalArgumentException("Unknown permission mode flags: " + uriModeFlags);
2053        }
2054    }
2055
2056    private void enforceForUri(
2057            int modeFlags, int resultOfCheck, boolean selfToo,
2058            int uid, Uri uri, String message) {
2059        if (resultOfCheck != PackageManager.PERMISSION_GRANTED) {
2060            throw new SecurityException(
2061                    (message != null ? (message + ": ") : "") +
2062                    (selfToo
2063                     ? "Neither user " + uid + " nor current process has "
2064                     : "User " + uid + " does not have ") +
2065                    uriModeFlagToString(modeFlags) +
2066                    " permission on " +
2067                    uri +
2068                    ".");
2069        }
2070    }
2071
2072    public void enforceUriPermission(
2073            Uri uri, int pid, int uid, int modeFlags, String message) {
2074        enforceForUri(
2075                modeFlags, checkUriPermission(uri, pid, uid, modeFlags),
2076                false, uid, uri, message);
2077    }
2078
2079    public void enforceCallingUriPermission(
2080            Uri uri, int modeFlags, String message) {
2081        enforceForUri(
2082                modeFlags, checkCallingUriPermission(uri, modeFlags),
2083                false,
2084                Binder.getCallingUid(), uri, message);
2085    }
2086
2087    public void enforceCallingOrSelfUriPermission(
2088            Uri uri, int modeFlags, String message) {
2089        enforceForUri(
2090                modeFlags,
2091                checkCallingOrSelfUriPermission(uri, modeFlags), true,
2092                Binder.getCallingUid(), uri, message);
2093    }
2094
2095    public void enforceUriPermission(
2096            Uri uri, String readPermission, String writePermission,
2097            int pid, int uid, int modeFlags, String message) {
2098        enforceForUri(modeFlags,
2099                      checkUriPermission(
2100                              uri, readPermission, writePermission, pid, uid,
2101                              modeFlags),
2102                      false,
2103                      uid,
2104                      uri,
2105                      message);
2106    }
2107
2108    /**
2109     * Logs a warning if the system process directly called a method such as
2110     * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
2111     * The "AsUser" variants allow us to properly enforce the user's restrictions.
2112     */
2113    private void warnIfCallingFromSystemProcess() {
2114        if (Process.myUid() == Process.SYSTEM_UID) {
2115            Slog.w(TAG, "Calling a method in the system process without a qualified user: "
2116                    + Debug.getCallers(5));
2117        }
2118    }
2119
2120    @Override
2121    public Context createApplicationContext(ApplicationInfo application, int flags)
2122            throws NameNotFoundException {
2123        LoadedApk pi = mMainThread.getPackageInfo(application, mResources.getCompatibilityInfo(),
2124                flags | CONTEXT_REGISTER_PACKAGE);
2125        if (pi != null) {
2126            final boolean restricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
2127            ContextImpl c = new ContextImpl(this, mMainThread, pi, mActivityToken,
2128                    new UserHandle(UserHandle.getUserId(application.uid)), restricted,
2129                    mDisplay, mOverrideConfiguration);
2130            if (c.mResources != null) {
2131                return c;
2132            }
2133        }
2134
2135        throw new PackageManager.NameNotFoundException(
2136                "Application package " + application.packageName + " not found");
2137    }
2138
2139    @Override
2140    public Context createPackageContext(String packageName, int flags)
2141            throws NameNotFoundException {
2142        return createPackageContextAsUser(packageName, flags,
2143                mUser != null ? mUser : Process.myUserHandle());
2144    }
2145
2146    @Override
2147    public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
2148            throws NameNotFoundException {
2149        final boolean restricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED;
2150        if (packageName.equals("system") || packageName.equals("android")) {
2151            return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken,
2152                    user, restricted, mDisplay, mOverrideConfiguration);
2153        }
2154
2155        LoadedApk pi = mMainThread.getPackageInfo(packageName, mResources.getCompatibilityInfo(),
2156                flags | CONTEXT_REGISTER_PACKAGE, user.getIdentifier());
2157        if (pi != null) {
2158            ContextImpl c = new ContextImpl(this, mMainThread, pi, mActivityToken,
2159                    user, restricted, mDisplay, mOverrideConfiguration);
2160            if (c.mResources != null) {
2161                return c;
2162            }
2163        }
2164
2165        // Should be a better exception.
2166        throw new PackageManager.NameNotFoundException(
2167                "Application package " + packageName + " not found");
2168    }
2169
2170    @Override
2171    public Context createConfigurationContext(Configuration overrideConfiguration) {
2172        if (overrideConfiguration == null) {
2173            throw new IllegalArgumentException("overrideConfiguration must not be null");
2174        }
2175
2176        return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken,
2177                mUser, mRestricted, mDisplay, overrideConfiguration);
2178    }
2179
2180    @Override
2181    public Context createDisplayContext(Display display) {
2182        if (display == null) {
2183            throw new IllegalArgumentException("display must not be null");
2184        }
2185
2186        return new ContextImpl(this, mMainThread, mPackageInfo, mActivityToken,
2187                mUser, mRestricted, display, mOverrideConfiguration);
2188    }
2189
2190    private int getDisplayId() {
2191        return mDisplay != null ? mDisplay.getDisplayId() : Display.DEFAULT_DISPLAY;
2192    }
2193
2194    @Override
2195    public boolean isRestricted() {
2196        return mRestricted;
2197    }
2198
2199    @Override
2200    public DisplayAdjustments getDisplayAdjustments(int displayId) {
2201        return mDisplayAdjustments;
2202    }
2203
2204    private File getDataDirFile() {
2205        if (mPackageInfo != null) {
2206            return mPackageInfo.getDataDirFile();
2207        }
2208        throw new RuntimeException("Not supported in system context");
2209    }
2210
2211    @Override
2212    public File getDir(String name, int mode) {
2213        name = "app_" + name;
2214        File file = makeFilename(getDataDirFile(), name);
2215        if (!file.exists()) {
2216            file.mkdir();
2217            setFilePermissionsFromMode(file.getPath(), mode,
2218                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH);
2219        }
2220        return file;
2221    }
2222
2223    /** {@hide} */
2224    public int getUserId() {
2225        return mUser.getIdentifier();
2226    }
2227
2228    static ContextImpl createSystemContext(ActivityThread mainThread) {
2229        LoadedApk packageInfo = new LoadedApk(mainThread);
2230        ContextImpl context = new ContextImpl(null, mainThread,
2231                packageInfo, null, null, false, null, null);
2232        context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
2233                context.mResourcesManager.getDisplayMetricsLocked(Display.DEFAULT_DISPLAY));
2234        return context;
2235    }
2236
2237    static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
2238        if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
2239        return new ContextImpl(null, mainThread,
2240                packageInfo, null, null, false, null, null);
2241    }
2242
2243    static ContextImpl createActivityContext(ActivityThread mainThread,
2244            LoadedApk packageInfo, IBinder activityToken) {
2245        if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
2246        if (activityToken == null) throw new IllegalArgumentException("activityInfo");
2247        return new ContextImpl(null, mainThread,
2248                packageInfo, activityToken, null, false, null, null);
2249    }
2250
2251    private ContextImpl(ContextImpl container, ActivityThread mainThread,
2252            LoadedApk packageInfo, IBinder activityToken, UserHandle user, boolean restricted,
2253            Display display, Configuration overrideConfiguration) {
2254        mOuterContext = this;
2255
2256        mMainThread = mainThread;
2257        mActivityToken = activityToken;
2258        mRestricted = restricted;
2259
2260        if (user == null) {
2261            user = Process.myUserHandle();
2262        }
2263        mUser = user;
2264
2265        mPackageInfo = packageInfo;
2266        mResourcesManager = ResourcesManager.getInstance();
2267        mDisplay = display;
2268        mOverrideConfiguration = overrideConfiguration;
2269
2270        final int displayId = getDisplayId();
2271        CompatibilityInfo compatInfo = null;
2272        if (container != null) {
2273            compatInfo = container.getDisplayAdjustments(displayId).getCompatibilityInfo();
2274        }
2275        if (compatInfo == null && displayId == Display.DEFAULT_DISPLAY) {
2276            compatInfo = packageInfo.getCompatibilityInfo();
2277        }
2278        mDisplayAdjustments.setCompatibilityInfo(compatInfo);
2279        mDisplayAdjustments.setActivityToken(activityToken);
2280
2281        Resources resources = packageInfo.getResources(mainThread);
2282        if (resources != null) {
2283            if (activityToken != null
2284                    || displayId != Display.DEFAULT_DISPLAY
2285                    || overrideConfiguration != null
2286                    || (compatInfo != null && compatInfo.applicationScale
2287                            != resources.getCompatibilityInfo().applicationScale)) {
2288                resources = mResourcesManager.getTopLevelResources(packageInfo.getResDir(),
2289                        packageInfo.getSplitResDirs(), packageInfo.getOverlayDirs(),
2290                        packageInfo.getApplicationInfo().sharedLibraryFiles, displayId,
2291                        overrideConfiguration, compatInfo, activityToken);
2292            }
2293        }
2294        mResources = resources;
2295
2296        if (container != null) {
2297            mBasePackageName = container.mBasePackageName;
2298            mOpPackageName = container.mOpPackageName;
2299        } else {
2300            mBasePackageName = packageInfo.mPackageName;
2301            ApplicationInfo ainfo = packageInfo.getApplicationInfo();
2302            if (ainfo.uid == Process.SYSTEM_UID && ainfo.uid != Process.myUid()) {
2303                // Special case: system components allow themselves to be loaded in to other
2304                // processes.  For purposes of app ops, we must then consider the context as
2305                // belonging to the package of this process, not the system itself, otherwise
2306                // the package+uid verifications in app ops will fail.
2307                mOpPackageName = ActivityThread.currentPackageName();
2308            } else {
2309                mOpPackageName = mBasePackageName;
2310            }
2311        }
2312
2313        mContentResolver = new ApplicationContentResolver(this, mainThread, user);
2314    }
2315
2316    void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
2317        mPackageInfo.installSystemApplicationInfo(info, classLoader);
2318    }
2319
2320    final void scheduleFinalCleanup(String who, String what) {
2321        mMainThread.scheduleContextCleanup(this, who, what);
2322    }
2323
2324    final void performFinalCleanup(String who, String what) {
2325        //Log.i(TAG, "Cleanup up context: " + this);
2326        mPackageInfo.removeContextRegistrations(getOuterContext(), who, what);
2327    }
2328
2329    final Context getReceiverRestrictedContext() {
2330        if (mReceiverRestrictedContext != null) {
2331            return mReceiverRestrictedContext;
2332        }
2333        return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext());
2334    }
2335
2336    final void setOuterContext(Context context) {
2337        mOuterContext = context;
2338    }
2339
2340    final Context getOuterContext() {
2341        return mOuterContext;
2342    }
2343
2344    final IBinder getActivityToken() {
2345        return mActivityToken;
2346    }
2347
2348    static void setFilePermissionsFromMode(String name, int mode,
2349            int extraPermissions) {
2350        int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR
2351            |FileUtils.S_IRGRP|FileUtils.S_IWGRP
2352            |extraPermissions;
2353        if ((mode&MODE_WORLD_READABLE) != 0) {
2354            perms |= FileUtils.S_IROTH;
2355        }
2356        if ((mode&MODE_WORLD_WRITEABLE) != 0) {
2357            perms |= FileUtils.S_IWOTH;
2358        }
2359        if (DEBUG) {
2360            Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode)
2361                  + ", perms=0x" + Integer.toHexString(perms));
2362        }
2363        FileUtils.setPermissions(name, perms, -1, -1);
2364    }
2365
2366    private File validateFilePath(String name, boolean createDirectory) {
2367        File dir;
2368        File f;
2369
2370        if (name.charAt(0) == File.separatorChar) {
2371            String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar));
2372            dir = new File(dirPath);
2373            name = name.substring(name.lastIndexOf(File.separatorChar));
2374            f = new File(dir, name);
2375        } else {
2376            dir = getDatabasesDir();
2377            f = makeFilename(dir, name);
2378        }
2379
2380        if (createDirectory && !dir.isDirectory() && dir.mkdir()) {
2381            FileUtils.setPermissions(dir.getPath(),
2382                FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
2383                -1, -1);
2384        }
2385
2386        return f;
2387    }
2388
2389    private File makeFilename(File base, String name) {
2390        if (name.indexOf(File.separatorChar) < 0) {
2391            return new File(base, name);
2392        }
2393        throw new IllegalArgumentException(
2394                "File " + name + " contains a path separator");
2395    }
2396
2397    /**
2398     * Ensure that given directories exist, trying to create them if missing. If
2399     * unable to create, they are filtered by replacing with {@code null}.
2400     */
2401    private File[] ensureDirsExistOrFilter(File[] dirs) {
2402        File[] result = new File[dirs.length];
2403        for (int i = 0; i < dirs.length; i++) {
2404            File dir = dirs[i];
2405            if (!dir.exists()) {
2406                if (!dir.mkdirs()) {
2407                    // recheck existence in case of cross-process race
2408                    if (!dir.exists()) {
2409                        // Failing to mkdir() may be okay, since we might not have
2410                        // enough permissions; ask vold to create on our behalf.
2411                        final IMountService mount = IMountService.Stub.asInterface(
2412                                ServiceManager.getService("mount"));
2413                        int res = -1;
2414                        try {
2415                            res = mount.mkdirs(getPackageName(), dir.getAbsolutePath());
2416                        } catch (RemoteException e) {
2417                        }
2418                        if (res != 0) {
2419                            Log.w(TAG, "Failed to ensure directory: " + dir);
2420                            dir = null;
2421                        }
2422                    }
2423                }
2424            }
2425            result[i] = dir;
2426        }
2427        return result;
2428    }
2429
2430    // ----------------------------------------------------------------------
2431    // ----------------------------------------------------------------------
2432    // ----------------------------------------------------------------------
2433
2434    private static final class ApplicationContentResolver extends ContentResolver {
2435        private final ActivityThread mMainThread;
2436        private final UserHandle mUser;
2437
2438        public ApplicationContentResolver(
2439                Context context, ActivityThread mainThread, UserHandle user) {
2440            super(context);
2441            mMainThread = Preconditions.checkNotNull(mainThread);
2442            mUser = Preconditions.checkNotNull(user);
2443        }
2444
2445        @Override
2446        protected IContentProvider acquireProvider(Context context, String auth) {
2447            return mMainThread.acquireProvider(context,
2448                    ContentProvider.getAuthorityWithoutUserId(auth),
2449                    resolveUserIdFromAuthority(auth), true);
2450        }
2451
2452        @Override
2453        protected IContentProvider acquireExistingProvider(Context context, String auth) {
2454            return mMainThread.acquireExistingProvider(context,
2455                    ContentProvider.getAuthorityWithoutUserId(auth),
2456                    resolveUserIdFromAuthority(auth), true);
2457        }
2458
2459        @Override
2460        public boolean releaseProvider(IContentProvider provider) {
2461            return mMainThread.releaseProvider(provider, true);
2462        }
2463
2464        @Override
2465        protected IContentProvider acquireUnstableProvider(Context c, String auth) {
2466            return mMainThread.acquireProvider(c,
2467                    ContentProvider.getAuthorityWithoutUserId(auth),
2468                    resolveUserIdFromAuthority(auth), false);
2469        }
2470
2471        @Override
2472        public boolean releaseUnstableProvider(IContentProvider icp) {
2473            return mMainThread.releaseProvider(icp, false);
2474        }
2475
2476        @Override
2477        public void unstableProviderDied(IContentProvider icp) {
2478            mMainThread.handleUnstableProviderDied(icp.asBinder(), true);
2479        }
2480
2481        @Override
2482        public void appNotRespondingViaProvider(IContentProvider icp) {
2483            mMainThread.appNotRespondingViaProvider(icp.asBinder());
2484        }
2485
2486        /** @hide */
2487        protected int resolveUserIdFromAuthority(String auth) {
2488            return ContentProvider.getUserIdFromAuthority(auth, mUser.getIdentifier());
2489        }
2490    }
2491}
2492