DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (b98968eb71d3)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/shared_memory.h"

#include "base/logging.h"
#include "base/win_util.h"
#include "base/string_util.h"
#include "mozilla/ipc/ProtocolUtils.h"
#include "mozilla/RandomNum.h"
#include "mozilla/WindowsVersion.h"
#include "nsDebug.h"
#include "nsString.h"

namespace {
// NtQuerySection is an internal (but believed to be stable) API and the
// structures it uses are defined in nt_internals.h.
// So we have to define them ourselves.
typedef enum _SECTION_INFORMATION_CLASS {
  SectionBasicInformation,
} SECTION_INFORMATION_CLASS;

typedef struct _SECTION_BASIC_INFORMATION {
  PVOID BaseAddress;
  ULONG Attributes;
  LARGE_INTEGER Size;
} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;

typedef ULONG(__stdcall* NtQuerySectionType)(
    HANDLE SectionHandle, SECTION_INFORMATION_CLASS SectionInformationClass,
    PVOID SectionInformation, ULONG SectionInformationLength,
    PULONG ResultLength);

// Checks if the section object is safe to map. At the moment this just means
// it's not an image section.
bool IsSectionSafeToMap(HANDLE handle) {
  static NtQuerySectionType nt_query_section_func =
      reinterpret_cast<NtQuerySectionType>(
          ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), "NtQuerySection"));
  DCHECK(nt_query_section_func);

  // The handle must have SECTION_QUERY access for this to succeed.
  SECTION_BASIC_INFORMATION basic_information = {};
  ULONG status =
      nt_query_section_func(handle, SectionBasicInformation, &basic_information,
                            sizeof(basic_information), nullptr);
  if (status) {
    return false;
  }

  return (basic_information.Attributes & SEC_IMAGE) != SEC_IMAGE;
}

}  // namespace

namespace base {

SharedMemory::SharedMemory()
    : external_section_(false),
      mapped_file_(NULL),
      memory_(NULL),
      read_only_(false),
      freezeable_(false),
      max_size_(0) {}

SharedMemory::SharedMemory(SharedMemory&& other) {
  if (this == &other) {
    return;
  }

  mapped_file_ = other.mapped_file_;
  memory_ = other.memory_;
  read_only_ = other.read_only_;
  max_size_ = other.max_size_;
  freezeable_ = other.freezeable_;
  external_section_ = other.external_section_;

  other.mapped_file_ = nullptr;
  other.memory_ = nullptr;
}

SharedMemory::~SharedMemory() {
  external_section_ = true;
  Close();
}

bool SharedMemory::SetHandle(SharedMemoryHandle handle, bool read_only) {
  DCHECK(mapped_file_ == NULL);

  external_section_ = true;
  freezeable_ = false;  // just in case
  mapped_file_ = handle;
  read_only_ = read_only;
  return true;
}

// static
bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
  return handle != NULL;
}

bool SharedMemory::IsValid() const { return mapped_file_ != NULL; }

// static
SharedMemoryHandle SharedMemory::NULLHandle() { return NULL; }

bool SharedMemory::CreateInternal(size_t size, bool freezeable) {
  DCHECK(mapped_file_ == NULL);
  read_only_ = false;

  SECURITY_ATTRIBUTES sa, *psa = nullptr;
  SECURITY_DESCRIPTOR sd;
  ACL dacl;
  nsAutoStringN<sizeof("MozSharedMem_") + 16 * 4> name;

  if (freezeable) {
    psa = &sa;
    sa.nLength = sizeof(sa);
    sa.lpSecurityDescriptor = &sd;
    sa.bInheritHandle = FALSE;

    if (NS_WARN_IF(!InitializeAcl(&dacl, sizeof(dacl), ACL_REVISION)) ||
        NS_WARN_IF(
            !InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) ||
        NS_WARN_IF(!SetSecurityDescriptorDacl(&sd, TRUE, &dacl, FALSE))) {
      return false;
    }

    if (!mozilla::IsWin8Point1OrLater()) {
      name.AssignLiteral("MozSharedMem_");
      for (size_t i = 0; i < 4; ++i) {
        mozilla::Maybe<uint64_t> randomNum = mozilla::RandomUint64();
        if (NS_WARN_IF(randomNum.isNothing())) {
          return false;
        }
        name.AppendPrintf("%016llx", *randomNum);
      }
    }
  }

  mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, psa, PAGE_READWRITE, 0,
                                   static_cast<DWORD>(size),
                                   name.IsEmpty() ? nullptr : name.get());
  if (!mapped_file_) return false;

  max_size_ = size;
  freezeable_ = freezeable;
  return true;
}

bool SharedMemory::Freeze() {
  DCHECK(!read_only_);
  CHECK(freezeable_);
  Unmap();

  if (!::DuplicateHandle(GetCurrentProcess(), mapped_file_, GetCurrentProcess(),
                         &mapped_file_, GENERIC_READ | FILE_MAP_READ, false,
                         DUPLICATE_CLOSE_SOURCE)) {
    return false;
  }

  read_only_ = true;
  freezeable_ = false;
  return true;
}

bool SharedMemory::Map(size_t bytes, void* fixed_address) {
  if (mapped_file_ == NULL) return false;

  if (external_section_ && !IsSectionSafeToMap(mapped_file_)) {
    return false;
  }

  memory_ = MapViewOfFileEx(
      mapped_file_, read_only_ ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE,
      0, 0, bytes, fixed_address);
  if (memory_ != NULL) {
    MOZ_ASSERT(!fixed_address || memory_ == fixed_address,
               "MapViewOfFileEx returned an expected address");
    return true;
  }
  return false;
}

bool SharedMemory::Unmap() {
  if (memory_ == NULL) return false;

  UnmapViewOfFile(memory_);
  memory_ = NULL;
  return true;
}

void* SharedMemory::FindFreeAddressSpace(size_t size) {
  void* memory = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
  if (memory) {
    VirtualFree(memory, 0, MEM_RELEASE);
  }
  return memory;
}

bool SharedMemory::ShareToProcessCommon(ProcessId processId,
                                        SharedMemoryHandle* new_handle,
                                        bool close_self) {
  freezeable_ = false;
  *new_handle = 0;
  DWORD access = FILE_MAP_READ | SECTION_QUERY;
  DWORD options = 0;
  HANDLE mapped_file = mapped_file_;
  HANDLE result;
  if (!read_only_) access |= FILE_MAP_WRITE;
  if (close_self) {
    // DUPLICATE_CLOSE_SOURCE causes DuplicateHandle to close mapped_file.
    options = DUPLICATE_CLOSE_SOURCE;
    mapped_file_ = NULL;
    Unmap();
  }

  if (processId == GetCurrentProcId() && close_self) {
    *new_handle = mapped_file;
    return true;
  }

  if (!mozilla::ipc::DuplicateHandle(mapped_file, processId, &result, access,
                                     options)) {
    return false;
  }

  *new_handle = result;
  return true;
}

void SharedMemory::Close(bool unmap_view) {
  if (unmap_view) {
    Unmap();
  }

  if (mapped_file_ != NULL) {
    CloseHandle(mapped_file_);
    mapped_file_ = NULL;
  }
}

mozilla::UniqueFileHandle SharedMemory::TakeHandle() {
  mozilla::UniqueFileHandle fh(mapped_file_);
  mapped_file_ = NULL;
  Unmap();
  return fh;
}

}  // namespace base