OSDN Git Service

Fix issue #27252896: Security Vulnerability -- weak binder am: 12bafe2 am: b4f0f33
[android-x86/frameworks-native.git] / services / surfaceflinger / SurfaceFlinger.h
1 /*
2  * Copyright (C) 2007 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
17 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
19
20 #include <stdint.h>
21 #include <sys/types.h>
22
23 #include <EGL/egl.h>
24
25 /*
26  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
27  */
28
29 #include <cutils/compiler.h>
30
31 #include <utils/Atomic.h>
32 #include <utils/Errors.h>
33 #include <utils/KeyedVector.h>
34 #include <utils/RefBase.h>
35 #include <utils/SortedVector.h>
36 #include <utils/threads.h>
37
38 #include <binder/IMemory.h>
39
40 #include <ui/PixelFormat.h>
41 #include <ui/mat4.h>
42
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
45
46 #include <hardware/hwcomposer_defs.h>
47
48 #include <private/gui/LayerState.h>
49
50 #include "Barrier.h"
51 #include "DisplayDevice.h"
52 #include "DispSync.h"
53 #include "FrameTracker.h"
54 #include "MessageQueue.h"
55
56 #include "DisplayHardware/HWComposer.h"
57 #include "Effects/Daltonizer.h"
58
59 namespace android {
60
61 // ---------------------------------------------------------------------------
62
63 class Client;
64 class DisplayEventConnection;
65 class EventThread;
66 class IGraphicBufferAlloc;
67 class Layer;
68 class LayerDim;
69 class Surface;
70 class RenderEngine;
71 class EventControlThread;
72
73 // ---------------------------------------------------------------------------
74
75 enum {
76     eTransactionNeeded        = 0x01,
77     eTraversalNeeded          = 0x02,
78     eDisplayTransactionNeeded = 0x04,
79     eTransactionMask          = 0x07
80 };
81
82 class SurfaceFlinger : public BnSurfaceComposer,
83                        private IBinder::DeathRecipient,
84                        private HWComposer::EventHandler
85 {
86 public:
87     static char const* getServiceName() ANDROID_API {
88         return "SurfaceFlinger";
89     }
90
91     SurfaceFlinger() ANDROID_API;
92
93     // must be called before clients can connect
94     void init() ANDROID_API;
95
96     // starts SurfaceFlinger main loop in the current thread
97     void run() ANDROID_API;
98
99     enum {
100         EVENT_VSYNC = HWC_EVENT_VSYNC
101     };
102
103     // post an asynchronous message to the main thread
104     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
105
106     // post a synchronous message to the main thread
107     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
108
109     // force full composition on all displays
110     void repaintEverything();
111
112     // returns the default Display
113     sp<const DisplayDevice> getDefaultDisplayDevice() const {
114         return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
115     }
116
117     // utility function to delete a texture on the main thread
118     void deleteTextureAsync(uint32_t texture);
119
120     // enable/disable h/w composer event
121     // TODO: this should be made accessible only to EventThread
122     void eventControl(int disp, int event, int enabled);
123
124     // called on the main thread by MessageQueue when an internal message
125     // is received
126     // TODO: this should be made accessible only to MessageQueue
127     void onMessageReceived(int32_t what);
128
129     // for debugging only
130     // TODO: this should be made accessible only to HWComposer
131     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
132
133     RenderEngine& getRenderEngine() const {
134         return *mRenderEngine;
135     }
136
137 private:
138     friend class Client;
139     friend class DisplayEventConnection;
140     friend class Layer;
141     friend class MonitoredProducer;
142
143     // This value is specified in number of frames.  Log frame stats at most
144     // every half hour.
145     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
146
147     static const size_t MAX_LAYERS = 4096;
148
149     // We're reference counted, never destroy SurfaceFlinger directly
150     virtual ~SurfaceFlinger();
151
152     /* ------------------------------------------------------------------------
153      * Internal data structures
154      */
155
156     class LayerVector : public SortedVector< sp<Layer> > {
157     public:
158         LayerVector();
159         LayerVector(const LayerVector& rhs);
160         virtual int do_compare(const void* lhs, const void* rhs) const;
161     };
162
163     struct DisplayDeviceState {
164         DisplayDeviceState();
165         DisplayDeviceState(DisplayDevice::DisplayType type);
166         bool isValid() const { return type >= 0; }
167         bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
168         bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
169         DisplayDevice::DisplayType type;
170         sp<IGraphicBufferProducer> surface;
171         uint32_t layerStack;
172         Rect viewport;
173         Rect frame;
174         uint8_t orientation;
175         uint32_t width, height;
176         String8 displayName;
177         bool isSecure;
178     };
179
180     struct State {
181         LayerVector layersSortedByZ;
182         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
183     };
184
185     /* ------------------------------------------------------------------------
186      * IBinder interface
187      */
188     virtual status_t onTransact(uint32_t code, const Parcel& data,
189         Parcel* reply, uint32_t flags);
190     virtual status_t dump(int fd, const Vector<String16>& args);
191
192     /* ------------------------------------------------------------------------
193      * ISurfaceComposer interface
194      */
195     virtual sp<ISurfaceComposerClient> createConnection();
196     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
197     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
198     virtual void destroyDisplay(const sp<IBinder>& display);
199     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
200     virtual void setTransactionState(const Vector<ComposerState>& state,
201             const Vector<DisplayState>& displays, uint32_t flags);
202     virtual void bootFinished();
203     virtual bool authenticateSurfaceTexture(
204         const sp<IGraphicBufferProducer>& bufferProducer) const;
205     virtual sp<IDisplayEventConnection> createDisplayEventConnection();
206     virtual status_t captureScreen(const sp<IBinder>& display,
207             const sp<IGraphicBufferProducer>& producer,
208             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
209             uint32_t minLayerZ, uint32_t maxLayerZ,
210             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
211     virtual status_t getDisplayStats(const sp<IBinder>& display,
212             DisplayStatInfo* stats);
213     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
214             Vector<DisplayInfo>* configs);
215     virtual int getActiveConfig(const sp<IBinder>& display);
216     virtual void setPowerMode(const sp<IBinder>& display, int mode);
217     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
218     virtual status_t clearAnimationFrameStats();
219     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
220
221     /* ------------------------------------------------------------------------
222      * DeathRecipient interface
223      */
224     virtual void binderDied(const wp<IBinder>& who);
225
226     /* ------------------------------------------------------------------------
227      * RefBase interface
228      */
229     virtual void onFirstRef();
230
231     /* ------------------------------------------------------------------------
232      * HWComposer::EventHandler interface
233      */
234     virtual void onVSyncReceived(int type, nsecs_t timestamp);
235     virtual void onHotplugReceived(int disp, bool connected);
236
237     /* ------------------------------------------------------------------------
238      * Message handling
239      */
240     void waitForEvent();
241     void signalTransaction();
242     void signalLayerUpdate();
243     void signalRefresh();
244
245     // called on the main thread in response to initializeDisplays()
246     void onInitializeDisplays();
247     // called on the main thread in response to setActiveConfig()
248     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
249     // called on the main thread in response to setPowerMode()
250     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
251
252     // Returns whether the transaction actually modified any state
253     bool handleMessageTransaction();
254
255     // Returns whether a new buffer has been latched (see handlePageFlip())
256     bool handleMessageInvalidate();
257
258     void handleMessageRefresh();
259
260     void handleTransaction(uint32_t transactionFlags);
261     void handleTransactionLocked(uint32_t transactionFlags);
262
263     void updateCursorAsync();
264
265     /* handlePageFlip - latch a new buffer if available and compute the dirty
266      * region. Returns whether a new buffer has been latched, i.e., whether it
267      * is necessary to perform a refresh during this vsync.
268      */
269     bool handlePageFlip();
270
271     /* ------------------------------------------------------------------------
272      * Transactions
273      */
274     uint32_t getTransactionFlags(uint32_t flags);
275     uint32_t peekTransactionFlags(uint32_t flags);
276     uint32_t setTransactionFlags(uint32_t flags);
277     void commitTransaction();
278     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
279     uint32_t setDisplayStateLocked(const DisplayState& s);
280
281     /* ------------------------------------------------------------------------
282      * Layer management
283      */
284     status_t createLayer(const String8& name, const sp<Client>& client,
285             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
286             sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
287
288     status_t createNormalLayer(const sp<Client>& client, const String8& name,
289             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
290             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
291             sp<Layer>* outLayer);
292
293     status_t createDimLayer(const sp<Client>& client, const String8& name,
294             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
295             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
296
297     // called in response to the window-manager calling
298     // ISurfaceComposerClient::destroySurface()
299     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
300
301     // called when all clients have released all their references to
302     // this layer meaning it is entirely safe to destroy all
303     // resources associated to this layer.
304     status_t onLayerDestroyed(const wp<Layer>& layer);
305
306     // remove a layer from SurfaceFlinger immediately
307     status_t removeLayer(const sp<Layer>& layer);
308
309     // add a layer to SurfaceFlinger
310     status_t addClientLayer(const sp<Client>& client,
311             const sp<IBinder>& handle,
312             const sp<IGraphicBufferProducer>& gbc,
313             const sp<Layer>& lbc);
314
315     /* ------------------------------------------------------------------------
316      * Boot animation, on/off animations and screen capture
317      */
318
319     void startBootAnim();
320
321     void renderScreenImplLocked(
322             const sp<const DisplayDevice>& hw,
323             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
324             uint32_t minLayerZ, uint32_t maxLayerZ,
325             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
326
327     status_t captureScreenImplLocked(
328             const sp<const DisplayDevice>& hw,
329             const sp<IGraphicBufferProducer>& producer,
330             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
331             uint32_t minLayerZ, uint32_t maxLayerZ,
332             bool useIdentityTransform, Transform::orientation_flags rotation);
333
334     /* ------------------------------------------------------------------------
335      * EGL
336      */
337     size_t getMaxTextureSize() const;
338     size_t getMaxViewportDims() const;
339
340     /* ------------------------------------------------------------------------
341      * Display and layer stack management
342      */
343     // called when starting, or restarting after system_server death
344     void initializeDisplays();
345
346     // Create an IBinder for a builtin display and add it to current state
347     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
348
349     // NOTE: can only be called from the main thread or with mStateLock held
350     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
351         return mDisplays.valueFor(dpy);
352     }
353
354     // NOTE: can only be called from the main thread or with mStateLock held
355     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
356         return mDisplays.valueFor(dpy);
357     }
358
359     // mark a region of a layer stack dirty. this updates the dirty
360     // region of all screens presenting this layer stack.
361     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
362
363     // allocate a h/w composer display id
364     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
365
366     /* ------------------------------------------------------------------------
367      * H/W composer
368      */
369
370     HWComposer& getHwComposer() const { return *mHwc; }
371
372     /* ------------------------------------------------------------------------
373      * Compositing
374      */
375     void invalidateHwcGeometry();
376     static void computeVisibleRegions(
377             const LayerVector& currentLayers, uint32_t layerStack,
378             Region& dirtyRegion, Region& opaqueRegion);
379
380     void preComposition();
381     void postComposition();
382     void rebuildLayerStacks();
383     void setUpHWComposer();
384     void doComposition();
385     void doDebugFlashRegions();
386     void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
387
388     // compose surfaces for display hw. this fails if using GL and the surface
389     // has been destroyed and is no longer valid.
390     bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
391
392     void postFramebuffer();
393     void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
394
395     /* ------------------------------------------------------------------------
396      * Display management
397      */
398
399     /* ------------------------------------------------------------------------
400      * VSync
401      */
402      void enableHardwareVsync();
403      void disableHardwareVsync(bool makeUnavailable);
404      void resyncToHardwareVsync(bool makeAvailable);
405
406     /* ------------------------------------------------------------------------
407      * Debugging & dumpsys
408      */
409     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
410     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
411     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
412     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
413     bool startDdmConnection();
414     static void appendSfConfigString(String8& result);
415     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
416             const sp<const DisplayDevice>& hw,
417             uint32_t minLayerZ, uint32_t maxLayerZ);
418
419     void logFrameStats();
420
421     void dumpStaticScreenStats(String8& result) const;
422
423     /* ------------------------------------------------------------------------
424      * Attributes
425      */
426
427     // access must be protected by mStateLock
428     mutable Mutex mStateLock;
429     State mCurrentState;
430     volatile int32_t mTransactionFlags;
431     Condition mTransactionCV;
432     bool mTransactionPending;
433     bool mAnimTransactionPending;
434     Vector< sp<Layer> > mLayersPendingRemoval;
435     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
436
437     // protected by mStateLock (but we could use another lock)
438     bool mLayersRemoved;
439
440     // access must be protected by mInvalidateLock
441     volatile int32_t mRepaintEverything;
442
443     // constant members (no synchronization needed for access)
444     HWComposer* mHwc;
445     RenderEngine* mRenderEngine;
446     nsecs_t mBootTime;
447     bool mGpuToCpuSupported;
448     sp<EventThread> mEventThread;
449     sp<EventThread> mSFEventThread;
450     sp<EventControlThread> mEventControlThread;
451     EGLContext mEGLContext;
452     EGLDisplay mEGLDisplay;
453     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
454
455     // Can only accessed from the main thread, these members
456     // don't need synchronization
457     State mDrawingState;
458     bool mVisibleRegionsDirty;
459     bool mHwWorkListDirty;
460     bool mAnimCompositionPending;
461
462     // this may only be written from the main thread with mStateLock held
463     // it may be read from other threads with mStateLock held
464     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
465
466     // don't use a lock for these, we don't care
467     int mDebugRegion;
468     int mDebugDDMS;
469     int mDebugDisableHWC;
470     int mDebugDisableTransformHint;
471     volatile nsecs_t mDebugInSwapBuffers;
472     nsecs_t mLastSwapBufferTime;
473     volatile nsecs_t mDebugInTransaction;
474     nsecs_t mLastTransactionTime;
475     bool mBootFinished;
476     bool mForceFullDamage;
477
478     // these are thread safe
479     mutable MessageQueue mEventQueue;
480     FrameTracker mAnimFrameTracker;
481     DispSync mPrimaryDispSync;
482
483     // protected by mDestroyedLayerLock;
484     mutable Mutex mDestroyedLayerLock;
485     Vector<Layer const *> mDestroyedLayers;
486
487     // protected by mHWVsyncLock
488     Mutex mHWVsyncLock;
489     bool mPrimaryHWVsyncEnabled;
490     bool mHWVsyncAvailable;
491
492     /* ------------------------------------------------------------------------
493      * Feature prototyping
494      */
495
496     Daltonizer mDaltonizer;
497     bool mDaltonize;
498
499     mat4 mColorMatrix;
500     bool mHasColorMatrix;
501
502     // Static screen stats
503     bool mHasPoweredOff;
504     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
505     nsecs_t mFrameBuckets[NUM_BUCKETS];
506     nsecs_t mTotalTime;
507     nsecs_t mLastSwapTime;
508 };
509
510 }; // namespace android
511
512 #endif // ANDROID_SURFACE_FLINGER_H