• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.pinner;
18 
19 import android.annotation.Nullable;
20 import android.system.ErrnoException;
21 import android.system.Os;
22 import android.system.OsConstants;
23 import android.util.Slog;
24 
25 import java.io.Closeable;
26 import java.io.FileDescriptor;
27 import java.io.IOException;
28 
29 /* package */ final class PinnerUtils {
30     private static final String TAG = "PinnerUtils";
31 
clamp(long min, long value, long max)32     public static long clamp(long min, long value, long max) {
33         return Math.max(min, Math.min(value, max));
34     }
35 
safeMunmap(long address, long mapSize)36     public static void safeMunmap(long address, long mapSize) {
37         try {
38             Os.munmap(address, mapSize);
39         } catch (ErrnoException ex) {
40             Slog.w(TAG, "ignoring error in unmap", ex);
41         }
42     }
43 
44     /**
45      * Close FD, swallowing irrelevant errors.
46      */
safeClose(@ullable FileDescriptor fd)47     public static void safeClose(@Nullable FileDescriptor fd) {
48         if (fd != null && fd.valid()) {
49             try {
50                 Os.close(fd);
51             } catch (ErrnoException ex) {
52                 // Swallow the exception: non-EBADF errors in close(2)
53                 // indicate deferred paging write errors, which we
54                 // don't care about here. The underlying file
55                 // descriptor is always closed.
56                 if (ex.errno == OsConstants.EBADF) {
57                     throw new AssertionError(ex);
58                 }
59             }
60         }
61     }
62 
63     /**
64      * Close closeable thing, swallowing errors.
65      */
safeClose(@ullable Closeable thing)66     public static void safeClose(@Nullable Closeable thing) {
67         if (thing != null) {
68             try {
69                 thing.close();
70             } catch (IOException ex) {
71                 Slog.w(TAG, "ignoring error closing resource: " + thing, ex);
72             }
73         }
74     }
75 }
76