summaryrefslogtreecommitdiffhomepage
path: root/test/syscalls/linux/shm.cc
blob: 9f57476c93b9f2ca676ef10ad660c1fa34953eac (plain)
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <stdio.h>

#include <sys/ipc.h>
#include <sys/mman.h>
#include <sys/shm.h>
#include <sys/types.h>

#include "absl/time/clock.h"
#include "test/util/multiprocess_util.h"
#include "test/util/posix_error.h"
#include "test/util/temp_path.h"
#include "test/util/test_util.h"

namespace gvisor {
namespace testing {
namespace {

using ::testing::_;

const uint64_t kAllocSize = kPageSize * 128ULL;

PosixErrorOr<int> Shmget(key_t key, size_t size, int shmflg) {
  int id = shmget(key, size, shmflg);
  if (id == -1) {
    return PosixError(errno, "shmget() failed");
  }
  return id;
}

PosixErrorOr<char*> Shmat(int shmid, const void* shmaddr, int shmflg) {
  const intptr_t addr =
      reinterpret_cast<intptr_t>(shmat(shmid, shmaddr, shmflg));
  if (addr == -1) {
    return PosixError(errno, "shmat() failed");
  }
  return reinterpret_cast<char*>(addr);
}

PosixError Shmdt(const char* shmaddr) {
  const int ret = shmdt(shmaddr);
  if (ret == -1) {
    return PosixError(errno, "shmdt() failed");
  }
  return NoError();
}

template <typename T>
PosixErrorOr<int> Shmctl(int shmid, int cmd, T* buf) {
  int ret = shmctl(shmid, cmd, reinterpret_cast<struct shmid_ds*>(buf));
  if (ret == -1) {
    return PosixError(errno, "shmctl() failed");
  }
  return ret;
}

TEST(ShmTest, AttachDetach) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  struct shmid_ds attr;
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  EXPECT_EQ(attr.shm_segsz, kAllocSize);
  EXPECT_EQ(attr.shm_nattch, 0);

  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  EXPECT_EQ(attr.shm_nattch, 1);

  const char* addr2 = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  EXPECT_EQ(attr.shm_nattch, 2);

  ASSERT_NO_ERRNO(Shmdt(addr));
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  EXPECT_EQ(attr.shm_nattch, 1);

  ASSERT_NO_ERRNO(Shmdt(addr2));
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  EXPECT_EQ(attr.shm_nattch, 0);
}

TEST(ShmTest, LookupByKey) {
  const TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const key_t key = ftok(keyfile.path().c_str(), 1);
  const int id =
      ASSERT_NO_ERRNO_AND_VALUE(Shmget(key, kAllocSize, IPC_CREAT | 0777));
  const int id2 = ASSERT_NO_ERRNO_AND_VALUE(Shmget(key, kAllocSize, 0777));
  EXPECT_EQ(id, id2);
}

TEST(ShmTest, DetachedSegmentsPersist) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  addr[0] = 'x';
  ASSERT_NO_ERRNO(Shmdt(addr));

  // We should be able to re-attach to the same segment and get our data back.
  addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  EXPECT_EQ(addr[0], 'x');
  ASSERT_NO_ERRNO(Shmdt(addr));
}

TEST(ShmTest, MultipleDetachFails) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmdt(addr));
  EXPECT_THAT(Shmdt(addr), PosixErrorIs(EINVAL, _));
}

