1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef GPU_COMMAND_BUFFER_SERVICE_SAFE_SHARED_MEMORY_POOL_H_ 6 #define GPU_COMMAND_BUFFER_SERVICE_SAFE_SHARED_MEMORY_POOL_H_ 7 8 #include <map> 9 10 #include "base/basictypes.h" 11 #include "base/memory/shared_memory.h" 12 #include "base/synchronization/lock.h" 13 #include "build/build_config.h" 14 15 namespace gpu { 16 class SafeSharedMemoryPool; 17 18 // These classes exist to help protect against deletion of shared 19 // memory that is being used on a worker thread. It's mainly a 20 // security measure to prevent use-after-free in the browser, due 21 // to a misbehaving client. That said, this should be removed 22 // in favor of higher-level reference counting of an appropriate 23 // opaque 'memory blob' data-structure. 24 25 class ScopedSafeSharedMemory { 26 public: 27 base::SharedMemory* shared_memory(); 28 ScopedSafeSharedMemory(SafeSharedMemoryPool* pool, 29 base::SharedMemory* memory, 30 size_t shm_size); 31 ~ScopedSafeSharedMemory(); 32 private: 33 base::SharedMemory* safe_shared_memory_; 34 base::SharedMemoryHandle original_handle_; 35 SafeSharedMemoryPool* pool_; 36 37 DISALLOW_COPY_AND_ASSIGN(ScopedSafeSharedMemory); 38 }; 39 40 class SafeSharedMemoryPool { 41 public: 42 SafeSharedMemoryPool(); 43 virtual ~SafeSharedMemoryPool(); 44 45 private: 46 friend class ScopedSafeSharedMemory; 47 48 // Acquires and release shared memory. The acquired shared memory 49 // is guaranteed to live until it is released. 50 base::SharedMemory* AcquireSafeSharedMemory(base::SharedMemory*, size_t size); 51 void ReleaseSafeSharedMemory(const base::SharedMemoryHandle&); 52 53 // Utility function to duplicate shared memory. 54 base::SharedMemory* DuplicateSharedMemory(base::SharedMemory*, size_t size); 55 56 // Track all SharedMemory's that we have already duplicated. 57 struct TrackedMemory { 58 base::SharedMemory* safe_shared_memory; 59 size_t shm_size; 60 int reference_count; 61 }; 62 63 typedef std::map<base::SharedMemoryHandle, TrackedMemory> MemoryMap; 64 MemoryMap memory_; 65 66 // Track usage to diagnose crashes. 67 int handles_acquired_; 68 int handles_consumed_; 69 size_t address_space_consumed_; 70 int max_handles_acquired_; 71 int max_handles_consumed_; 72 size_t max_address_space_consumed_; 73 74 base::Lock lock_; 75 76 DISALLOW_COPY_AND_ASSIGN(SafeSharedMemoryPool); 77 }; 78 79 } // namespace gfx 80 81 #endif // GPU_COMMAND_BUFFER_SERVICE_SAFE_SHARED_MEMORY_POOL_H_ 82 83