1 // Copyright 2014 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 #include "mojo/system/raw_shared_buffer.h" 6 7 #include "base/logging.h" 8 #include "mojo/embedder/platform_handle_utils.h" 9 10 namespace mojo { 11 namespace system { 12 13 // static 14 RawSharedBuffer* RawSharedBuffer::Create(size_t num_bytes) { 15 DCHECK_GT(num_bytes, 0u); 16 17 RawSharedBuffer* rv = new RawSharedBuffer(num_bytes); 18 if (!rv->Init()) { 19 // We can't just delete it directly, due to the "in destructor" (debug) 20 // check. 21 scoped_refptr<RawSharedBuffer> deleter(rv); 22 return NULL; 23 } 24 25 return rv; 26 } 27 28 RawSharedBuffer* RawSharedBuffer::CreateFromPlatformHandle( 29 size_t num_bytes, 30 embedder::ScopedPlatformHandle platform_handle) { 31 DCHECK_GT(num_bytes, 0u); 32 33 RawSharedBuffer* rv = new RawSharedBuffer(num_bytes); 34 if (!rv->InitFromPlatformHandle(platform_handle.Pass())) { 35 // We can't just delete it directly, due to the "in destructor" (debug) 36 // check. 37 scoped_refptr<RawSharedBuffer> deleter(rv); 38 return NULL; 39 } 40 41 return rv; 42 } 43 44 scoped_ptr<RawSharedBufferMapping> RawSharedBuffer::Map(size_t offset, 45 size_t length) { 46 if (!IsValidMap(offset, length)) 47 return scoped_ptr<RawSharedBufferMapping>(); 48 49 return MapNoCheck(offset, length); 50 } 51 52 bool RawSharedBuffer::IsValidMap(size_t offset, size_t length) { 53 if (offset > num_bytes_ || length == 0) 54 return false; 55 56 // Note: This is an overflow-safe check of |offset + length > num_bytes_| 57 // (that |num_bytes >= offset| is verified above). 58 if (length > num_bytes_ - offset) 59 return false; 60 61 return true; 62 } 63 64 scoped_ptr<RawSharedBufferMapping> RawSharedBuffer::MapNoCheck(size_t offset, 65 size_t length) { 66 DCHECK(IsValidMap(offset, length)); 67 return MapImpl(offset, length); 68 } 69 70 embedder::ScopedPlatformHandle RawSharedBuffer::DuplicatePlatformHandle() { 71 return embedder::DuplicatePlatformHandle(handle_.get()); 72 } 73 74 embedder::ScopedPlatformHandle RawSharedBuffer::PassPlatformHandle() { 75 DCHECK(HasOneRef()); 76 return handle_.Pass(); 77 } 78 79 RawSharedBuffer::RawSharedBuffer(size_t num_bytes) : num_bytes_(num_bytes) { 80 } 81 82 RawSharedBuffer::~RawSharedBuffer() { 83 } 84 85 } // namespace system 86 } // namespace mojo 87