TEST(ShmTest, IpcStat) {
  const TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const key_t key = ftok(keyfile.path().c_str(), 1);

  const time_t start = time(nullptr);

  const int id =
      ASSERT_NO_ERRNO_AND_VALUE(Shmget(key, kAllocSize, IPC_CREAT | 0777));

  const uid_t uid = getuid();
  const gid_t gid = getgid();
  const pid_t pid = getpid();

  struct shmid_ds attr;
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));

  EXPECT_EQ(attr.shm_perm.__key, key);
  EXPECT_EQ(attr.shm_perm.uid, uid);
  EXPECT_EQ(attr.shm_perm.gid, gid);
  EXPECT_EQ(attr.shm_perm.cuid, uid);
  EXPECT_EQ(attr.shm_perm.cgid, gid);
  EXPECT_EQ(attr.shm_perm.mode, 0777);

  EXPECT_EQ(attr.shm_segsz, kAllocSize);

  EXPECT_EQ(attr.shm_atime, 0);
  EXPECT_EQ(attr.shm_dtime, 0);

  // Change time is set on creation.
  EXPECT_GE(attr.shm_ctime, start);

  EXPECT_EQ(attr.shm_cpid, pid);
  EXPECT_EQ(attr.shm_lpid, 0);

  EXPECT_EQ(attr.shm_nattch, 0);

  // The timestamps only have a resolution of seconds; slow down so we actually
  // see the timestamps change.
  absl::SleepFor(absl::Seconds(1));
  const time_t pre_attach = time(nullptr);

  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));

  EXPECT_GE(attr.shm_atime, pre_attach);
  EXPECT_EQ(attr.shm_dtime, 0);
  EXPECT_LT(attr.shm_ctime, pre_attach);
  EXPECT_EQ(attr.shm_lpid, pid);
  EXPECT_EQ(attr.shm_nattch, 1);

  absl::SleepFor(absl::Seconds(1));
  const time_t pre_detach = time(nullptr);

  ASSERT_NO_ERRNO(Shmdt(addr));
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));

  EXPECT_LT(attr.shm_atime, pre_detach);
  EXPECT_GE(attr.shm_dtime, pre_detach);
  EXPECT_LT(attr.shm_ctime, pre_detach);
  EXPECT_EQ(attr.shm_lpid, pid);
  EXPECT_EQ(attr.shm_nattch, 0);
}

TEST(ShmTest, ShmStat) {
  // This test relies on the segment we create to be the first one on the
  // system, causing it to occupy slot 1. We can't reasonably expect this on a
  // general Linux host.
  SKIP_IF(!IsRunningOnGvisor());

  ASSERT_NO_ERRNO(Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  struct shmid_ds attr;
  ASSERT_NO_ERRNO(Shmctl(1, SHM_STAT, &attr));
  // This does the same thing as IPC_STAT, so only test that the syscall
  // succeeds here.
}

TEST(ShmTest, IpcInfo) {
  struct shminfo info;
  ASSERT_NO_ERRNO(Shmctl(0, IPC_INFO, &info));

  EXPECT_EQ(info.shmmin, 1);  // This is always 1, according to the man page.
  EXPECT_GT(info.shmmax, info.shmmin);
  EXPECT_GT(info.shmmni, 0);
  EXPECT_GT(info.shmseg, 0);
  EXPECT_GT(info.shmall, 0);
}

TEST(ShmTest, ShmInfo) {
  struct shm_info info;

  // We generally can't know what other processes on a linux machine
  // does with shared memory segments, so we can't test specific
  // numbers on Linux. When running under gvisor, we're guaranteed to
  // be the only ones using shm, so we can easily verify machine-wide
  // numbers.
  if (IsRunningOnGvisor()) {
    ASSERT_NO_ERRNO(Shmctl(0, SHM_INFO, &info));
    EXPECT_EQ(info.used_ids, 0);
    EXPECT_EQ(info.shm_tot, 0);
    EXPECT_EQ(info.shm_rss, 0);
    EXPECT_EQ(info.shm_swp, 0);
  }

  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));

  ASSERT_NO_ERRNO(Shmctl(1, SHM_INFO, &info));

  if (IsRunningOnGvisor()) {
    ASSERT_NO_ERRNO(Shmctl(id, SHM_INFO, &info));
    EXPECT_EQ(info.used_ids, 1);
    EXPECT_EQ(info.shm_tot, kAllocSize / kPageSize);
    EXPECT_EQ(info.shm_rss, kAllocSize / kPageSize);
    EXPECT_EQ(info.shm_swp, 0);  // Gvisor currently never swaps.
  }

  ASSERT_NO_ERRNO(Shmdt(addr));
}

