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
|
// Copyright 2018 The gVisor Authors.
//
// 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.
package fsutil
import (
"bytes"
"io"
"testing"
"gvisor.googlesource.com/gvisor/pkg/sentry/context"
"gvisor.googlesource.com/gvisor/pkg/sentry/context/contexttest"
"gvisor.googlesource.com/gvisor/pkg/sentry/fs"
ktime "gvisor.googlesource.com/gvisor/pkg/sentry/kernel/time"
"gvisor.googlesource.com/gvisor/pkg/sentry/memmap"
"gvisor.googlesource.com/gvisor/pkg/sentry/safemem"
"gvisor.googlesource.com/gvisor/pkg/sentry/usermem"
"gvisor.googlesource.com/gvisor/pkg/syserror"
)
type noopBackingFile struct{}
func (noopBackingFile) ReadToBlocksAt(ctx context.Context, dsts safemem.BlockSeq, offset uint64) (uint64, error) {
return dsts.NumBytes(), nil
}
func (noopBackingFile) WriteFromBlocksAt(ctx context.Context, srcs safemem.BlockSeq, offset uint64) (uint64, error) {
return srcs.NumBytes(), nil
}
func (noopBackingFile) SetMaskedAttributes(context.Context, fs.AttrMask, fs.UnstableAttr) error {
return nil
}
func (noopBackingFile) Sync(context.Context) error {
return nil
}
func (noopBackingFile) FD() int {
return -1
}
func (noopBackingFile) Allocate(ctx context.Context, offset int64, length int64) error {
return nil
}
func TestSetPermissions(t *testing.T) {
ctx := contexttest.Context(t)
uattr := fs.WithCurrentTime(ctx, fs.UnstableAttr{
Perms: fs.FilePermsFromMode(0444),
})
iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, false /*forcePageCache*/)
defer iops.Release()
perms := fs.FilePermsFromMode(0777)
if !iops.SetPermissions(ctx, nil, perms) {
t.Fatalf("SetPermissions failed, want success")
}
// Did permissions change?
if iops.attr.Perms != perms {
t.Fatalf("got perms +%v, want +%v", iops.attr.Perms, perms)
}
// Did status change time change?
if !iops.dirtyAttr.StatusChangeTime {
t.Fatalf("got status change time not dirty, want dirty")
}
if iops.attr.StatusChangeTime.Equal(uattr.StatusChangeTime) {
t.Fatalf("got status change time unchanged")
}
}
func TestSetTimestamps(t *testing.T) {
ctx := contexttest.Context(t)
for _, test := range []struct {
desc string
ts fs.TimeSpec
wantChanged fs.AttrMask
}{
{
desc: "noop",
ts: fs.TimeSpec{
ATimeOmit: true,
MTimeOmit: true,
},
wantChanged: fs.AttrMask{},
},
{
desc: "access time only",
ts: fs.TimeSpec{
ATime: ktime.NowFromContext(ctx),
MTimeOmit: true,
},
wantChanged: fs.AttrMask{
AccessTime: true,
},
},
{
desc: "modification time only",
ts: fs.TimeSpec{
ATimeOmit: true,
MTime: ktime.NowFromContext(ctx),
},
wantChanged: fs.AttrMask{
ModificationTime: true,
},
},
{
desc: "access and modification time",
ts: fs.TimeSpec{
ATime: ktime.NowFromContext(ctx),
MTime: ktime.NowFromContext(ctx),
},
wantChanged: fs.AttrMask{
AccessTime: true,
ModificationTime: true,
},
},
{
desc: "system time access and modification time",
ts: fs.TimeSpec{
ATimeSetSystemTime: true,
MTimeSetSystemTime: true,
},
wantChanged: fs.AttrMask{
AccessTime: true,
ModificationTime: true,
},
},
} {
t.Run(test.desc, func(t *testing.T) {
ctx := contexttest.Context(t)
epoch := ktime.ZeroTime
uattr := fs.UnstableAttr{
AccessTime: epoch,
ModificationTime: epoch,
StatusChangeTime: epoch,
}
iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, false /*forcePageCache*/)
defer iops.Release()
if err := iops.SetTimestamps(ctx, nil, test.ts); err != nil {
t.Fatalf("SetTimestamps got error %v, want nil", err)
}
if test.wantChanged.AccessTime {
if !iops.attr.AccessTime.After(uattr.AccessTime) {
t.Fatalf("diritied access time did not advance, want %v > %v", iops.attr.AccessTime, uattr.AccessTime)
}
if !iops.dirtyAttr.StatusChangeTime {
t.Fatalf("dirty access time requires dirty status change time")
}
if !iops.attr.StatusChangeTime.After(uattr.StatusChangeTime) {
t.Fatalf("dirtied status change time did not advance")
}
}
if test.wantChanged.ModificationTime {
if !iops.attr.ModificationTime.After(uattr.ModificationTime) {
t.Fatalf("diritied modification time did not advance")
}
if !iops.dirtyAttr.StatusChangeTime {
t.Fatalf("dirty modification time requires dirty status change time")
}
if !iops.attr.StatusChangeTime.After(uattr.StatusChangeTime) {
t.Fatalf("dirtied status change time did not advance")
}
}
})
}
}
func TestTruncate(t *testing.T) {
ctx := contexttest.Context(t)
uattr := fs.UnstableAttr{
Size: 0,
}
iops := NewCachingInodeOperations(ctx, noopBackingFile{}, uattr, false /*forcePageCache*/)
defer iops.Release()
if err := iops.Truncate(ctx, nil, uattr.Size); err != nil {
t.Fatalf("Truncate got error %v, want nil", err)
}
var size int64 = 4096
if err := iops.Truncate(ctx, nil, size); err != nil {
t.Fatalf("Truncate got error %v, want nil", err)
}
if iops.attr.Size != size {
t.Fatalf("Truncate got %d, want %d", iops.attr.Size, size)
}
if !iops.dirtyAttr.ModificationTime || !iops.dirtyAttr.StatusChangeTime {
t.Fatalf("Truncate did not dirty modification and status change time")
}
if !iops.attr.ModificationTime.After(uattr.ModificationTime) {
t.Fatalf("dirtied modification time did not change")
}
if !iops.attr.StatusChangeTime.After(uattr.StatusChangeTime) {
t.Fatalf("dirtied status change time did not change")
}
}
type sliceBackingFile struct {
data []byte
}
func newSliceBackingFile(data []byte) *sliceBackingFile {
return &sliceBackingFile{data}
}
func (f *sliceBackingFile) ReadToBlocksAt(ctx context.Context, dsts safemem.BlockSeq, offset uint64) (uint64, error) {
r := safemem.BlockSeqReader{safemem.BlockSeqOf(safemem.BlockFromSafeSlice(f.data)).DropFirst64(offset)}
return r.ReadToBlocks(dsts)
}
func (f *sliceBackingFile) WriteFromBlocksAt(ctx context.Context, srcs safemem.BlockSeq, offset uint64) (uint64, error) {
w := safemem.BlockSeqWriter{safemem.BlockSeqOf(safemem.BlockFromSafeSlice(f.data)).DropFirst64(offset)}
return w.WriteFromBlocks(srcs)
}
func (*sliceBackingFile) SetMaskedAttributes(context.Context, fs.AttrMask, fs.UnstableAttr) error {
return nil
}
func (*sliceBackingFile) Sync(context.Context) error {
return nil
}
func (*sliceBackingFile) FD() int {
return -1
}
func (f *sliceBackingFile) Allocate(ctx context.Context, offset int64, length int64) error {
return syserror.EOPNOTSUPP
}
type noopMappingSpace struct{}
// Invalidate implements memmap.MappingSpace.Invalidate.
func (noopMappingSpace) Invalidate(ar usermem.AddrRange, opts memmap.InvalidateOpts) {
}
func anonInode(ctx context.Context) *fs.Inode {
return fs.NewInode(&SimpleFileInode{
InodeSimpleAttributes: NewInodeSimpleAttributes(ctx, fs.FileOwnerFromContext(ctx), fs.FilePermissions{
User: fs.PermMask{Read: true, Write: true},
}, 0),
}, fs.NewPseudoMountSource(), fs.StableAttr{
Type: fs.Anonymous,
BlockSize: usermem.PageSize,
})
}
func pagesOf(bs ...byte) []byte {
buf := make([]byte, 0, len(bs)*usermem.PageSize)
for _, b := range bs {
buf = append(buf, bytes.Repeat([]byte{b}, usermem.PageSize)...)
}
return buf
}
func TestRead(t *testing.T) {
ctx := contexttest.Context(t)
// Construct a 3-page file.
buf := pagesOf('a', 'b', 'c')
file := fs.NewFile(ctx, fs.NewDirent(anonInode(ctx), "anon"), fs.FileFlags{}, nil)
uattr := fs.UnstableAttr{
Size: int64(len(buf)),
}
iops := NewCachingInodeOperations(ctx, newSliceBackingFile(buf), uattr, false /*forcePageCache*/)
defer iops.Release()
// Expect the cache to be initially empty.
if cached := iops.cache.Span(); cached != 0 {
t.Errorf("Span got %d, want 0", cached)
}
// Create a memory mapping of the second page (as CachingInodeOperations
// expects to only cache mapped pages), then call Translate to force it to
// be cached.
var ms noopMappingSpace
ar := usermem.AddrRange{usermem.PageSize, 2 * usermem.PageSize}
if err := iops.AddMapping(ctx, ms, ar, usermem.PageSize, true); err != nil {
t.Fatalf("AddMapping got %v, want nil", err)
}
mr := memmap.MappableRange{usermem.PageSize, 2 * usermem.PageSize}
if _, err := iops.Translate(ctx, mr, mr, usermem.Read); err != nil {
t.Fatalf("Translate got %v, want nil", err)
}
if cached := iops.cache.Span(); cached != usermem.PageSize {
t.Errorf("SpanRange got %d, want %d", cached, usermem.PageSize)
}
// Try to read 4 pages. The first and third pages should be read directly
// from the "file", the second page should be read from the cache, and only
// 3 pages (the size of the file) should be readable.
rbuf := make([]byte, 4*usermem.PageSize)
dst := usermem.BytesIOSequence(rbuf)
n, err := iops.Read(ctx, file, dst, 0)
if n != 3*usermem.PageSize || (err != nil && err != io.EOF) {
t.Fatalf("Read got (%d, %v), want (%d, nil or EOF)", n, err, 3*usermem.PageSize)
}
rbuf = rbuf[:3*usermem.PageSize]
// Did we get the bytes we expect?
if !bytes.Equal(rbuf, buf) {
t.Errorf("Read back bytes %v, want %v", rbuf, buf)
}
// Delete the memory mapping before iops.Release(). The cached page will
// either be evicted by ctx's pgalloc.MemoryFile, or dropped by
// iops.Release().
iops.RemoveMapping(ctx, ms, ar, usermem.PageSize, true)
}
func TestWrite(t *testing.T) {
ctx := contexttest.Context(t)
// Construct a 4-page file.
buf := pagesOf('a', 'b', 'c', 'd')
orig := append([]byte(nil), buf...)
inode := anonInode(ctx)
uattr := fs.UnstableAttr{
Size: int64(len(buf)),
}
iops := NewCachingInodeOperations(ctx, newSliceBackingFile(buf), uattr, false /*forcePageCache*/)
defer iops.Release()
// Expect the cache to be initially empty.
if cached := iops.cache.Span(); cached != 0 {
t.Errorf("Span got %d, want 0", cached)
}
// Create a memory mapping of the second and third pages (as
// CachingInodeOperations expects to only cache mapped pages), then call
// Translate to force them to be cached.
var ms noopMappingSpace
ar := usermem.AddrRange{usermem.PageSize, 3 * usermem.PageSize}
if err := iops.AddMapping(ctx, ms, ar, usermem.PageSize, true); err != nil {
t.Fatalf("AddMapping got %v, want nil", err)
}
defer iops.RemoveMapping(ctx, ms, ar, usermem.PageSize, true)
mr := memmap.MappableRange{usermem.PageSize, 3 * usermem.PageSize}
if _, err := iops.Translate(ctx, mr, mr, usermem.Read); err != nil {
t.Fatalf("Translate got %v, want nil", err)
}
if cached := iops.cache.Span(); cached != 2*usermem.PageSize {
t.Errorf("SpanRange got %d, want %d", cached, 2*usermem.PageSize)
}
// Write to the first 2 pages.
wbuf := pagesOf('e', 'f')
src := usermem.BytesIOSequence(wbuf)
n, err := iops.Write(ctx, src, 0)
if n != 2*usermem.PageSize || err != nil {
t.Fatalf("Write got (%d, %v), want (%d, nil)", n, err, 2*usermem.PageSize)
}
// The first page should have been written directly, since it was not cached.
want := append([]byte(nil), orig...)
copy(want, pagesOf('e'))
if !bytes.Equal(buf, want) {
t.Errorf("File contents are %v, want %v", buf, want)
}
// Sync back to the "backing file".
if err := iops.WriteOut(ctx, inode); err != nil {
t.Errorf("Sync got %v, want nil", err)
}
// Now the second page should have been written as well.
copy(want[usermem.PageSize:], pagesOf('f'))
if !bytes.Equal(buf, want) {
t.Errorf("File contents are %v, want %v", buf, want)
}
}
|