1// Copyright 2012 the V8 project 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// Platform-specific code for OpenBSD and NetBSD goes here. For the
6// POSIX-compatible parts, the implementation is in platform-posix.cc.
7
8#include <pthread.h>
9#include <semaphore.h>
10#include <signal.h>
11#include <sys/time.h>
12#include <sys/resource.h>
13#include <sys/syscall.h>
14#include <sys/types.h>
15#include <stdlib.h>
16
17#include <sys/types.h>  // mmap & munmap
18#include <sys/mman.h>   // mmap & munmap
19#include <sys/stat.h>   // open
20#include <fcntl.h>      // open
21#include <unistd.h>     // sysconf
22#include <strings.h>    // index
23#include <errno.h>
24#include <stdarg.h>
25
26#undef MAP_TYPE
27
28#include "src/v8.h"
29
30#include "src/platform.h"
31
32
33namespace v8 {
34namespace internal {
35
36
37const char* OS::LocalTimezone(double time, TimezoneCache* cache) {
38  if (std::isnan(time)) return "";
39  time_t tv = static_cast<time_t>(std::floor(time/msPerSecond));
40  struct tm* t = localtime(&tv);
41  if (NULL == t) return "";
42  return t->tm_zone;
43}
44
45
46double OS::LocalTimeOffset(TimezoneCache* cache) {
47  time_t tv = time(NULL);
48  struct tm* t = localtime(&tv);
49  // tm_gmtoff includes any daylight savings offset, so subtract it.
50  return static_cast<double>(t->tm_gmtoff * msPerSecond -
51                             (t->tm_isdst > 0 ? 3600 * msPerSecond : 0));
52}
53
54
55void* OS::Allocate(const size_t requested,
56                   size_t* allocated,
57                   bool is_executable) {
58  const size_t msize = RoundUp(requested, AllocateAlignment());
59  int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
60  void* addr = OS::GetRandomMmapAddr();
61  void* mbase = mmap(addr, msize, prot, MAP_PRIVATE | MAP_ANON, -1, 0);
62  if (mbase == MAP_FAILED) return NULL;
63  *allocated = msize;
64  return mbase;
65}
66
67
68class PosixMemoryMappedFile : public OS::MemoryMappedFile {
69 public:
70  PosixMemoryMappedFile(FILE* file, void* memory, int size)
71    : file_(file), memory_(memory), size_(size) { }
72  virtual ~PosixMemoryMappedFile();
73  virtual void* memory() { return memory_; }
74  virtual int size() { return size_; }
75 private:
76  FILE* file_;
77  void* memory_;
78  int size_;
79};
80
81
82OS::MemoryMappedFile* OS::MemoryMappedFile::open(const char* name) {
83  FILE* file = fopen(name, "r+");
84  if (file == NULL) return NULL;
85
86  fseek(file, 0, SEEK_END);
87  int size = ftell(file);
88
89  void* memory =
90      mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
91  return new PosixMemoryMappedFile(file, memory, size);
92}
93
94
95OS::MemoryMappedFile* OS::MemoryMappedFile::create(const char* name, int size,
96    void* initial) {
97  FILE* file = fopen(name, "w+");
98  if (file == NULL) return NULL;
99  int result = fwrite(initial, size, 1, file);
100  if (result < 1) {
101    fclose(file);
102    return NULL;
103  }
104  void* memory =
105      mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fileno(file), 0);
106  return new PosixMemoryMappedFile(file, memory, size);
107}
108
109
110PosixMemoryMappedFile::~PosixMemoryMappedFile() {
111  if (memory_) OS::Free(memory_, size_);
112  fclose(file_);
113}
114
115
116std::vector<OS::SharedLibraryAddress> OS::GetSharedLibraryAddresses() {
117  std::vector<SharedLibraryAddress> result;
118  // This function assumes that the layout of the file is as follows:
119  // hex_start_addr-hex_end_addr rwxp <unused data> [binary_file_name]
120  // If we encounter an unexpected situation we abort scanning further entries.
121  FILE* fp = fopen("/proc/self/maps", "r");
122  if (fp == NULL) return result;
123
124  // Allocate enough room to be able to store a full file name.
125  const int kLibNameLen = FILENAME_MAX + 1;
126  char* lib_name = reinterpret_cast<char*>(malloc(kLibNameLen));
127
128  // This loop will terminate once the scanning hits an EOF.
129  while (true) {
130    uintptr_t start, end;
131    char attr_r, attr_w, attr_x, attr_p;
132    // Parse the addresses and permission bits at the beginning of the line.
133    if (fscanf(fp, "%" V8PRIxPTR "-%" V8PRIxPTR, &start, &end) != 2) break;
134    if (fscanf(fp, " %c%c%c%c", &attr_r, &attr_w, &attr_x, &attr_p) != 4) break;
135
136    int c;
137    if (attr_r == 'r' && attr_w != 'w' && attr_x == 'x') {
138      // Found a read-only executable entry. Skip characters until we reach
139      // the beginning of the filename or the end of the line.
140      do {
141        c = getc(fp);
142      } while ((c != EOF) && (c != '\n') && (c != '/'));
143      if (c == EOF) break;  // EOF: Was unexpected, just exit.
144
145      // Process the filename if found.
146      if (c == '/') {
147        ungetc(c, fp);  // Push the '/' back into the stream to be read below.
148
149        // Read to the end of the line. Exit if the read fails.
150        if (fgets(lib_name, kLibNameLen, fp) == NULL) break;
151
152        // Drop the newline character read by fgets. We do not need to check
153        // for a zero-length string because we know that we at least read the
154        // '/' character.
155        lib_name[strlen(lib_name) - 1] = '\0';
156      } else {
157        // No library name found, just record the raw address range.
158        snprintf(lib_name, kLibNameLen,
159                 "%08" V8PRIxPTR "-%08" V8PRIxPTR, start, end);
160      }
161      result.push_back(SharedLibraryAddress(lib_name, start, end));
162    } else {
163      // Entry not describing executable data. Skip to end of line to set up
164      // reading the next entry.
165      do {
166        c = getc(fp);
167      } while ((c != EOF) && (c != '\n'));
168      if (c == EOF) break;
169    }
170  }
171  free(lib_name);
172  fclose(fp);
173  return result;
174}
175
176
177void OS::SignalCodeMovingGC() {
178  // Support for ll_prof.py.
179  //
180  // The Linux profiler built into the kernel logs all mmap's with
181  // PROT_EXEC so that analysis tools can properly attribute ticks. We
182  // do a mmap with a name known by ll_prof.py and immediately munmap
183  // it. This injects a GC marker into the stream of events generated
184  // by the kernel and allows us to synchronize V8 code log and the
185  // kernel log.
186  int size = sysconf(_SC_PAGESIZE);
187  FILE* f = fopen(FLAG_gc_fake_mmap, "w+");
188  if (f == NULL) {
189    OS::PrintError("Failed to open %s\n", FLAG_gc_fake_mmap);
190    OS::Abort();
191  }
192  void* addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE,
193                    fileno(f), 0);
194  ASSERT(addr != MAP_FAILED);
195  OS::Free(addr, size);
196  fclose(f);
197}
198
199
200
201// Constants used for mmap.
202static const int kMmapFd = -1;
203static const int kMmapFdOffset = 0;
204
205
206VirtualMemory::VirtualMemory() : address_(NULL), size_(0) { }
207
208
209VirtualMemory::VirtualMemory(size_t size)
210    : address_(ReserveRegion(size)), size_(size) { }
211
212
213VirtualMemory::VirtualMemory(size_t size, size_t alignment)
214    : address_(NULL), size_(0) {
215  ASSERT(IsAligned(alignment, static_cast<intptr_t>(OS::AllocateAlignment())));
216  size_t request_size = RoundUp(size + alignment,
217                                static_cast<intptr_t>(OS::AllocateAlignment()));
218  void* reservation = mmap(OS::GetRandomMmapAddr(),
219                           request_size,
220                           PROT_NONE,
221                           MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
222                           kMmapFd,
223                           kMmapFdOffset);
224  if (reservation == MAP_FAILED) return;
225
226  Address base = static_cast<Address>(reservation);
227  Address aligned_base = RoundUp(base, alignment);
228  ASSERT_LE(base, aligned_base);
229
230  // Unmap extra memory reserved before and after the desired block.
231  if (aligned_base != base) {
232    size_t prefix_size = static_cast<size_t>(aligned_base - base);
233    OS::Free(base, prefix_size);
234    request_size -= prefix_size;
235  }
236
237  size_t aligned_size = RoundUp(size, OS::AllocateAlignment());
238  ASSERT_LE(aligned_size, request_size);
239
240  if (aligned_size != request_size) {
241    size_t suffix_size = request_size - aligned_size;
242    OS::Free(aligned_base + aligned_size, suffix_size);
243    request_size -= suffix_size;
244  }
245
246  ASSERT(aligned_size == request_size);
247
248  address_ = static_cast<void*>(aligned_base);
249  size_ = aligned_size;
250}
251
252
253VirtualMemory::~VirtualMemory() {
254  if (IsReserved()) {
255    bool result = ReleaseRegion(address(), size());
256    ASSERT(result);
257    USE(result);
258  }
259}
260
261
262bool VirtualMemory::IsReserved() {
263  return address_ != NULL;
264}
265
266
267void VirtualMemory::Reset() {
268  address_ = NULL;
269  size_ = 0;
270}
271
272
273bool VirtualMemory::Commit(void* address, size_t size, bool is_executable) {
274  return CommitRegion(address, size, is_executable);
275}
276
277
278bool VirtualMemory::Uncommit(void* address, size_t size) {
279  return UncommitRegion(address, size);
280}
281
282
283bool VirtualMemory::Guard(void* address) {
284  OS::Guard(address, OS::CommitPageSize());
285  return true;
286}
287
288
289void* VirtualMemory::ReserveRegion(size_t size) {
290  void* result = mmap(OS::GetRandomMmapAddr(),
291                      size,
292                      PROT_NONE,
293                      MAP_PRIVATE | MAP_ANON | MAP_NORESERVE,
294                      kMmapFd,
295                      kMmapFdOffset);
296
297  if (result == MAP_FAILED) return NULL;
298
299  return result;
300}
301
302
303bool VirtualMemory::CommitRegion(void* base, size_t size, bool is_executable) {
304  int prot = PROT_READ | PROT_WRITE | (is_executable ? PROT_EXEC : 0);
305  if (MAP_FAILED == mmap(base,
306                         size,
307                         prot,
308                         MAP_PRIVATE | MAP_ANON | MAP_FIXED,
309                         kMmapFd,
310                         kMmapFdOffset)) {
311    return false;
312  }
313  return true;
314}
315
316
317bool VirtualMemory::UncommitRegion(void* base, size_t size) {
318  return mmap(base,
319              size,
320              PROT_NONE,
321              MAP_PRIVATE | MAP_ANON | MAP_NORESERVE | MAP_FIXED,
322              kMmapFd,
323              kMmapFdOffset) != MAP_FAILED;
324}
325
326
327bool VirtualMemory::ReleaseRegion(void* base, size_t size) {
328  return munmap(base, size) == 0;
329}
330
331
332bool VirtualMemory::HasLazyCommits() {
333  // TODO(alph): implement for the platform.
334  return false;
335}
336
337} }  // namespace v8::internal
338