android.system.OsConstants Java Examples
The following examples show how to use
android.system.OsConstants.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContextImpl.java From AndroidComponentPlugin with Apache License 2.0 | 6 votes |
/** * Common-path handling of app data dir creation */ private static File ensurePrivateDirExists(File file) { if (!file.exists()) { try { Os.mkdir(file.getAbsolutePath(), 0771); Os.chmod(file.getAbsolutePath(), 0771); } catch (ErrnoException e) { if (e.errno == OsConstants.EEXIST) { // We must have raced with someone; that's okay } else { Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage()); } } } return file; }
Example #2
Source File: ConnectStats.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
@Override public String toString() { StringBuilder builder = new StringBuilder("ConnectStats(").append("netId=").append(netId).append(", "); for (int t : BitUtils.unpackBits(transports)) { builder.append(NetworkCapabilities.transportNameOf(t)).append(", "); } builder.append(String.format("%d events, ", eventCount)); builder.append(String.format("%d success, ", connectCount)); builder.append(String.format("%d blocking, ", connectBlockingCount)); builder.append(String.format("%d IPv6 dst", ipv6ConnectCount)); for (int i = 0; i < errnos.size(); i++) { String errno = OsConstants.errnoName(errnos.keyAt(i)); int count = errnos.valueAt(i); builder.append(String.format(", %s: %d", errno, count)); } return builder.append(")").toString(); }
Example #3
Source File: StrictJarFile.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
@Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { synchronized (this.fd) { final long length = endOffset - offset; if (byteCount > length) { byteCount = (int) length; } try { Os.lseek(fd, offset, OsConstants.SEEK_SET); } catch (ErrnoException e) { throw new IOException(e); } int count = IoBridge.read(fd, buffer, byteOffset, byteCount); if (count > 0) { offset += count; return count; } else { return -1; } } }
Example #4
Source File: ContextImpl.java From AndroidComponentPlugin with Apache License 2.0 | 6 votes |
/** * Common-path handling of app data dir creation */ private static File ensurePrivateDirExists(File file) { if (!file.exists()) { try { Os.mkdir(file.getAbsolutePath(), 0771); Os.chmod(file.getAbsolutePath(), 0771); } catch (ErrnoException e) { if (e.errno == OsConstants.EEXIST) { // We must have raced with someone; that's okay } else { Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage()); } } } return file; }
Example #5
Source File: SharedMemory.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Creates an mmap of the SharedMemory with the specified prot, offset, and length. This will * always produce a new ByteBuffer window to the backing shared memory region. Every call * to map() may be paired with a call to {@link #unmap(ByteBuffer)} when the ByteBuffer * returned by map() is no longer needed. * * @param prot A bitwise-or'd combination of PROT_READ, PROT_WRITE, PROT_EXEC, or PROT_NONE. * @param offset The offset into the shared memory to begin mapping. Must be >= 0 and less than * getSize(). * @param length The length of the region to map. Must be > 0 and offset + length must not * exceed getSize(). * @return A ByteBuffer mapping. * @throws ErrnoException if the mmap call failed. */ public @NonNull ByteBuffer map(int prot, int offset, int length) throws ErrnoException { checkOpen(); validateProt(prot); if (offset < 0) { throw new IllegalArgumentException("Offset must be >= 0"); } if (length <= 0) { throw new IllegalArgumentException("Length must be > 0"); } if (offset + length > mSize) { throw new IllegalArgumentException("offset + length must not exceed getSize()"); } long address = Os.mmap(0, length, prot, OsConstants.MAP_SHARED, mFileDescriptor, offset); boolean readOnly = (prot & OsConstants.PROT_WRITE) == 0; Runnable unmapper = new Unmapper(address, length, mMemoryRegistration.acquire()); return new DirectByteBuffer(length, address, mFileDescriptor, unmapper, readOnly); }
Example #6
Source File: Process.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Check to see if a thread belongs to a given process. This may require * more permissions than apps generally have. * @return true if this thread belongs to a process * @hide */ public static final boolean isThreadInProcess(int tid, int pid) { StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); try { if (Os.access("/proc/" + tid + "/task/" + pid, OsConstants.F_OK)) { return true; } else { return false; } } catch (Exception e) { return false; } finally { StrictMode.setThreadPolicy(oldPolicy); } }
Example #7
Source File: FileBridge.java From container with GNU General Public License v3.0 | 6 votes |
/** * java.io thinks that a read at EOF is an error and should return -1, contrary to traditional * Unix practice where you'd read until you got 0 bytes (and any future read would return -1). */ public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException { ArrayUtils.checkOffsetAndCount(bytes.length, byteOffset, byteCount); if (byteCount == 0) { return 0; } try { int readCount = Os.read(fd, bytes, byteOffset, byteCount); if (readCount == 0) { return -1; } return readCount; } catch (ErrnoException errnoException) { if (errnoException.errno == OsConstants.EAGAIN) { // We return 0 rather than throw if we try to read from an empty non-blocking pipe. return 0; } throw new IOException(errnoException); } }
Example #8
Source File: IpSecService.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * This function finds and forcibly binds to a random system port, ensuring that the port cannot * be unbound. * * <p>A socket cannot be un-bound from a port if it was bound to that port by number. To select * a random open port and then bind by number, this function creates a temp socket, binds to a * random port (specifying 0), gets that port number, and then uses is to bind the user's UDP * Encapsulation Socket forcibly, so that it cannot be un-bound by the user with the returned * FileHandle. * * <p>The loop in this function handles the inherent race window between un-binding to a port * and re-binding, during which the system could *technically* hand that port out to someone * else. */ private int bindToRandomPort(FileDescriptor sockFd) throws IOException { for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) { try { FileDescriptor probeSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); Os.bind(probeSocket, INADDR_ANY, 0); int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort(); Os.close(probeSocket); Log.v(TAG, "Binding to port " + port); Os.bind(sockFd, INADDR_ANY, port); return port; } catch (ErrnoException e) { // Someone miraculously claimed the port just after we closed probeSocket. if (e.errno == OsConstants.EADDRINUSE) { continue; } throw e.rethrowAsIOException(); } } throw new IOException("Failed " + MAX_PORT_BIND_ATTEMPTS + " attempts to bind to a port"); }
Example #9
Source File: OffloadController.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
private static int connectionTimeoutUpdateSecondsFor(int proto) { // TODO: Replace this with more thoughtful work, perhaps reading from // and maybe writing to any required // // /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_* // /proc/sys/net/netfilter/nf_conntrack_udp_timeout{,_stream} // // entries. TBD. if (proto == OsConstants.IPPROTO_TCP) { // Cf. /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established return 432000; } else { // Cf. /proc/sys/net/netfilter/nf_conntrack_udp_timeout_stream return 180; } }
Example #10
Source File: PinnerService.java From android_9.0.0_r45 with Apache License 2.0 | 6 votes |
/** * Close FD, swallowing irrelevant errors. */ private static void safeClose(@Nullable FileDescriptor fd) { if (fd != null && fd.valid()) { try { Os.close(fd); } catch (ErrnoException ex) { // Swallow the exception: non-EBADF errors in close(2) // indicate deferred paging write errors, which we // don't care about here. The underlying file // descriptor is always closed. if (ex.errno == OsConstants.EBADF) { throw new AssertionError(ex); } } } }
Example #11
Source File: DocumentMetadata.java From samba-documents-provider with GNU General Public License v3.0 | 6 votes |
public static DocumentMetadata fromUri(Uri uri, SmbClient client) throws IOException { final List<String> pathSegments = uri.getPathSegments(); if (pathSegments.isEmpty()) { throw new UnsupportedOperationException("Can't load metadata for workgroup or server."); } final StructStat stat = client.stat(uri.toString()); final DirectoryEntry entry = new DirectoryEntry( OsConstants.S_ISDIR(stat.st_mode) ? DirectoryEntry.DIR : DirectoryEntry.FILE, "", uri.getLastPathSegment()); final DocumentMetadata metadata = new DocumentMetadata(uri, entry); metadata.mStat.set(stat); return metadata; }
Example #12
Source File: IpSecManager.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private static void maybeHandleServiceSpecificException(ServiceSpecificException sse) { // OsConstants are late binding, so switch statements can't be used. if (sse.errorCode == OsConstants.EINVAL) { throw new IllegalArgumentException(sse); } else if (sse.errorCode == OsConstants.EAGAIN) { throw new IllegalStateException(sse); } else if (sse.errorCode == OsConstants.EOPNOTSUPP) { throw new UnsupportedOperationException(sse); } }
Example #13
Source File: TcpProvider.java From Daedalus with GNU General Public License v3.0 | 5 votes |
@Override protected void forwardPacket(DatagramPacket outPacket, IpPacket parsedPacket, AbstractDnsServer dnsServer) throws DaedalusVpnService.VpnNetworkException { Socket dnsSocket; try { // Packets to be sent to the real DNS server will need to be protected from the VPN dnsSocket = SocketChannel.open().socket(); service.protect(dnsSocket); SocketAddress address = new InetSocketAddress(outPacket.getAddress(), dnsServer.getPort()); dnsSocket.connect(address, 5000); dnsSocket.setSoTimeout(5000); Logger.info("TcpProvider: Sending DNS query request"); DataOutputStream dos = new DataOutputStream(dnsSocket.getOutputStream()); byte[] packet = processUdpPacket(outPacket, parsedPacket); dos.writeShort(packet.length); dos.write(packet); dos.flush(); if (parsedPacket != null) { dnsIn.add(new TcpProvider.WaitingOnSocketPacket(dnsSocket, parsedPacket)); } else { dnsSocket.close(); } } catch (IOException e) { if (e.getCause() instanceof ErrnoException) { ErrnoException errnoExc = (ErrnoException) e.getCause(); if ((errnoExc.errno == OsConstants.ENETUNREACH) || (errnoExc.errno == OsConstants.EPERM)) { throw new DaedalusVpnService.VpnNetworkException("Cannot send message:", e); } } Log.w(TAG, "handleDnsRequest: Could not send packet to upstream", e); } }
Example #14
Source File: BufferHolder.java From android-open-accessory-bridge with Apache License 2.0 | 5 votes |
private boolean ioExceptionIsNoSuchDevice(IOException ioException) { final Throwable cause = ioException.getCause(); if (cause instanceof ErrnoException) { final ErrnoException errnoException = (ErrnoException) cause; return errnoException.errno == OsConstants.ENODEV; } return false; }
Example #15
Source File: SysUtil.java From SoLoader with Apache License 2.0 | 5 votes |
@DoNotOptimize public static void fallocateIfSupported(FileDescriptor fd, long length) throws IOException { try { Os.posix_fallocate(fd, 0, length); } catch (ErrnoException ex) { if (ex.errno != OsConstants.EOPNOTSUPP && ex.errno != OsConstants.ENOSYS && ex.errno != OsConstants.EINVAL) { throw new IOException(ex.toString(), ex); } } }
Example #16
Source File: LocalSocketImpl.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public int available() throws IOException { FileDescriptor myFd = fd; if (myFd == null) throw new IOException("socket closed"); Int32Ref avail = new Int32Ref(0); try { Os.ioctlInt(myFd, OsConstants.FIONREAD, avail); } catch (ErrnoException e) { throw e.rethrowAsIOException(); } return avail.value; }
Example #17
Source File: LocalSocketImpl.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Wait until the data in sending queue is emptied. A polling version * for flush implementation. * @throws IOException * if an i/o error occurs. */ @Override public void flush() throws IOException { FileDescriptor myFd = fd; if (myFd == null) throw new IOException("socket closed"); // Loop until the output buffer is empty. Int32Ref pending = new Int32Ref(0); while (true) { try { // See linux/net/unix/af_unix.c Os.ioctlInt(myFd, OsConstants.TIOCOUTQ, pending); } catch (ErrnoException e) { throw e.rethrowAsIOException(); } if (pending.value <= 0) { // The output buffer is empty. break; } try { Thread.sleep(10); } catch (InterruptedException ie) { break; } } }
Example #18
Source File: LocalSocketImpl.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Creates a socket in the underlying OS. * * @param sockType either {@link LocalSocket#SOCKET_DGRAM}, {@link LocalSocket#SOCKET_STREAM} * or {@link LocalSocket#SOCKET_SEQPACKET} * @throws IOException */ public void create(int sockType) throws IOException { if (fd != null) { throw new IOException("LocalSocketImpl already has an fd"); } int osType; switch (sockType) { case LocalSocket.SOCKET_DGRAM: osType = OsConstants.SOCK_DGRAM; break; case LocalSocket.SOCKET_STREAM: osType = OsConstants.SOCK_STREAM; break; case LocalSocket.SOCKET_SEQPACKET: osType = OsConstants.SOCK_SEQPACKET; break; default: throw new IllegalStateException("unknown sockType"); } try { fd = Os.socket(OsConstants.AF_UNIX, osType, 0); mFdCreatedInternally = true; } catch (ErrnoException e) { e.rethrowAsIOException(); } }
Example #19
Source File: LocalSocketImpl.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Shuts down the input side of the socket. * * @throws IOException */ protected void shutdownInput() throws IOException { if (fd == null) { throw new IOException("socket not created"); } try { Os.shutdown(fd, OsConstants.SHUT_RD); } catch (ErrnoException e) { throw e.rethrowAsIOException(); } }
Example #20
Source File: LocalSocketImpl.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Shuts down the output side of the socket. * * @throws IOException */ protected void shutdownOutput() throws IOException { if (fd == null) { throw new IOException("socket not created"); } try { Os.shutdown(fd, OsConstants.SHUT_WR); } catch (ErrnoException e) { throw e.rethrowAsIOException(); } }
Example #21
Source File: LocalSocketImpl.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private static int javaSoToOsOpt(int optID) { switch (optID) { case SocketOptions.SO_SNDBUF: return OsConstants.SO_SNDBUF; case SocketOptions.SO_RCVBUF: return OsConstants.SO_RCVBUF; case SocketOptions.SO_REUSEADDR: return OsConstants.SO_REUSEADDR; default: throw new UnsupportedOperationException("Unknown option: " + optID); } }
Example #22
Source File: KeepalivePacketData.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
public static KeepalivePacketData nattKeepalivePacket( InetAddress srcAddress, int srcPort, InetAddress dstAddress, int dstPort) throws InvalidPacketException { if (!(srcAddress instanceof Inet4Address) || !(dstAddress instanceof Inet4Address)) { throw new InvalidPacketException(ERROR_INVALID_IP_ADDRESS); } if (dstPort != NATT_PORT) { throw new InvalidPacketException(ERROR_INVALID_PORT); } int length = IPV4_HEADER_LENGTH + UDP_HEADER_LENGTH + 1; ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) 0x4500); // IP version and TOS buf.putShort((short) length); buf.putInt(0); // ID, flags, offset buf.put((byte) 64); // TTL buf.put((byte) OsConstants.IPPROTO_UDP); int ipChecksumOffset = buf.position(); buf.putShort((short) 0); // IP checksum buf.put(srcAddress.getAddress()); buf.put(dstAddress.getAddress()); buf.putShort((short) srcPort); buf.putShort((short) dstPort); buf.putShort((short) (length - 20)); // UDP length int udpChecksumOffset = buf.position(); buf.putShort((short) 0); // UDP checksum buf.put((byte) 0xff); // NAT-T keepalive buf.putShort(ipChecksumOffset, IpUtils.ipChecksum(buf, 0)); buf.putShort(udpChecksumOffset, IpUtils.udpChecksum(buf, 0, IPV4_HEADER_LENGTH)); return new KeepalivePacketData(srcAddress, srcPort, dstAddress, dstPort, buf.array()); }
Example #23
Source File: DownloadUriOutputStream.java From okdownload with Apache License 2.0 | 5 votes |
@Override public void setLength(long newLength) { final String tag = "DownloadUriOutputStream"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { try { Os.posix_fallocate(pdf.getFileDescriptor(), 0, newLength); } catch (Throwable e) { if (e instanceof ErrnoException) { if (((ErrnoException) e).errno == OsConstants.ENOSYS || ((ErrnoException) e).errno == OsConstants.ENOTSUP) { Util.w(tag, "fallocate() not supported; falling back to ftruncate()"); try { Os.ftruncate(pdf.getFileDescriptor(), newLength); } catch (Throwable e1) { Util.w(tag, "It can't pre-allocate length(" + newLength + ") on the sdk" + " version(" + Build.VERSION.SDK_INT + "), because of " + e1); } } } else { Util.w(tag, "It can't pre-allocate length(" + newLength + ") on the sdk" + " version(" + Build.VERSION.SDK_INT + "), because of " + e); } } } else { Util.w(tag, "It can't pre-allocate length(" + newLength + ") on the sdk " + "version(" + Build.VERSION.SDK_INT + ")"); } }
Example #24
Source File: Sysconf.java From Battery-Metrics with MIT License | 5 votes |
@SuppressLint("ObsoleteSdkInt") public static long getScClkTck(long fallback) { long result = fallback; if (Build.VERSION.SDK_INT >= 21) { result = Os.sysconf(OsConstants._SC_CLK_TCK); } else if (Build.VERSION.SDK_INT >= 14) { result = fromLibcore("_SC_CLK_TCK", fallback); } return result > 0 ? result : fallback; }
Example #25
Source File: Sysconf.java From Battery-Metrics with MIT License | 5 votes |
@SuppressLint("ObsoleteSdkInt") public static long getScNProcessorsConf(long fallback) { if (Build.VERSION.SDK_INT >= 21) { return Os.sysconf(OsConstants._SC_NPROCESSORS_CONF); } else if (Build.VERSION.SDK_INT >= 14) { return fromLibcore("_SC_NPROCESSORS_CONF", fallback); } return fallback; }
Example #26
Source File: PackageInstallerSession.java From container with GNU General Public License v3.0 | 5 votes |
private ParcelFileDescriptor openWriteInternal(String name, long offsetBytes, long lengthBytes) throws IOException { // Quick sanity check of state, and allocate a pipe for ourselves. We // then do heavy disk allocation outside the lock, but this open pipe // will block any attempted install transitions. final FileBridge bridge; synchronized (mLock) { assertPreparedAndNotSealed("openWrite"); bridge = new FileBridge(); mBridges.add(bridge); } try { final File target = new File(resolveStageDir(), name); // TODO: this should delegate to DCS so the system process avoids // holding open FDs into containers. final FileDescriptor targetFd = Os.open(target.getAbsolutePath(), O_CREAT | O_WRONLY, 0644); // If caller specified a total length, allocate it for them. Free up // cache space to grow, if needed. if (lengthBytes > 0) { Os.posix_fallocate(targetFd, 0, lengthBytes); } if (offsetBytes > 0) { Os.lseek(targetFd, offsetBytes, OsConstants.SEEK_SET); } bridge.setTargetFile(targetFd); bridge.start(); return ParcelFileDescriptor.dup(bridge.getClientSocket()); } catch (ErrnoException e) { throw new IOException(e); } }
Example #27
Source File: SambaProxyFileCallback.java From samba-documents-provider with GNU General Public License v3.0 | 5 votes |
private void throwErrnoException(IOException e) throws ErrnoException { // Hack around that SambaProxyFileCallback throws ErrnoException rather than IOException // assuming the underlying cause is an ErrnoException. if (e.getCause() instanceof ErrnoException) { throw (ErrnoException) e.getCause(); } else { throw new ErrnoException("I/O", OsConstants.EIO, e); } }
Example #28
Source File: UserDataPreparer.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Set serial number stored in user directory inode. * * @throws IOException if serial number was already set */ private static void setSerialNumber(File file, int serialNumber) throws IOException { try { final byte[] buf = Integer.toString(serialNumber).getBytes(StandardCharsets.UTF_8); Os.setxattr(file.getAbsolutePath(), XATTR_SERIAL, buf, OsConstants.XATTR_CREATE); } catch (ErrnoException e) { throw e.rethrowAsIOException(); } }
Example #29
Source File: ZygoteInit.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
/** * Gets the bit array representation of the provided list of POSIX capabilities. */ private static long posixCapabilitiesAsBits(int... capabilities) { long result = 0; for (int capability : capabilities) { if ((capability < 0) || (capability > OsConstants.CAP_LAST_CAP)) { throw new IllegalArgumentException(String.valueOf(capability)); } result |= (1L << capability); } return result; }
Example #30
Source File: OffloadHardwareInterface.java From android_9.0.0_r45 with Apache License 2.0 | 5 votes |
private static int networkProtocolToOsConstant(int proto) { switch (proto) { case NetworkProtocol.TCP: return OsConstants.IPPROTO_TCP; case NetworkProtocol.UDP: return OsConstants.IPPROTO_UDP; default: // The caller checks this value and will log an error. Just make // sure it won't collide with valid OsContants.IPPROTO_* values. return -Math.abs(proto); } }