protected void setBinaries(Map<CLDevice, byte[]> binaries) { if (this.devices == null) { this.devices = new CLDevice[binaries.size()]; int iDevice = 0; for (CLDevice device : binaries.keySet()) this.devices[iDevice++] = device; } int nDevices = this.devices.length; NativeSize[] lengths = new NativeSize[nDevices]; cl_device_id[] deviceIds = new cl_device_id[nDevices]; Memory binariesArray = new Memory(Pointer.SIZE * nDevices); Memory[] binariesMems = new Memory[nDevices]; for (int iDevice = 0; iDevice < nDevices; iDevice++) { CLDevice device = devices[iDevice]; byte[] binary = binaries.get(device); Memory binaryMem = binariesMems[iDevice] = new Memory(binary.length); binaryMem.write(0, binary, 0, binary.length); binariesArray.setPointer(iDevice * Pointer.SIZE, binaryMem); lengths[iDevice] = toNS(binary.length); deviceIds[iDevice] = device.getEntity(); } PointerByReference binariesPtr = new PointerByReference(); binariesPtr.setPointer(binariesArray); IntBuffer errBuff = NIOUtils.directInts(1, ByteOrder.nativeOrder()); int previousAttempts = 0; IntBuffer statuses = NIOUtils.directInts(nDevices, ByteOrder.nativeOrder()); do { entity = CL.clCreateProgramWithBinary( context.getEntity(), nDevices, deviceIds, lengths, binariesPtr, statuses, errBuff); } while (failedForLackOfMemory(errBuff.get(0), previousAttempts++)); }
public synchronized void fail() throws Fail { int err = GetLastError(); Memory buffer = new Memory(2048); int res = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, null, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buffer, (int) buffer.size(), null); log = log && log( 1, "fail() %s, Windows GetLastError()= %d, %s\n", lineno(1), err, buffer.getString(0, true)); // FIXME here convert from Windows error code to 'posix' error code Fail f = new Fail(); throw f; }
public static File getTempDir() { Memory buf = new Memory(1024); if (Kernel32.INSTANCE.GetTempPathW(1024, buf) != 0) { return new File(buf.getString(0, true)); } else { return null; } }
private Memory toPointer(String input) { byte[] data = Native.toByteArray(input); Memory pointer = new Memory(data.length + 1); pointer.write(0, data, 0, data.length); pointer.setByte(data.length, (byte) 0); return pointer; }
/** * converts a string to a pointer * * @param string * @return pointer to a copy of the string */ private Pointer str(String string) { if (string == null) { return null; } Memory mem = new Memory(string.length() + 1); mem.setString(0, string); return mem; }
/** * String representation of the buffer. * * @return Unicode string. */ public String getString() { byte[] data = Buffer.getByteArray(0, Length); if (data.length < 2 || data[data.length - 1] != 0) { Memory newdata = new Memory(data.length + 2); newdata.write(0, data, 0, data.length); return newdata.getString(0, true); } return Buffer.getString(0, true); }
@Override public synchronized int onEvent( int evtSubscribeNotifyAction, WinDef.PVOID userContext, WinNT.HANDLE eventHandle) { if (logger.isDebugEnabled()) { logger.debug("onEvent(" + evtSubscribeNotifyAction + ", " + userContext + ", " + eventHandle); } if (evtSubscribeNotifyAction == WEvtApi.EvtSubscribeNotifyAction.ERROR) { if (eventHandle.getPointer().getInt(0) == WEvtApi.EvtSubscribeErrors.ERROR_EVT_QUERY_RESULT_STALE) { logger.error(MISSING_EVENT_MESSAGE); } else { logger.error(RECEIVED_THE_FOLLOWING_WIN32_ERROR + eventHandle.getPointer().getInt(0)); } } else if (evtSubscribeNotifyAction == WEvtApi.EvtSubscribeNotifyAction.DELIVER) { wEvtApi.EvtRender( null, eventHandle, WEvtApi.EvtRenderFlags.EVENT_XML, size, buffer, used, propertyCount); // Not enough room in buffer, resize so it's big enough if (kernel32.GetLastError() == W32Errors.ERROR_INSUFFICIENT_BUFFER) { int newMaxSize = used.getInt(0); // Check for overflow or too big if (newMaxSize < size || newMaxSize > maxBufferSize) { logger.error( "Dropping event " + eventHandle + " because it couldn't be rendered within " + maxBufferSize + " bytes."); // Ignored, see // https://msdn.microsoft.com/en-us/library/windows/desktop/aa385577(v=vs.85).aspx return 0; } size = newMaxSize; buffer = new Memory(size); wEvtApi.EvtRender( null, eventHandle, WEvtApi.EvtRenderFlags.EVENT_XML, size, buffer, used, propertyCount); } int lastError = kernel32.GetLastError(); if (lastError == W32Errors.ERROR_SUCCESS) { int usedBytes = used.getInt(0); String string = Charsets.UTF_16LE.decode(buffer.getByteBuffer(0, usedBytes)).toString(); if (string.endsWith("\u0000")) { string = string.substring(0, string.length() - 1); } consumer.accept(string); } else { logger.error( EVT_RENDER_RETURNED_THE_FOLLOWING_ERROR_CODE + errorLookup.getLastError() + "."); } } // Ignored, see https://msdn.microsoft.com/en-us/library/windows/desktop/aa385577(v=vs.85).aspx return 0; }
@Override public void display( DirectMediaPlayer mediaPlayer, Memory[] nativeBuffers, BufferFormat bufferFormat) { Memory nativeBuffer = nativeBuffers[0]; ByteBuffer byteBuffer = nativeBuffer.getByteBuffer(0, nativeBuffer.size()); pixelWriter.setPixels( 0, 0, bufferFormat.getWidth(), bufferFormat.getHeight(), pixelFormat, byteBuffer, bufferFormat.getPitches()[0]); }
public SockFProg(SockFilter filters[]) { len = (short) filters.length; // serialize struct sock_filter * explicitly, its less confusing than the JNA magic we would // need Memory filter = new Memory(len * 8); ByteBuffer bbuf = filter.getByteBuffer(0, len * 8); bbuf.order(ByteOrder.nativeOrder()); // little endian for (SockFilter f : filters) { bbuf.putShort(f.code); bbuf.put(f.jt); bbuf.put(f.jf); bbuf.putInt(f.k); } this.filter = filter; }
private void writeNative(byte[] bs) throws SerialPortException { Memory mem = new Memory(Byte.SIZE * bs.length + 1); mem.clear(); PointerByReference inipar = new PointerByReference(); inipar.setPointer(mem); for (int i = 0; i < bs.length; i++) { inipar.getPointer().setByte(i * Byte.SIZE / 8, bs[i]); } byte c = '\n'; inipar.getPointer().setByte((bs.length + 1) * Byte.SIZE / 8, c); int rt = NativeLoader.getInstance().serialport_write(getFd(), inipar); if (rt != 0) { logger.error("Warning fail to write store " + bs.length); throw new SerialPortException("The serial port is closed " + getFd()); } }
/** * Get the binaries of the program (one for each device, in order) * * @return map from each device the program was compiled for to the corresponding binary data */ public Map<CLDevice, byte[]> getBinaries() throws CLBuildException { synchronized (this) { if (!built) build(); } Memory s = infos.getMemory(getEntity(), CL_PROGRAM_BINARY_SIZES); int n = (int) s.getSize() / Native.SIZE_T_SIZE; NativeSize[] sizes = readNSArray(s, n); // int[] sizes = new int[n]; // for (int i = 0; i < n; i++) { // sizes[i] = s.getNativeLong(i * Native.LONG_SIZE).intValue(); // } Memory[] binMems = new Memory[n]; Memory ptrs = new Memory(n * Native.POINTER_SIZE); for (int i = 0; i < n; i++) { ptrs.setPointer(i * Native.POINTER_SIZE, binMems[i] = new Memory(sizes[i].intValue())); } error( infos.getInfo( getEntity(), CL_PROGRAM_BINARIES, toNS(ptrs.getSize() * Native.POINTER_SIZE), ptrs, null)); Map<CLDevice, byte[]> ret = new HashMap<CLDevice, byte[]>(devices.length); int iBin = n == devices.length + 1 ? 1 : 0; for (int i = 0; i < n; i++) { CLDevice device = devices[i]; Memory bytes = binMems[iBin + i]; if (bytes != null) ret.put(device, bytes.getByteArray(0, sizes[iBin + i].intValue())); } return ret; }
// https://github.com/twall/jna/issues/53 public String hack(Memory m) { String str = ""; for (int i = 0; i < m.size(); i += 2) { byte b1 = m.getByte(i + 0); byte b2 = m.getByte(i + 1); String s; try { s = new String(new byte[] {-2, -1, b2, b1}, "UTF-16"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } str += s; } return str; }
protected static void write(int level, String message, UnixSyslogConfig config) throws SyslogRuntimeException { synchronized (libraryInstance) { if (currentFacility != config.getFacility()) { if (openlogCalled) { libraryInstance.closelog(); openlogCalled = false; } currentFacility = config.getFacility(); } if (!openlogCalled) { String ident = config.getIdent(); if (ident != null && "".equals(ident.trim())) { ident = null; } Memory identBuffer = ident == null ? null : (Memory) identMap.get(ident); if (ident != null && identBuffer == null) { identBuffer = new Memory(128); identBuffer.setString(0, ident, false); identMap.put(ident, identBuffer); } libraryInstance.openlog(identBuffer, config.getOption(), currentFacility); openlogCalled = true; } int priority = currentFacility | level; libraryInstance.syslog(priority, "%s", message); } }
// TODO: this method isn't very safe to leave public, perhaps some // setPropertyData[String/UInt32/etc.] methods would be better // hansi: i like having as much as possible public. it's nice for people who know what they're // doing. @SuppressWarnings("unchecked") public static <T> T getPropertyDataAdvanced( final EdsBaseRef ref, final EdsPropertyID property, final long param) throws IllegalArgumentException, IllegalStateException { final int size = (int) CanonUtils.getPropertySize(ref, property, param); final EdsDataType type = CanonUtils.getPropertyType(ref, property, param); final Memory memory = new Memory(size > 0 ? size : 1); final EdsError err = CanonUtils.getPropertyData(ref, property, param, size, memory); if (err == EdsError.EDS_ERR_OK) { switch (type) { case kEdsDataType_Unknown: // Unknown return null; case kEdsDataType_String: // EdsChar[] return (T) memory.getString(0); case kEdsDataType_Int8: // EdsInt8 case kEdsDataType_UInt8: // EdsUInt8 return (T) Byte.valueOf(memory.getByte(0)); case kEdsDataType_Int16: // EdsInt16 case kEdsDataType_UInt16: // EdsUInt16 return (T) Short.valueOf(memory.getShort(0)); case kEdsDataType_Int32: // EdsInt32 case kEdsDataType_UInt32: // EdsUInt32 return (T) Long.valueOf(memory.getNativeLong(0).longValue()); case kEdsDataType_Int64: // EdsInt64 case kEdsDataType_UInt64: // EdsUInt64 return (T) Long.valueOf(memory.getLong(0)); case kEdsDataType_Float: // EdsFloat return (T) Float.valueOf(memory.getFloat(0)); case kEdsDataType_Double: // EdsDouble return (T) Double.valueOf(memory.getDouble(0)); case kEdsDataType_ByteBlock: // Byte Block // TODO: According to API, is either EdsInt8[] or // EdsUInt32[], but perhaps former is a typo or an old value return (T) memory.getIntArray(0, size / 4); case kEdsDataType_Rational: // EdsRational return (T) new EdsRational(memory); case kEdsDataType_Point: // EdsPoint return (T) new EdsPoint(memory); case kEdsDataType_Rect: // EdsRect return (T) new EdsRect(memory); case kEdsDataType_Time: // EdsTime return (T) new EdsTime(memory); case kEdsDataType_FocusInfo: // EdsFocusInfo return (T) new EdsFocusInfo(memory); case kEdsDataType_PictureStyleDesc: // EdsPictureStyleDesc return (T) new EdsPictureStyleDesc(memory); case kEdsDataType_Int8_Array: // EdsInt8[] case kEdsDataType_UInt8_Array: // EdsUInt8[] return (T) memory.getByteArray(0, size); case kEdsDataType_Int16_Array: // EdsInt16[] case kEdsDataType_UInt16_Array: // EdsUInt16[] return (T) memory.getShortArray(0, size / 2); case kEdsDataType_Int32_Array: // EdsInt32[] case kEdsDataType_UInt32_Array: // EdsUInt32[] return (T) memory.getIntArray(0, size / 4); case kEdsDataType_Bool: // EdsBool // TODO: implement case kEdsDataType_Bool_Array: // EdsBool[] // TODO: implement case kEdsDataType_Rational_Array: // EdsRational[] // TODO: implement default: throw new IllegalStateException( type.description() + " (" + type.name() + ") is not currently supported by GetPropertyCommand"); } } throw new IllegalArgumentException( "An error occurred while getting " + property.name() + " data (error " + err.value() + ": " + err.name() + " - " + err.description() + ")"); }
@Override public synchronized void dispose() { super.dispose(); }
/** Returns the context of this program */ public synchronized CLProgram build() throws CLBuildException { if (built) throw new IllegalThreadStateException("Program was already built !"); String contentSignature = null; File cacheFile = null; boolean readBinaries = false; if (isCached()) { try { contentSignature = computeCacheSignature(); byte[] sha = java.security.MessageDigest.getInstance("MD5") .digest(contentSignature.getBytes(textEncoding)); StringBuilder shab = new StringBuilder(); for (byte b : sha) shab.append(Integer.toHexString(b & 0xff)); String hash = shab.toString(); cacheFile = new File(JavaCL.userCacheDir, hash); if (cacheFile.exists()) { Pair<Map<CLDevice, byte[]>, String> bins = readBinaries( Arrays.asList(getDevices()), contentSignature, new FileInputStream(cacheFile)); setBinaries(bins.getFirst()); this.source = bins.getSecond(); assert log(Level.INFO, "Read binaries cache from '" + cacheFile + "'"); readBinaries = true; } } catch (Exception ex) { assert log(Level.WARNING, "Failed to load cached program", ex); entity = null; } } if (entity == null) allocate(); Runnable deleteTempFiles = null; if (!readBinaries) try { deleteTempFiles = copyIncludesToTemporaryDirectory(); } catch (IOException ex) { throw new CLBuildException(this, ex.toString(), Collections.EMPTY_LIST); } int nDevices = devices.length; cl_device_id[] deviceIds = null; if (nDevices != 0) { deviceIds = new cl_device_id[nDevices]; for (int i = 0; i < nDevices; i++) deviceIds[i] = devices[i].getEntity(); } int err = CL.clBuildProgram( getEntity(), nDevices, deviceIds, readBinaries ? null : getOptionsString(), null, null); // int err = CL.clBuildProgram(getEntity(), 0, null, getOptionsString(), null, null); if (err != CL_SUCCESS) { // BUILD_PROGRAM_FAILURE) { NativeSizeByReference len = new NativeSizeByReference(); int bufLen = 2048 * 32; // TODO find proper size Memory buffer = new Memory(bufLen); HashSet<String> errs = new HashSet<String>(); if (deviceIds == null) { error( CL.clGetProgramBuildInfo( getEntity(), null, CL_PROGRAM_BUILD_LOG, toNS(bufLen), buffer, len)); String s = buffer.getString(0); errs.add(s); } else for (cl_device_id device : deviceIds) { error( CL.clGetProgramBuildInfo( getEntity(), device, CL_PROGRAM_BUILD_LOG, toNS(bufLen), buffer, len)); String s = buffer.getString(0); errs.add(s); } throw new CLBuildException(this, "Compilation failure : " + errorString(err), errs); } built = true; if (deleteTempFiles != null) deleteTempFiles.run(); if (isCached() && !readBinaries) { JavaCL.userCacheDir.mkdirs(); try { Map<CLDevice, byte[]> binaries = getBinaries(); if (!binaries.isEmpty()) { writeBinaries( getBinaries(), getSource(), contentSignature, new FileOutputStream(cacheFile)); assert log(Level.INFO, "Wrote binaries cache to '" + cacheFile + "'"); } } catch (Exception ex) { new IOException("[JavaCL] Failed to cache program", ex).printStackTrace(); } } return this; }
@Override public void display(Memory memory) { if (BUFFER_SIZE <= 0) return; videoBuffer = memory.getByteBuffer(0, BUFFER_SIZE); newBuffer = true; }