1 /* 2 * Copyright (C) 2025 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 libcore.io; 18 19 import android.system.ErrnoException; 20 import android.system.Os; 21 import android.system.OsConstants; 22 23 import java.io.FileDescriptor; 24 import java.io.FileNotFoundException; 25 import java.io.IOException; 26 27 public class IoBridge { 28 closeAndSignalBlockedThreads(FileDescriptor fd)29 public static void closeAndSignalBlockedThreads(FileDescriptor fd) throws IOException { 30 if (fd == null) { 31 return; 32 } 33 try { 34 Os.close(fd); 35 } catch (ErrnoException errnoException) { 36 throw errnoException.rethrowAsIOException(); 37 } 38 } 39 open(String path, int flags)40 public static FileDescriptor open(String path, int flags) throws FileNotFoundException { 41 FileDescriptor fd = null; 42 try { 43 fd = Os.open(path, flags, 0666); 44 // Posix open(2) fails with EISDIR only if you ask for write permission. 45 // Java disallows reading directories too.f 46 if (OsConstants.S_ISDIR(Os.fstat(fd).st_mode)) { 47 throw new ErrnoException("open", OsConstants.EISDIR); 48 } 49 return fd; 50 } catch (ErrnoException errnoException) { 51 try { 52 if (fd != null) { 53 closeAndSignalBlockedThreads(fd); 54 } 55 } catch (IOException ignored) { 56 } 57 FileNotFoundException ex = new FileNotFoundException(path + ": " 58 + errnoException.getMessage()); 59 ex.initCause(errnoException); 60 throw ex; 61 } 62 } 63 } 64