TEST(ShmTest, ShmCtlSet) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));

  struct shmid_ds attr;
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  ASSERT_EQ(attr.shm_perm.mode, 0777);

  attr.shm_perm.mode = 0766;
  ASSERT_NO_ERRNO(Shmctl(id, IPC_SET, &attr));

  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  ASSERT_EQ(attr.shm_perm.mode, 0766);

  ASSERT_NO_ERRNO(Shmdt(addr));
}

TEST(ShmTest, RemovedSegmentsAreMarkedDeleted) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmctl<void>(id, IPC_RMID, nullptr));
  struct shmid_ds attr;
  ASSERT_NO_ERRNO(Shmctl(id, IPC_STAT, &attr));
  EXPECT_NE(attr.shm_perm.mode & SHM_DEST, 0);
  ASSERT_NO_ERRNO(Shmdt(addr));
}

TEST(ShmTest, RemovedSegmentsAreDestroyed) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));

  const uint64_t alloc_pages = kAllocSize / kPageSize;

  struct shm_info info;
  ASSERT_NO_ERRNO(Shmctl(1, SHM_INFO, &info));
  const uint64_t before = info.shm_tot;

  ASSERT_NO_ERRNO(Shmctl<void>(id, IPC_RMID, nullptr));
  ASSERT_NO_ERRNO(Shmdt(addr));

  ASSERT_NO_ERRNO(Shmctl(1, SHM_INFO, &info));
  const uint64_t after = info.shm_tot;
  EXPECT_EQ(after, before - alloc_pages);
}

TEST(ShmTest, AllowsAttachToRemovedSegmentWithRefs) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  const char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmctl<void>(id, IPC_RMID, nullptr));
  const char* addr2 = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  ASSERT_NO_ERRNO(Shmdt(addr));
  ASSERT_NO_ERRNO(Shmdt(addr2));
}

TEST(ShmTest, RemovedSegmentsAreNotDiscoverable) {
  const TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const key_t key = ftok(keyfile.path().c_str(), 1);
  const int id =
      ASSERT_NO_ERRNO_AND_VALUE(Shmget(key, kAllocSize, IPC_CREAT | 0777));
  ASSERT_NO_ERRNO(Shmctl<void>(id, IPC_RMID, nullptr));
  EXPECT_THAT(Shmget(key, kAllocSize, 0777), PosixErrorIs(ENOENT, _));
}

TEST(ShmDeathTest, ReadonlySegment) {
  SetupGvisorDeathTest();
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, SHM_RDONLY));
  // Reading succeeds.
  static_cast<void>(addr[0]);
  // Writing fails.
  EXPECT_EXIT(addr[0] = 'x', ::testing::KilledBySignal(SIGSEGV), "");
}

TEST(ShmDeathTest, SegmentNotAccessibleAfterDetach) {
  // This test is susceptible to races with concurrent mmaps running in parallel
  // gtest threads since the test relies on the address freed during a shm
  // segment destruction to remain unused. We run the test body in a forked
  // child to guarantee a single-threaded context to avoid this.

  SetupGvisorDeathTest();

  const auto rest = [&] {
    const int id = ASSERT_NO_ERRNO_AND_VALUE(
        Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
    char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
    addr[0] = 'x';
    ASSERT_NO_ERRNO(Shmdt(addr));

    // This access should cause a SIGSEGV.
    addr[0] = 'x';
  };

  EXPECT_THAT(InForkedProcess(rest),
              IsPosixErrorOkAndHolds(W_EXITCODE(0, SIGSEGV)));
}

TEST(ShmTest, RequestingSegmentSmallerThanSHMMINFails) {
  struct shminfo info;
  ASSERT_NO_ERRNO(Shmctl(0, IPC_INFO, &info));
  const uint64_t size = info.shmmin - 1;
  EXPECT_THAT(Shmget(IPC_PRIVATE, size, IPC_CREAT | 0777),
              PosixErrorIs(EINVAL, _));
}

TEST(ShmTest, RequestingSegmentLargerThanSHMMAXFails) {
  struct shminfo info;
  ASSERT_NO_ERRNO(Shmctl(0, IPC_INFO, &info));
  const uint64_t size = info.shmmax + kPageSize;
  EXPECT_THAT(Shmget(IPC_PRIVATE, size, IPC_CREAT | 0777),
              PosixErrorIs(EINVAL, _));
}

TEST(ShmTest, RequestingUnalignedSizeSucceeds) {
  EXPECT_NO_ERRNO(Shmget(IPC_PRIVATE, 4097, IPC_CREAT | 0777));
}

TEST(ShmTest, RequestingDuplicateCreationFails) {
  const TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const key_t key = ftok(keyfile.path().c_str(), 1);
  ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(key, kAllocSize, IPC_CREAT | IPC_EXCL | 0777));
  EXPECT_THAT(Shmget(key, kAllocSize, IPC_CREAT | IPC_EXCL | 0777),
              PosixErrorIs(EEXIST, _));
}

