JNIEXPORT jint JNICALL Java_com_codeminders_hidapi_HIDDevice_readTimeout (JNIEnv *env, jobject self, jbyteArray data, jint milliseconds ) { hid_device *peer = getPeer(env, self); if(!peer) { throwIOException(env, peer); return 0; /* not an error, freed previously */ } jsize bufsize = env->GetArrayLength(data); jbyte *buf = env->GetByteArrayElements(data, NULL); int read = hid_read_timeout(peer, (unsigned char*) buf, bufsize, milliseconds); env->ReleaseByteArrayElements(data, buf, read==-1?JNI_ABORT:0); if(read == 0) /* time out */ { return 0; } else if(read == -1) { throwIOException(env, peer); return 0; /* not an error, freed previously */ } return read; }
jint android_security_cts_LinuxRngTest_getCharDeviceMinor(JNIEnv* env, jobject thiz, jstring name) { const char* nameStr = env->GetStringUTFChars(name, NULL); jint result = -1; struct stat st; if (stat(nameStr, &st) == -1) { throwIOException(env, "Failed to stat %s: %s", nameStr, strerror(errno)); goto ret; } if (!S_ISCHR(st.st_mode)) { throwIOException(env, "%s is not a character device: mode is 0%o", nameStr, st.st_mode); goto ret; } result = minor(st.st_rdev); ret: if (nameStr != NULL) { env->ReleaseStringUTFChars(name, nameStr); } return result; }
JNIEXPORT jstring FUNC(getPortName)(JNIEnv *env, jclass cls, jint i) { HKEY key; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_READ, &key) != ERROR_SUCCESS) { throwIOException(env, "Can not find registry key"); return NULL; } wchar_t name[256]; DWORD len = sizeof(name); LONG rc = RegEnumValue(key, (DWORD)i, name, &len, NULL, NULL, NULL, NULL); if (rc != ERROR_SUCCESS) { if (rc != ERROR_NO_MORE_ITEMS) { throwIOException(env, "Can not enum value"); } RegCloseKey(key); return NULL; } wchar_t value[256]; DWORD type; len = sizeof(value); if (RegQueryValueEx(key, name, NULL, &type, (BYTE *)value, &len) != ERROR_SUCCESS) { throwIOException(env, "Can not query value"); RegCloseKey(key); return NULL; } jstring result = env->NewString((jchar *)value, (jsize) wcslen(value)); RegCloseKey(key); return result; }
/* * Class: com_pi4j_jni_Serial * Method: echo * Signature: (IZ)V */ JNIEXPORT void JNICALL Java_com_pi4j_jni_Serial_echo (JNIEnv *env, jclass obj, jint fd, jboolean enabled) { struct termios options ; // get and modify current options: if(tcgetattr (fd, &options) == -1){ int err_number = errno; char err_message[100]; sprintf(err_message, "Failed to GET terminal attributes for the serial port. (Error #%d)", err_number); throwIOException(env, err_message); } if(enabled == JNI_FALSE){ // disable ECHO options.c_lflag &= ~ECHO; } else{ // enable ECHO options.c_lflag |= ECHO; } // set updated options if(tcsetattr (fd, TCSANOW, &options) == -1){ int err_number = errno; char err_message[100]; sprintf(err_message, "Failed to SET terminal attributes for the serial port. (Error #%d)", err_number); throwIOException(env, err_message); } }
JNIEXPORT void JNICALL FUNC(write0)(JNIEnv *env, jobject jobj, jlong jhandle, jint b) { OVERLAPPED olp = { 0 }; olp.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (olp.hEvent == NULL) { throwIOException(env, "Error creating event"); return; } char buff = (char)b; DWORD nwritten; HANDLE handle = (HANDLE)jhandle; if (!WriteFile(handle, &buff, sizeof(buff), &nwritten, &olp)) { if (GetLastError() != ERROR_IO_PENDING) { throwIOException(env, "Error writing to port"); } else { switch (WaitForSingleObject(olp.hEvent, INFINITE)) { case WAIT_OBJECT_0: if (!GetOverlappedResult(handle, &olp, &nwritten, FALSE)) { throwIOException(env, "Error waiting for write"); } } } } CloseHandle(olp.hEvent); }
JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackBlueZ_l2Ready (JNIEnv* env, jobject peer, jlong handle) { struct pollfd fds; int timeout = 10; // milliseconds memset(&fds, 0, sizeof(fds)); fds.fd = handle; fds.events = POLLIN | POLLHUP | POLLERR;// | POLLRDHUP; fds.revents = 0; int poll_rc = poll(&fds, 1, timeout); if (poll_rc > 0) { if (fds.revents & (POLLHUP | POLLERR /*| POLLRDHUP*/)) { throwIOException(env, "Peer closed connection"); return JNI_FALSE; } else if (fds.revents & POLLNVAL) { // this connection has been closed by invoking the close() method. throwIOException(env, "Connection closed"); return JNI_FALSE; } else if (fds.revents & POLLIN) { return JNI_TRUE; } } else if (poll_rc == -1) { throwIOException(env, "Failed to read. [%d] %s", errno, strerror(errno)); return JNI_FALSE; } else { //Edebug("poll: call timed out"); } return JNI_FALSE; }
JNIEXPORT void JNICALL Java_org_apache_activemq_artemis_jlibaio_LibaioContext_fill (JNIEnv * env, jclass clazz, jint fd, jlong size) { int i; int blocks = size / ONE_MEGA; int rest = size % ONE_MEGA; #ifdef DEBUG fprintf (stderr, "blocks = %d, rest=%d\n", blocks, rest); #endif lseek (fd, 0, SEEK_SET); for (i = 0; i < blocks; i++) { if (write(fd, oneMegaBuffer, ONE_MEGA) < 0) { throwIOException(env, "Cannot initialize file"); return; } } if (rest != 0l) { if (write(fd, oneMegaBuffer, rest) < 0) { throwIOException(env, "Cannot initialize file"); return; } } lseek (fd, 0, SEEK_SET); }
void RandomAccessFile_setLength (JNIEnv *env, w_instance thisRAF, w_long newlen) { w_instance fd_obj; vfs_FILE *file; fd_obj = getReferenceField(thisRAF, F_RandomAccessFile_fd); file = getWotsitField(fd_obj, F_FileDescriptor_fd); if(file == NULL) { throwNullPointerException(JNIEnv2w_thread(env)); } else { char *pathname; w_long oldptr; pathname = getFDName(fd_obj); oldptr = vfs_ftell(file); if(vfs_truncate(pathname, newlen) == -1) { throwIOException(JNIEnv2w_thread(env)); } freeFDName(pathname); if(newlen < oldptr && vfs_fseek(file, newlen, SEEK_SET) == -1) { throwIOException(JNIEnv2w_thread(env)); } } }
static int create_subprocess(JNIEnv *env, const char *cmd, char *const argv[], char *const envp[], int masterFd) { // same size as Android 1.6 libc/unistd/ptsname_r.c char devname[64]; pid_t pid; fcntl(masterFd, F_SETFD, FD_CLOEXEC); // grantpt is unnecessary, because we already assume devpts by using /dev/ptmx if(unlockpt(masterFd)){ throwIOException(env, errno, "trouble with /dev/ptmx"); return -1; } memset(devname, 0, sizeof(devname)); // Early (Android 1.6) bionic versions of ptsname_r had a bug where they returned the buffer // instead of 0 on success. A compatible way of telling whether ptsname_r // succeeded is to zero out errno and check it after the call errno = 0; int ptsResult = ptsname_r(masterFd, devname, sizeof(devname)); if (ptsResult && errno) { throwIOException(env, errno, "ptsname_r returned error"); return -1; } pid = fork(); if(pid < 0) { throwIOException(env, errno, "fork failed"); return -1; } if(pid == 0){ int pts; setsid(); pts = open(devname, O_RDWR); if(pts < 0) exit(-1); ioctl(pts, TIOCSCTTY, 0); dup2(pts, 0); dup2(pts, 1); dup2(pts, 2); closeNonstandardFileDescriptors(); if (envp) { for (; *envp; ++envp) { putenv(*envp); } } execv(cmd, argv); exit(-1); } else { return (int) pid; } }
extern "C" JNIEXPORT void JNICALL Java_java_nio_channels_SocketChannel_natThrowWriteError(JNIEnv *e, jclass, jint socket) { int error; socklen_t size = sizeof(int); int r = getsockopt(socket, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &size); if (r != 0 or size != sizeof(int)) { throwIOException(e); } else if (error != 0) { throwIOException(e, socketErrorString(e, error)); } }
w_int RandomAccessFile_skipBytes (JNIEnv *env, w_instance thisRAF, w_int n) { w_thread thread = JNIEnv2w_thread(env); w_instance fd_obj; vfs_FILE *file; w_long result = 0; w_long prev_pos; fd_obj = getReferenceField(thisRAF, F_RandomAccessFile_fd); file = getWotsitField(fd_obj, F_FileDescriptor_fd); if (file == NULL) { throwNullPointerException(thread); } else { struct vfs_STAT statbuf; w_long size = 0; if(statFD(fd_obj, &statbuf)) { size = statbuf.st_size; } else { throwIOException(thread); return -1; } prev_pos = vfs_ftell(file); if (prev_pos < 0) { throwIOException(thread); return -1; } if(n > (size - prev_pos)) { n = size - prev_pos; } result = vfs_fseek(file, (long)n, SEEK_CUR); if (result < 0) { throwIOException(thread); return -1; } result = vfs_ftell(file) - prev_pos; if (result < 0) { throwIOException(thread); } } return result; }
jint read0(JNIEnv * env, jclass clazz, jint fd, void *buffer, jint pos, jint limit) { ssize_t res; int err; do { res = read(fd, buffer + pos, (size_t) (limit - pos)); // Keep on reading if we was interrupted } while (res == -1 && ((err = errno) == EINTR)); if (res < 0) { if (err == EAGAIN || err == EWOULDBLOCK) { // Nothing left to read return 0; } if (err == EBADF) { throwClosedChannelException(env); return -1; } throwIOException(env, exceptionMessage("Error while read(...): ", err)); return -1; } if (res == 0) { // end-of-stream return -1; } return (jint) res; }
JNIEXPORT jstring JNICALL Java_com_codeminders_hidapi_HIDDevice_getIndexedString (JNIEnv *env, jobject self, jint index) { hid_device *peer = getPeer(env, self); if(!peer) { throwIOException(env, peer); return NULL; /* not an error, freed previously */ } wchar_t data[MAX_BUFFER_SIZE]; int res = hid_get_indexed_string(peer, index, data, MAX_BUFFER_SIZE); if(res < 0) { /* We decided not to treat this as an error, but return an empty string in this case throwIOException(env, peer); return NULL; */ data[0] = 0; } char *u8 = convertToUTF8(env, data); jstring string = env->NewStringUTF(u8); free(u8); return string; }
jint sendTo0(JNIEnv * env, jint fd, void* buffer, jint pos, jint limit ,jbyteArray address, jint scopeId, jint port) { struct sockaddr_storage addr; init_sockaddr(env, address, scopeId, port, &addr); ssize_t res; int err; do { res = sendto(fd, buffer + pos, (size_t) (limit - pos), 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_storage)); // keep on writing if it was interrupted } while(res == -1 && ((err = errno) == EINTR)); if (res < 0) { // network stack saturated... try again later if (err == EAGAIN || err == EWOULDBLOCK) { return 0; } if (err == EBADF) { throwClosedChannelException(env); return -1; } throwIOException(env, exceptionMessage("Error while sendto(...): ", err)); return -1; } return (jint) res; }
JNIEXPORT void JNICALL Java_net_java_games_input_LinuxEventDevice_nEraseEffect(JNIEnv *env, jclass unused, jlong fd_address, jint ff_id) { int fd = (int)fd_address; int ff_id_int = ff_id; if (ioctl(fd, EVIOCRMFF, &ff_id_int) == -1) throwIOException(env, "Failed to erase effect (%d)\n", errno); }
/* * Class: com_pi4j_jni_Serial * Method: setDTR * Signature: (IZ)V */ JNIEXPORT void JNICALL Java_com_pi4j_jni_Serial_setDTR (JNIEnv *env, jclass obj, jint fd, jboolean enabled) { int status = 0; int ret; status |= TIOCM_DTR; if(enabled == JNI_FALSE) { ret = ioctl(fd, TIOCMBIC, &status); } else { ret = ioctl(fd, TIOCMBIS, &status); } // raise IOException if failed if(ret != 0) { int err_number = errno; char err_message[100]; sprintf(err_message, "Failed to set DTR pin state. (Error #%d)", err_number); throwIOException(env, err_message); } }
JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackBlueZ_l2Send (JNIEnv* env, jobject peer, jlong handle, jbyteArray data, jint transmitMTU) { #ifdef BLUECOVE_L2CAP_MTU_TRUNCATE struct l2cap_options opt; if (!l2Get_options(env, handle, &opt)) { return; } #endif //BLUECOVE_L2CAP_MTU_TRUNCATE if (data == NULL) { throwRuntimeException(env, "Invalid argument"); return; } jbyte *bytes = (*env)->GetByteArrayElements(env, data, 0); if (bytes == NULL) { throwRuntimeException(env, "Invalid argument"); return; } int len = (int)(*env)->GetArrayLength(env, data); if (len > transmitMTU) { len = transmitMTU; } #ifdef BLUECOVE_L2CAP_MTU_TRUNCATE if (len > opt.omtu) { len = opt.omtu; } #endif //BLUECOVE_L2CAP_MTU_TRUNCATE int count = send(handle, (char *)bytes, len, 0); if (count < 0) { throwIOException(env, "Failed to write. [%d] %s", errno, strerror(errno)); } (*env)->ReleaseByteArrayElements(env, data, bytes, 0); }
/* * Class: com_pi4j_jni_Serial * Method: setBreak * Signature: (IZ)V */ JNIEXPORT void JNICALL Java_com_pi4j_jni_Serial_setBreak (JNIEnv *env, jclass obj, jint fd, jboolean enabled) { if(enabled == JNI_FALSE) { printf("SERIAL SET BREAK - FALSE\n"); if(ioctl(fd, TIOCCBRK, NULL) == 0) { printf("SERIAL SET BREAK - SUCCESS\n"); return; } } else { printf("SERIAL SET BREAK - TRUE\n"); if(ioctl(fd, TIOCSBRK, NULL) == 0) { printf("SERIAL SET BREAK - SUCCESS\n"); return; } } printf("SERIAL SET BREAK - ERROR\n"); // raise IOException if failed int err_number = errno; char err_message[100]; sprintf(err_message, "Failed to set RTS pin state. (Error #%d)", err_number); throwIOException(env, err_message); }
jobject recvFrom0(JNIEnv * env, jint fd, void* buffer, jint pos, jint limit) { struct sockaddr_storage addr; socklen_t addrlen = sizeof(addr); ssize_t res; int err; do { res = recvfrom(fd, buffer + pos, (size_t) (limit - pos), 0, (struct sockaddr *)&addr, &addrlen); // Keep on reading if we was interrupted } while (res == -1 && ((err = errno) == EINTR)); if (res < 0) { if (err == EAGAIN || err == EWOULDBLOCK) { // Nothing left to read return NULL; } if (err == EBADF) { throwClosedChannelException(env); return NULL; } throwIOException(env, exceptionMessage("Error while recvFrom(...): ", err)); return NULL; } return createDatagramSocketAddress(env, addr, res); }
JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackBlueZDBus_connectionRfWrite__J_3BII (JNIEnv* env, jobject peer, jlong handle, jbyteArray b, jint off, jint len) { if (b == NULL) { throwRuntimeException(env, "Invalid argument"); return; } jbyte *bytes = (*env)->GetByteArrayElements(env, b, 0); if (bytes == NULL) { throwRuntimeException(env, "Invalid argument"); return; } int done = 0; while(done < len) { int count = send(handle, (char *)(bytes + off + done), len - done, 0); if (count < 0) { throwIOException(env, "Failed to write. [%d] %s", errno, strerror(errno)); break; } if (isCurrentThreadInterrupted(env, peer)) { break; } done += count; } (*env)->ReleaseByteArrayElements(env, b, bytes, 0); }
JNIEXPORT void JNICALL Java_com_codeminders_hidapi_HIDDevice_disableBlocking (JNIEnv *env, jobject self) { hid_device *peer = getPeer(env, self); if(!peer) { throwIOException(env, peer); return; /* not an error, freed previously */ } int res = hid_set_nonblocking(peer, 1); if(res!=0) { throwIOException(env, peer); return; /* not an error, freed previously */ } }
JNIEXPORT void JNICALL Java_org_apache_activemq_artemis_jlibaio_LibaioContext_submitWrite (JNIEnv * env, jclass clazz, jint fileHandle, jobject contextPointer, jlong position, jint size, jobject bufferWrite, jobject callback) { struct io_control * theControl = getIOControl(env, contextPointer); if (theControl == NULL) { return; } #ifdef DEBUG fprintf (stdout, "submitWrite position %ld, size %d\n", position, size); #endif struct iocb * iocb = getIOCB(theControl); if (iocb == NULL) { throwIOException(env, "Not enough space in libaio queue"); return; } io_prep_pwrite(iocb, fileHandle, getBuffer(env, bufferWrite), (size_t)size, position); // The GlobalRef will be deleted when poll is called. this is done so // the vm wouldn't crash if the Callback passed by the user is GCed between submission // and callback. // also as the real intention is to hold the reference until the life cycle is complete iocb->data = (void *) (*env)->NewGlobalRef(env, callback); submit(env, theControl, iocb); }
JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackBlueZDBus_connectionRfWrite__JI (JNIEnv* env, jobject peer, jlong handle, jint b) { char c = (char)b; if (send(handle, &c, 1, 0) != 1) { throwIOException(env, "Failed to write. [%d] %s", errno, strerror(errno)); } }
/* * Class: com_pi4j_jni_Serial * Method: read * Signature: (II)[B */ JNIEXPORT jbyteArray JNICALL Java_com_pi4j_jni_Serial_read__II (JNIEnv *env, jclass obj, jint fd, jint length) { // determine result data array length from the number of bytes available on the receive buffer int availableBytes; availableBytes = getAvailableByteCount(fd); // check for error return; if error, then return NULL if (availableBytes < 0){ int err_number = errno; char err_message[100]; sprintf(err_message, "Error attempting to read data from serial port. (Error #%d)", err_number); throwIOException(env, err_message); return (*env)->NewByteArray(env, 0); // ERROR READING RX BUFFER } // reduce length if it exceeds the number available if(length > availableBytes){ length = availableBytes; } // create a new payload result byte array jbyte result[length]; // copy the data bytes from the serial receive buffer into the payload result int i; for (i = 0; i < length; i++) { // read a single byte from the RX buffer uint8_t x ; if (read (fd, &x, 1) != 1){ int err_number = errno; char err_message[100]; sprintf(err_message, "Failed to read data from serial port. (Error #%d)", err_number); throwIOException(env, err_message); return (*env)->NewByteArray(env, 0); // ERROR READING RX BUFFER } // assign the single byte; cast to unsigned char result[i] = (unsigned char)(((int)x) & 0xFF); } // create a java array object and copy the raw payload bytes jbyteArray javaResult = (*env)->NewByteArray(env, length); (*env)->SetByteArrayRegion(env, javaResult, 0, length, result); return javaResult; }
bool l2Get_options(JNIEnv* env, jlong handle, struct l2cap_options* opt) { socklen_t opt_len = sizeof(*opt); if (getsockopt(handle, SOL_L2CAP, L2CAP_OPTIONS, opt, &opt_len) < 0) { throwIOException(env, "Failed to get L2CAP link mtu. [%d] %s", errno, strerror(errno)); return false; } return true; }
JNIEXPORT jint JNICALL Java_net_java_games_input_LinuxEventDevice_nGrab(JNIEnv *env, jclass unused, jlong fd_address, jint do_grab) { int fd = (int)fd_address; int grab = (int)do_grab; if (ioctl(fd,EVIOCGRAB,grab) == -1){ throwIOException(env, "Failed to grab device (%d)\n", errno); return -1; } return 1; }
JNIEXPORT jint JNICALL Java_net_java_games_input_LinuxEventDevice_nGetNumEffects(JNIEnv *env, jclass unused, jlong fd_address) { int fd = (int)fd_address; int num_effects; if (ioctl(fd, EVIOCGEFFECTS, &num_effects) == -1) { throwIOException(env, "Failed to get number of device effects (%d)\n", errno); return -1; } return num_effects; }
JNIEXPORT jint JNICALL Java_net_java_games_input_LinuxEventDevice_nGetVersion(JNIEnv *env, jclass unused, jlong fd_address) { int fd = (int)fd_address; int version; if (ioctl(fd, EVIOCGVERSION, &version) == -1) { throwIOException(env, "Failed to get device version (%d)\n", errno); return -1; } return version; }
JNIEXPORT void JNICALL Java_io_netty_channel_epoll_Native_bind(JNIEnv * env, jclass clazz, jint fd, jbyteArray address, jint scopeId, jint port) { struct sockaddr_storage addr; init_sockaddr(env, address, scopeId, port, &addr); if(bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1){ int err = errno; throwIOException(env, exceptionMessage("Error during bind(...): ", err)); } }
/* * Class: com_pi4j_jni_Serial * Method: readToBuffer * Signature: (IOI)I */ JNIEXPORT jint JNICALL Java_com_pi4j_jni_Serial_readToBuffer (JNIEnv *env, jclass obj, jint fd, jobject buffer, jint length) { // determine result data array length from the number of bytes available on the receive buffer int availableBytes; availableBytes = getAvailableByteCount(fd); // check for error return; if error, then return NULL if (availableBytes < 0){ int err_number = errno; char err_message[100]; sprintf(err_message, "Error attempting to read data from serial port. (Error #%d)", err_number); throwIOException(env, err_message); return -1; // ERROR READING RX BUFFER } // reduce length if it exceeds the number available if(length > availableBytes){ length = availableBytes; } jbyte *result = (*env)->GetDirectBufferAddress(env, buffer); // copy the data bytes from the serial receive buffer into the payload result int i; for (i = 0; i < length; i++) { // read a single byte from the RX buffer uint8_t x ; if (read (fd, &x, 1) != 1){ int err_number = errno; char err_message[100]; sprintf(err_message, "Failed to read data from serial port. (Error #%d)", err_number); throwIOException(env, err_message); return -1; // ERROR READING RX BUFFER } // assign the single byte; cast to unsigned char result[i] = (unsigned char)(((int)x) & 0xFF); } // return number of bytes written into buffer return length; }