summaryrefslogtreecommitdiff
path: root/common/testutils/devicetests/com/android/testutils/async/FakeOsAccess.java
blob: 48b57d70be4f029997ed90c252481c4cb1f36819 (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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * 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 com.android.testutils.async;

import android.os.ParcelFileDescriptor;
import android.system.StructPollfd;
import android.util.Log;

import com.android.net.module.util.async.CircularByteBuffer;
import com.android.net.module.util.async.OsAccess;

import java.io.FileDescriptor;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class FakeOsAccess extends OsAccess {
    public static final boolean ENABLE_FINE_DEBUG = true;

    public static final int DEFAULT_FILE_DATA_QUEUE_SIZE = 8 * 1024;

    private enum FileType { PAIR, PIPE }

    // Common poll() constants:
    private static final short POLLIN  = 0x0001;
    private static final short POLLOUT = 0x0004;
    private static final short POLLERR = 0x0008;
    private static final short POLLHUP = 0x0010;

    private static final Constructor<FileDescriptor> FD_CONSTRUCTOR;
    private static final Field FD_FIELD_DESCRIPTOR;
    private static final Field PFD_FIELD_DESCRIPTOR;
    private static final Field PFD_FIELD_GUARD;
    private static final Method CLOSE_GUARD_METHOD_CLOSE;

    private final int mReadQueueSize = DEFAULT_FILE_DATA_QUEUE_SIZE;
    private final int mWriteQueueSize = DEFAULT_FILE_DATA_QUEUE_SIZE;
    private final HashMap<Integer, File> mFiles = new HashMap<>();
    private final byte[] mTmpBuffer = new byte[1024];
    private final long mStartTime;
    private final String mLogTag;
    private int mFileNumberGen = 3;
    private boolean mHasRateLimitedData;

    public FakeOsAccess(String logTag) {
        mLogTag = logTag;
        mStartTime = monotonicTimeMillis();
    }

    @Override
    public long monotonicTimeMillis() {
        return System.nanoTime() / 1000000;
    }

    @Override
    public FileDescriptor getInnerFileDescriptor(ParcelFileDescriptor fd) {
        try {
            return (FileDescriptor) PFD_FIELD_DESCRIPTOR.get(fd);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void close(ParcelFileDescriptor fd) {
        if (fd != null) {
            close(getInnerFileDescriptor(fd));

            try {
                // Reduce CloseGuard warnings.
                Object guard = PFD_FIELD_GUARD.get(fd);
                CLOSE_GUARD_METHOD_CLOSE.invoke(guard);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public synchronized void close(FileDescriptor fd) {
        if (fd != null) {
            File file = getFileOrNull(fd);
            if (file != null) {
                file.decreaseRefCount();
                mFiles.remove(getFileDescriptorNumber(fd));
                setFileDescriptorNumber(fd, -1);
                notifyAll();
            }
        }
    }

    private File getFile(String func, FileDescriptor fd) throws IOException {
        File file = getFileOrNull(fd);
        if (file == null) {
            throw newIOException(func, "Unknown file descriptor: " + getFileDebugName(fd));
        }
        return file;
    }

    private File getFileOrNull(FileDescriptor fd) {
        return mFiles.get(getFileDescriptorNumber(fd));
    }

    @Override
    public String getFileDebugName(ParcelFileDescriptor fd) {
        return (fd != null ? getFileDebugName(getInnerFileDescriptor(fd)) : "null");
    }

    public String getFileDebugName(FileDescriptor fd) {
        if (fd == null) {
            return "null";
        }

        final int fdNumber = getFileDescriptorNumber(fd);
        File file = mFiles.get(fdNumber);

        StringBuilder sb = new StringBuilder();
        if (file != null) {
            if (file.name != null) {
                sb.append(file.name);
                sb.append("/");
            }
            sb.append(file.type);
            sb.append("/");
        } else {
            sb.append("BADFD/");
        }
        sb.append(fdNumber);
        return sb.toString();
    }

    public synchronized void setFileName(FileDescriptor fd, String name) {
        File file = getFileOrNull(fd);
        if (file != null) {
            file.name = name;
        }
    }

    @Override
    public synchronized void setNonBlocking(FileDescriptor fd) throws IOException {
        File file = getFile("fcntl", fd);
        file.isBlocking = false;
    }

    @Override
    public synchronized int read(FileDescriptor fd, byte[] buffer, int pos, int len)
            throws IOException {
        checkBoundaries("read", buffer, pos, len);

        File file = getFile("read", fd);
        if (file.readQueue == null) {
            throw newIOException("read", "File not readable");
        }
        file.checkNonBlocking("read");

        if (len == 0) {
            return 0;
        }

        final int availSize = file.readQueue.size();
        if (availSize == 0) {
            if (file.isEndOfStream) {
                // Java convention uses -1 to indicate end of stream.
                return -1;
            }
            return 0;  // EAGAIN
        }

        final int readCount = Math.min(len, availSize);
        file.readQueue.readBytes(buffer, pos, readCount);
        maybeTransferData(file);
        return readCount;
    }

    @Override
    public synchronized int write(FileDescriptor fd, byte[] buffer, int pos, int len)
            throws IOException {
        checkBoundaries("write", buffer, pos, len);

        File file = getFile("write", fd);
        if (file.writeQueue == null) {
            throw newIOException("read", "File not writable");
        }
        if (file.type == FileType.PIPE && file.sink.openCount == 0) {
            throw newIOException("write", "The other end of pipe is closed");
        }
        file.checkNonBlocking("write");

        if (len == 0) {
            return 0;
        }

        final int originalFreeSize = file.writeQueue.freeSize();
        if (originalFreeSize == 0) {
            return 0;  // EAGAIN
        }

        final int writeCount = Math.min(len, originalFreeSize);
        file.writeQueue.writeBytes(buffer, pos, writeCount);
        maybeTransferData(file);

        if (file.writeQueue.freeSize() < originalFreeSize) {
            final int additionalQueuedCount = originalFreeSize - file.writeQueue.freeSize();
            Log.i(mLogTag, logStr("Delaying transfer of " + additionalQueuedCount
                + " bytes, queued=" + file.writeQueue.size() + ", type=" + file.type
                + ", src_red=" + file.outboundLimiter + ", dst_red=" + file.sink.inboundLimiter));
        }

        return writeCount;
    }

    private void maybeTransferData(File file) {
        boolean hasChanges = copyFileBuffers(file, file.sink);
        hasChanges = copyFileBuffers(file.source, file) || hasChanges;

        if (hasChanges) {
            // TODO(b/245971639): Avoid notifying if no-one is polling.
            notifyAll();
        }
    }

    private boolean copyFileBuffers(File src, File dst) {
        if (src.writeQueue == null || dst.readQueue == null) {
            return false;
        }

        final int originalCopyCount = Math.min(mTmpBuffer.length,
            Math.min(src.writeQueue.size(), dst.readQueue.freeSize()));

        final int allowedCopyCount = RateLimiter.limit(
            src.outboundLimiter, dst.inboundLimiter, originalCopyCount);

        if (allowedCopyCount < originalCopyCount) {
            if (ENABLE_FINE_DEBUG) {
                Log.i(mLogTag, logStr("Delaying transfer of "
                    + (originalCopyCount - allowedCopyCount) + " bytes, original="
                    + originalCopyCount + ", allowed=" + allowedCopyCount
                    + ", type=" + src.type));
            }
            if (originalCopyCount > 0) {
                mHasRateLimitedData = true;
            }
            if (allowedCopyCount == 0) {
                return false;
            }
        }

        boolean hasChanges = false;
        if (allowedCopyCount > 0) {
            if (dst.readQueue.size() == 0 || src.writeQueue.freeSize() == 0) {
                hasChanges = true;  // Read queue had no data, or write queue was full.
            }
            src.writeQueue.readBytes(mTmpBuffer, 0, allowedCopyCount);
            dst.readQueue.writeBytes(mTmpBuffer, 0, allowedCopyCount);
        }

        if (!dst.isEndOfStream && src.openCount == 0
                && src.writeQueue.size() == 0 && dst.readQueue.size() == 0) {
            dst.isEndOfStream = true;
            hasChanges = true;
        }

        return hasChanges;
    }

    public void clearInboundRateLimit(FileDescriptor fd) {
        setInboundRateLimit(fd, Integer.MAX_VALUE);
    }

    public void clearOutboundRateLimit(FileDescriptor fd) {
        setOutboundRateLimit(fd, Integer.MAX_VALUE);
    }

    public synchronized void setInboundRateLimit(FileDescriptor fd, int bytesPerSecond) {
        File file = getFileOrNull(fd);
        if (file != null) {
            file.inboundLimiter.setBytesPerSecond(bytesPerSecond);
            maybeTransferData(file);
        }
    }

    public synchronized void setOutboundRateLimit(FileDescriptor fd, int bytesPerSecond) {
        File file = getFileOrNull(fd);
        if (file != null) {
            file.outboundLimiter.setBytesPerSecond(bytesPerSecond);
            maybeTransferData(file);
        }
    }

    public synchronized ParcelFileDescriptor[] socketpair() throws IOException {
        int fdNumber1 = getNextFd("socketpair");
        int fdNumber2 = getNextFd("socketpair");

        File file1 = new File(FileType.PAIR, mReadQueueSize, mWriteQueueSize);
        File file2 = new File(FileType.PAIR, mReadQueueSize, mWriteQueueSize);

        return registerFilePair(fdNumber1, file1, fdNumber2, file2);
    }

    @Override
    public synchronized ParcelFileDescriptor[] pipe() throws IOException {
        int fdNumber1 = getNextFd("pipe");
        int fdNumber2 = getNextFd("pipe");

        File file1 = new File(FileType.PIPE, mReadQueueSize, 0);
        File file2 = new File(FileType.PIPE, 0, mWriteQueueSize);

        return registerFilePair(fdNumber1, file1, fdNumber2, file2);
    }

    private ParcelFileDescriptor[] registerFilePair(
            int fdNumber1, File file1, int fdNumber2, File file2) {
        file1.sink = file2;
        file1.source = file2;
        file2.sink = file1;
        file2.source = file1;

        mFiles.put(fdNumber1, file1);
        mFiles.put(fdNumber2, file2);
        return new ParcelFileDescriptor[] {
            newParcelFileDescriptor(fdNumber1), newParcelFileDescriptor(fdNumber2)};
    }

    @Override
    public short getPollInMask() {
        return POLLIN;
    }

    @Override
    public short getPollOutMask() {
        return POLLOUT;
    }

    @Override
    public synchronized int poll(StructPollfd[] fds, int timeoutMs) throws IOException {
        if (timeoutMs < 0) {
            timeoutMs = (int) TimeUnit.HOURS.toMillis(1);  // Make "infinite" equal to 1 hour.
        }

        if (fds == null || fds.length > 1000) {
            throw newIOException("poll", "Invalid fds param");
        }
        for (StructPollfd pollFd : fds) {
            getFile("poll", pollFd.fd);
        }

        int waitCallCount = 0;
        final long deadline = monotonicTimeMillis() + timeoutMs;
        while (true) {
            if (mHasRateLimitedData) {
                mHasRateLimitedData = false;
                for (File file : mFiles.values()) {
                    if (file.inboundLimiter.getLastRequestReduction() != 0) {
                        copyFileBuffers(file.source, file);
                    }
                    if (file.outboundLimiter.getLastRequestReduction() != 0) {
                        copyFileBuffers(file, file.sink);
                    }
                }
            }

            final int readyCount = calculateReadyCount(fds);
            if (readyCount > 0) {
                if (ENABLE_FINE_DEBUG) {
                    Log.v(mLogTag, logStr("Poll returns " + readyCount
                            + " after " + waitCallCount + " wait calls"));
                }
                return readyCount;
            }

            long remainingTimeoutMs = deadline - monotonicTimeMillis();
            if (remainingTimeoutMs <= 0) {
                if (ENABLE_FINE_DEBUG) {
                    Log.v(mLogTag, logStr("Poll timeout " + timeoutMs
                            + "ms after " + waitCallCount + " wait calls"));
                }
                return 0;
            }

            if (mHasRateLimitedData) {
                remainingTimeoutMs = Math.min(RateLimiter.BUCKET_DURATION_MS, remainingTimeoutMs);
            }

            try {
                wait(remainingTimeoutMs);
            } catch (InterruptedException e) {
                // Ignore and retry
            }
            waitCallCount++;
        }
    }

    private int calculateReadyCount(StructPollfd[] fds) {
        int fdCount = 0;
        for (StructPollfd pollFd : fds) {
            pollFd.revents = 0;

            File file = getFileOrNull(pollFd.fd);
            if (file == null) {
                Log.w(mLogTag, logStr("Ignoring FD concurrently closed by a buggy app: "
                        + getFileDebugName(pollFd.fd)));
                continue;
            }

            if (ENABLE_FINE_DEBUG) {
                Log.v(mLogTag, logStr("calculateReadyCount fd=" + getFileDebugName(pollFd.fd)
                        + ", events=" + pollFd.events + ", eof=" + file.isEndOfStream
                        + ", r=" + (file.readQueue != null ? file.readQueue.size() : -1)
                        + ", w=" + (file.writeQueue != null ? file.writeQueue.freeSize() : -1)));
            }

            if ((pollFd.events & POLLIN) != 0) {
                if (file.readQueue != null && file.readQueue.size() != 0) {
                    pollFd.revents |= POLLIN;
                }
                if (file.isEndOfStream) {
                    pollFd.revents |= POLLHUP;
                }
            }

            if ((pollFd.events & POLLOUT) != 0) {
                if (file.type == FileType.PIPE && file.sink.openCount == 0) {
                    pollFd.revents |= POLLERR;
                }
                if (file.writeQueue != null && file.writeQueue.freeSize() != 0) {
                    pollFd.revents |= POLLOUT;
                }
            }

            if (pollFd.revents != 0) {
                fdCount++;
            }
        }
        return fdCount;
    }

    private int getNextFd(String func) throws IOException {
        if (mFileNumberGen > 100000) {
            throw newIOException(func, "Too many files open");
        }

        return mFileNumberGen++;
    }

    private static IOException newIOException(String func, String message) {
        return new IOException(message + ", func=" + func);
    }

    public static void checkBoundaries(String func, byte[] buffer, int pos, int len)
            throws IOException {
        if (((buffer.length | pos | len) < 0 || pos > buffer.length - len)) {
            throw newIOException(func, "Invalid array bounds");
        }
    }

    private ParcelFileDescriptor newParcelFileDescriptor(int fdNumber) {
        try {
            return new ParcelFileDescriptor(newFileDescriptor(fdNumber));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private FileDescriptor newFileDescriptor(int fdNumber) {
        try {
            return FD_CONSTRUCTOR.newInstance(Integer.valueOf(fdNumber));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public int getFileDescriptorNumber(FileDescriptor fd) {
        try {
            return (Integer) FD_FIELD_DESCRIPTOR.get(fd);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void setFileDescriptorNumber(FileDescriptor fd, int fdNumber) {
        try {
            FD_FIELD_DESCRIPTOR.set(fd, Integer.valueOf(fdNumber));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String logStr(String message) {
        return "[FakeOs " + (monotonicTimeMillis() - mStartTime) + "] " + message;
    }

    private class File {
        final FileType type;
        final CircularByteBuffer readQueue;
        final CircularByteBuffer writeQueue;
        final RateLimiter inboundLimiter = new RateLimiter(FakeOsAccess.this, Integer.MAX_VALUE);
        final RateLimiter outboundLimiter = new RateLimiter(FakeOsAccess.this, Integer.MAX_VALUE);
        String name;
        int openCount = 1;
        boolean isBlocking = true;
        File sink;
        File source;
        boolean isEndOfStream;

        File(FileType type, int readQueueSize, int writeQueueSize) {
            this.type = type;
            readQueue = (readQueueSize > 0 ? new CircularByteBuffer(readQueueSize) : null);
            writeQueue = (writeQueueSize > 0 ? new CircularByteBuffer(writeQueueSize) : null);
        }

        void decreaseRefCount() {
            if (openCount <= 0) {
                throw new IllegalStateException();
            }
            openCount--;
        }

        void checkNonBlocking(String func) throws IOException {
            if (isBlocking) {
                throw newIOException(func, "File in blocking mode");
            }
        }
    }

    static {
        try {
            FD_CONSTRUCTOR = FileDescriptor.class.getDeclaredConstructor(int.class);
            FD_CONSTRUCTOR.setAccessible(true);

            Field descriptorIntField;
            try {
                descriptorIntField = FileDescriptor.class.getDeclaredField("descriptor");
            } catch (NoSuchFieldException e) {
                descriptorIntField = FileDescriptor.class.getDeclaredField("fd");
            }
            FD_FIELD_DESCRIPTOR = descriptorIntField;
            FD_FIELD_DESCRIPTOR.setAccessible(true);

            PFD_FIELD_DESCRIPTOR = ParcelFileDescriptor.class.getDeclaredField("mFd");
            PFD_FIELD_DESCRIPTOR.setAccessible(true);

            PFD_FIELD_GUARD = ParcelFileDescriptor.class.getDeclaredField("mGuard");
            PFD_FIELD_GUARD.setAccessible(true);

            CLOSE_GUARD_METHOD_CLOSE = Class.forName("dalvik.system.CloseGuard")
                .getDeclaredMethod("close");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}