TEST(ShmTest, SegmentsSizeFixedOnCreation) {
  const TempPath keyfile = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFile());
  const key_t key = ftok(keyfile.path().c_str(), 1);

  // Base segment.
  const int id =
      ASSERT_NO_ERRNO_AND_VALUE(Shmget(key, kAllocSize, IPC_CREAT | 0777));

  // Ask for the same segment at half size. This succeeds.
  const int id2 = ASSERT_NO_ERRNO_AND_VALUE(Shmget(key, kAllocSize / 2, 0777));

  // Ask for the same segment at double size.
  EXPECT_THAT(Shmget(key, kAllocSize * 2, 0777), PosixErrorIs(EINVAL, _));

  char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  char* addr2 = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id2, nullptr, 0));

  // We have 2 different maps...
  EXPECT_NE(addr, addr2);

  // ... And both maps are kAllocSize bytes; despite asking for a half-sized
  // segment for the second map.
  addr[kAllocSize - 1] = 'x';
  addr2[kAllocSize - 1] = 'x';

  ASSERT_NO_ERRNO(Shmdt(addr));
  ASSERT_NO_ERRNO(Shmdt(addr2));
}

TEST(ShmTest, PartialUnmap) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  EXPECT_THAT(munmap(addr + (kAllocSize / 4), kAllocSize / 2),
              SyscallSucceeds());
  ASSERT_NO_ERRNO(Shmdt(addr));
}

// Check that sentry does not panic when asked for a zero-length private shm
// segment.
TEST(ShmTest, GracefullyFailOnZeroLenSegmentCreation) {
  EXPECT_THAT(Shmget(IPC_PRIVATE, 0, 0), PosixErrorIs(EINVAL, _));
}

TEST(ShmTest, NoDestructionOfAttachedSegmentWithMultipleRmid) {
  const int id = ASSERT_NO_ERRNO_AND_VALUE(
      Shmget(IPC_PRIVATE, kAllocSize, IPC_CREAT | 0777));
  char* addr = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));
  char* addr2 = ASSERT_NO_ERRNO_AND_VALUE(Shmat(id, nullptr, 0));

  // There should be 2 refs to the segment from the 2 attachments, and a single
  // self-reference. Mark the segment as destroyed more than 3 times through
  // shmctl(RMID). If there's a bug with the ref counting, this should cause the
  // count to drop to zero.
  for (int i = 0; i < 6; ++i) {
    ASSERT_NO_ERRNO(Shmctl<void>(id, IPC_RMID, nullptr));
  }

  // Segment should remain accessible.
  addr[0] = 'x';
  ASSERT_NO_ERRNO(Shmdt(addr));

  // Segment should remain accessible even after one of the two attachments are
  // detached.
  addr2[0] = 'x';
  ASSERT_NO_ERRNO(Shmdt(addr2));
}

}  // namespace
}  // namespace testing
}  // namespace gvisor