1 /* 2 * Copyright (C) 2010 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 #ifndef NET_FD_H_included 18 #define NET_FD_H_included 19 20 #include <nativehelper/JNIHelp.h> 21 22 /** 23 * Wraps access to the int inside a java.io.FileDescriptor, taking care of throwing exceptions. 24 */ 25 class NetFd { 26 public: NetFd(JNIEnv * env,jobject fileDescriptor)27 NetFd(JNIEnv* env, jobject fileDescriptor) 28 : mEnv(env), mFileDescriptor(fileDescriptor), mFd(-1) 29 { 30 } 31 isClosed()32 bool isClosed() { 33 mFd = jniGetFDFromFileDescriptor(mEnv, mFileDescriptor); 34 bool closed = (mFd == -1); 35 if (closed) { 36 jniThrowException(mEnv, "java/net/SocketException", "Socket closed"); 37 } 38 return closed; 39 } 40 get()41 int get() const { 42 return mFd; 43 } 44 45 private: 46 JNIEnv* mEnv; 47 jobject mFileDescriptor; 48 int mFd; 49 50 // Disallow copy and assignment. 51 NetFd(const NetFd&); 52 void operator=(const NetFd&); 53 }; 54 55 /** 56 * Used to retry syscalls that can return EINTR. This differs from TEMP_FAILURE_RETRY in that 57 * it also considers the case where the reason for failure is that another thread called 58 * Socket.close. 59 */ 60 #define NET_FAILURE_RETRY(fd, exp) ({ \ 61 typeof (exp) _rc; \ 62 do { \ 63 _rc = (exp); \ 64 if (_rc == -1) { \ 65 if (fd.isClosed() || errno != EINTR) { \ 66 break; \ 67 } \ 68 } \ 69 } while (_rc == -1); \ 70 _rc; }) 71 72 #endif // NET_FD_H_included 73