1// Copyright (c) 2006-2008 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 "sandbox/win/src/shared_handles.h"
6
7namespace sandbox {
8
9// Note once again the the assumption here is that the shared memory is
10// initialized with zeros in the process that calls SetHandle and that
11// the process that calls GetHandle 'sees' this memory.
12
13SharedHandles::SharedHandles() {
14  shared_.items = NULL;
15  shared_.max_items = 0;
16}
17
18bool SharedHandles::Init(void* raw_mem, size_t size_bytes) {
19  if (size_bytes < sizeof(shared_.items[0])) {
20    // The shared memory is too small!
21    return false;
22  }
23  shared_.items = static_cast<SharedItem*>(raw_mem);
24  shared_.max_items = size_bytes / sizeof(shared_.items[0]);
25  return true;
26}
27
28// Note that an empty slot is marked with a tag == 0 that is why is
29// not a valid imput tag
30bool SharedHandles::SetHandle(uint32 tag, HANDLE handle) {
31  if (0 == tag) {
32    // Invalid tag
33    return false;
34  }
35  // Find empty slot and put the tag and the handle there
36  SharedItem* empty_slot = FindByTag(0);
37  if (NULL == empty_slot) {
38    return false;
39  }
40  empty_slot->tag = tag;
41  empty_slot->item = handle;
42  return true;
43}
44
45bool SharedHandles::GetHandle(uint32 tag, HANDLE* handle) {
46  if (0 == tag) {
47    // Invalid tag
48    return false;
49  }
50  SharedItem* found = FindByTag(tag);
51  if (NULL == found) {
52    return false;
53  }
54  *handle = found->item;
55  return true;
56}
57
58SharedHandles::SharedItem* SharedHandles::FindByTag(uint32 tag) {
59  for (size_t ix = 0; ix != shared_.max_items; ++ix) {
60    if (tag == shared_.items[ix].tag) {
61      return &shared_.items[ix];
62    }
63  }
64  return NULL;
65}
66
67}  // namespace sandbox
68