OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2009 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 <errno.h> |
| 6 #include <stdlib.h> |
| 7 #include <sys/ipc.h> |
| 8 #include <sys/shm.h> |
| 9 |
| 10 #include "base/logging.h" |
| 11 #include "chrome/common/transport_dib.h" |
| 12 |
| 13 // The shmat system call uses this as it's invalid return address |
| 14 static void *const kInvalidAddress = (void*) -1; |
| 15 |
| 16 TransportDIB::TransportDIB() |
| 17 : key_(-1), |
| 18 address_(kInvalidAddress), |
| 19 size_(0) { |
| 20 } |
| 21 |
| 22 TransportDIB::~TransportDIB() { |
| 23 if (address_ != kInvalidAddress) { |
| 24 shmdt(address_); |
| 25 address_ = kInvalidAddress; |
| 26 } |
| 27 } |
| 28 |
| 29 // static |
| 30 TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { |
| 31 // We use a mode of 0666 since the X server won't attach to memory which is |
| 32 // 0600 since it can't know if it (as a root process) is being asked to map |
| 33 // someone else's private shared memory region. |
| 34 const int shmkey = shmget(IPC_PRIVATE, size, 0666); |
| 35 if (shmkey == -1) { |
| 36 DLOG(ERROR) << "Failed to create SysV shared memory region" |
| 37 << " errno:" << errno; |
| 38 return false; |
| 39 } |
| 40 |
| 41 void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); |
| 42 // Here we mark the shared memory for deletion. Since we attached it in the |
| 43 // line above, it doesn't actually get deleted but, if we crash, this means |
| 44 // that the kernel will automatically clean it up for us. |
| 45 shmctl(shmkey, IPC_RMID, 0); |
| 46 if (address == kInvalidAddress) |
| 47 return false; |
| 48 |
| 49 TransportDIB* dib = new TransportDIB; |
| 50 |
| 51 dib->key_ = shmkey; |
| 52 dib->address_ = address; |
| 53 dib->size_ = size; |
| 54 return dib; |
| 55 } |
| 56 |
| 57 TransportDIB* TransportDIB::Map(Handle shmkey) { |
| 58 struct shmid_ds shmst; |
| 59 if (shmctl(shmkey, IPC_STAT, &shmst) == -1) |
| 60 return NULL; |
| 61 |
| 62 void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); |
| 63 if (address == kInvalidAddress) |
| 64 return NULL; |
| 65 |
| 66 TransportDIB* dib = new TransportDIB; |
| 67 |
| 68 dib->address_ = address; |
| 69 dib->size_ = shmst.shm_segsz; |
| 70 dib->key_ = shmkey; |
| 71 return dib; |
| 72 } |
| 73 |
| 74 void* TransportDIB::memory() const { |
| 75 DCHECK_NE(address_, kInvalidAddress); |
| 76 return address_; |
| 77 } |
| 78 |
| 79 TransportDIB::Id TransportDIB::id() const { |
| 80 return key_; |
| 81 } |
| 82 |
| 83 TransportDIB::Handle TransportDIB::handle() const { |
| 84 return key_; |
| 85 } |
OLD | NEW |