input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code void delete(byte[] key) throws IOException { writeLock.lock(); try { InMemoryIndexMetaData metaData = inMemoryIndex.get(key); if (metaData != null) { //TODO: implement a getAndRemove method in InMemoryIndex. inMemoryIndex.remove(key); TombstoneEntry entry = new TombstoneEntry(key, getNextSequenceNumber(), -1, Versions.CURRENT_TOMBSTONE_FILE_VERSION); currentTombstoneFile = rollOverTombstoneFile(entry, currentTombstoneFile); currentTombstoneFile.write(entry); markPreviousVersionAsStale(key, metaData); } } finally { writeLock.unlock(); } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code void close() throws IOException { writeLock.lock(); try { if (isClosing) { // instance already closed. return; } isClosing = true; try { if(!compactionManager.stopCompactionThread(true)) setIOErrorFlag(); } catch (IOException e) { logger.error("Error while stopping compaction thread. Setting IOError flag", e); setIOErrorFlag(); } if (options.isCleanUpInMemoryIndexOnClose()) inMemoryIndex.close(); if (currentWriteFile != null) { currentWriteFile.flushToDisk(); currentWriteFile.getIndexFile().flushToDisk(); currentWriteFile.close(); } if (currentTombstoneFile != null) { currentTombstoneFile.flushToDisk(); currentTombstoneFile.close(); } for (HaloDBFile file : readFileMap.values()) { file.close(); } DBMetaData metaData = new DBMetaData(dbDirectory); metaData.loadFromFileIfExists(); metaData.setOpen(false); metaData.storeToFile(); dbDirectory.close(); if (dbLock != null) { dbLock.close(); } } finally { writeLock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long getSequenceNumber() { return sequenceNumber; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code DBMetaData(String dbDirectory) { this.dbDirectory = dbDirectory; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean stopCompactionThread() throws IOException { isRunning = false; if (compactionThread != null) { try { // We don't want to call interrupt on compaction thread as it // may interrupt IO operations and leave files in an inconsistent state. // instead we use -10101 as a stop signal. compactionQueue.put(STOP_SIGNAL); compactionThread.join(); if (currentWriteFile != null) { currentWriteFile.flushToDisk(); currentWriteFile.getIndexFile().flushToDisk(); currentWriteFile.close(); } } catch (InterruptedException e) { logger.error("Error while waiting for compaction thread to stop", e); return false; } } return true; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code CompactionManager(HaloDBInternal dbInternal) { this.dbInternal = dbInternal; this.compactionRateLimiter = RateLimiter.create(dbInternal.options.getCompactionJobRate()); this.compactionQueue = new LinkedBlockingQueue<>(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void mergeTombstoneFiles() throws IOException { if (!options.isCleanUpTombstonesDuringOpen()) { logger.info("CleanUpTombstonesDuringOpen is not enabled, returning"); return; } File[] tombStoneFiles = dbDirectory.listTombstoneFiles(); logger.info("About to merge {} tombstone files ...", tombStoneFiles.length); TombstoneFile mergedTombstoneFile = null; // Use compaction job rate as write rate limiter to avoid IO impact final RateLimiter rateLimiter = RateLimiter.create(options.getCompactionJobRate()); for (File file : tombStoneFiles) { TombstoneFile tombstoneFile = new TombstoneFile(file, options, dbDirectory); if (currentTombstoneFile != null && tombstoneFile.getName().equals(currentTombstoneFile.getName())) { continue; // not touch current tombstone file } tombstoneFile.open(); TombstoneFile.TombstoneFileIterator iterator = tombstoneFile.newIterator(); long count = 0; while (iterator.hasNext()) { TombstoneEntry entry = iterator.next(); rateLimiter.acquire(entry.size()); count++; mergedTombstoneFile = rollOverTombstoneFile(entry, mergedTombstoneFile); mergedTombstoneFile.write(entry); } if (count > 0) { logger.debug("Merged {} tombstones from {} to {}", count, tombstoneFile.getName(), mergedTombstoneFile.getName()); } tombstoneFile.close(); tombstoneFile.delete(); } logger.info("Tombstone files count, before merge:{}, after merge:{}", tombStoneFiles.length, dbDirectory.listTombstoneFiles().length); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void close() throws IOException { writeLock.lock(); try { if (isClosing) { // instance already closed. return; } isClosing = true; try { if(!compactionManager.stopCompactionThread(true)) setIOErrorFlag(); } catch (IOException e) { logger.error("Error while stopping compaction thread. Setting IOError flag", e); setIOErrorFlag(); } if (options.isCleanUpInMemoryIndexOnClose()) inMemoryIndex.close(); if (currentWriteFile != null) { currentWriteFile.flushToDisk(); currentWriteFile.getIndexFile().flushToDisk(); currentWriteFile.close(); } if (currentTombstoneFile != null) { currentTombstoneFile.flushToDisk(); currentTombstoneFile.close(); } for (HaloDBFile file : readFileMap.values()) { file.close(); } DBMetaData metaData = new DBMetaData(dbDirectory); metaData.loadFromFileIfExists(); metaData.setOpen(false); metaData.storeToFile(); dbDirectory.close(); if (dbLock != null) { dbLock.close(); } } finally { writeLock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean isMergeComplete() { if (compactionQueue.isEmpty()) { try { stopCompactionThread(); } catch (IOException e) { logger.error("Error in isMergeComplete", e); } return true; } for (int fileId : compactionQueue) { // current write file and current compaction file will not be compacted. // if there are any other pending files return false. if (fileId != dbInternal.getCurrentWriteFileId() && fileId != getCurrentWriteFileId()) { return false; } } return true; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code CompactionManager(HaloDBInternal dbInternal) { this.dbInternal = dbInternal; this.compactionRateLimiter = RateLimiter.create(dbInternal.options.compactionJobRate); this.compactionQueue = new LinkedBlockingQueue<>(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReOpenDBAfterMerge() throws IOException, InterruptedException { String directory = "/tmp/HaloDBTestWithMerge/testReOpenDBAfterMerge"; HaloDBOptions options = new HaloDBOptions(); options.maxFileSize = recordsPerFile * recordSize; options.mergeThresholdPerFile = 0.5; options.isMergeDisabled = false; options.mergeJobIntervalInSeconds = 2; HaloDB db = getTestDB(directory, options); Record[] records = insertAndUpdateRecords(numberOfRecords, db); TestUtils.waitForMergeToComplete(db); db.close(); db = getTestDBWithoutDeletingFiles(directory, options); for (Record r : records) { byte[] actual = db.get(r.getKey()); Assert.assertEquals(actual, r.getValue()); } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReOpenDBAfterMerge() throws IOException, InterruptedException { String directory = "/tmp/HaloDBTestWithMerge/testReOpenDBAfterMerge"; HaloDBOptions options = new HaloDBOptions(); options.maxFileSize = recordsPerFile * recordSize; options.mergeThresholdPerFile = 0.5; options.isMergeDisabled = false; HaloDB db = getTestDB(directory, options); Record[] records = insertAndUpdateRecords(numberOfRecords, db); TestUtils.waitForMergeToComplete(db); db.close(); db = getTestDBWithoutDeletingFiles(directory, options); for (Record r : records) { byte[] actual = db.get(r.getKey()); Assert.assertEquals(actual, r.getValue()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean isCompactionComplete() { if (dbInternal.options.isCompactionDisabled()) return true; if (compactionQueue.isEmpty()) { try { submitFileForCompaction(STOP_SIGNAL); compactionThread.join(); } catch (InterruptedException e) { logger.error("Error in isCompactionComplete", e); } return true; } return false; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code CompactionManager(HaloDBInternal dbInternal) { this.dbInternal = dbInternal; this.compactionRateLimiter = RateLimiter.create(dbInternal.options.getCompactionJobRate()); this.compactionQueue = new LinkedBlockingQueue<>(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRepairDB() throws IOException { String directory = Paths.get("tmp", "DBRepairTest", "testRepairDB").toString(); HaloDBOptions options = new HaloDBOptions(); options.maxFileSize = 1024 * 1024; HaloDB db = getTestDB(directory, options); int noOfRecords = 5 * 1024 + 512; List<Record> records = TestUtils.insertRandomRecordsOfSize(db, noOfRecords, 1024-Record.Header.HEADER_SIZE); File latestDataFile = TestUtils.getLatestDataFile(directory); db.close(); // trick the db to think that there was an unclean shutdown. DBMetaData dbMetaData = new DBMetaData(directory); dbMetaData.setOpen(true); dbMetaData.storeToFile(); db = getTestDBWithoutDeletingFiles(directory, options); // latest file should have been repaired and deleted. Assert.assertFalse(latestDataFile.exists()); Assert.assertEquals(db.size(), noOfRecords); for (Record r : records) { Assert.assertEquals(db.get(r.getKey()), r.getValue()); } } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testRepairDB() throws IOException { String directory = Paths.get("tmp", "DBRepairTest", "testRepairDB").toString(); HaloDBOptions options = new HaloDBOptions(); options.maxFileSize = 1024 * 1024; HaloDB db = getTestDB(directory, options); int noOfRecords = 5 * 1024 + 512; // 5 files with 1024 records and 1 with 512 records. List<Record> records = TestUtils.insertRandomRecordsOfSize(db, noOfRecords, 1024-Record.Header.HEADER_SIZE); File latestDataFile = TestUtils.getLatestDataFile(directory); db.close(); // trick the db to think that there was an unclean shutdown. DBMetaData dbMetaData = new DBMetaData(directory); dbMetaData.setOpen(true); dbMetaData.storeToFile(); db = getTestDBWithoutDeletingFiles(directory, options); // latest file should have been repaired and deleted. Assert.assertFalse(latestDataFile.exists()); Assert.assertEquals(db.size(), noOfRecords); for (Record r : records) { Assert.assertEquals(db.get(r.getKey()), r.getValue()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code RecordMetaDataForCache writeRecord(Record record) throws IOException { long start = System.nanoTime(); writeToChannel(record.serialize(), writeChannel); int recordSize = record.getRecordSize(); long recordOffset = writeOffset; writeOffset += recordSize; IndexFileEntry indexFileEntry = new IndexFileEntry(record.getKey(), recordSize, recordOffset, record.getSequenceNumber(), record.getFlags()); indexFile.write(indexFileEntry); HaloDB.recordWriteLatency(System.nanoTime() - start); return new RecordMetaDataForCache(fileId, recordOffset, recordSize, record.getSequenceNumber()); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code long getWriteOffset() { return writeOffset; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static int sizeof(Class<? extends Pointer> type) { // Should we synchronize that? return memberOffsets.get(type).get("sizeof"); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public static int sizeof(Class<? extends Pointer> type) { return offsetof(type, "sizeof"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code String translate(String text) { int namespace = text.lastIndexOf("::"); if (namespace >= 0) { Info info2 = infoMap.getFirst(text.substring(0, namespace)); text = text.substring(namespace + 2); if (info2.pointerTypes != null) { text = info2.pointerTypes[0] + "." + text; } } return text; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code Parser(Parser p, String text) { this.logger = p.logger; this.properties = p.properties; this.infoMap = p.infoMap; this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize()); this.lineSeparator = p.lineSeparator; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BytePointer putString(String s) { byte[] bytes = s.getBytes(); //capacity(bytes.length+1); asBuffer().put(bytes).put((byte)0); return this; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public BytePointer putString(String s) { byte[] bytes = s.getBytes(); return put(bytes).put(bytes.length, (byte)0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean generate(Class<?> ... classes) throws FileNotFoundException { // first pass using a null writer to fill up the LinkedListRegister objects out = new PrintWriter(new Writer() { @Override public void close() { } @Override public void flush() { } @Override public void write(char[] cbuf, int off, int len) { } }); functionDefinitions = new LinkedListRegister<String>(); functionPointers = new LinkedListRegister<String>(); deallocators = new LinkedListRegister<Class>(); arrayDeallocators = new LinkedListRegister<Class>(); jclasses = new LinkedListRegister<Class>(); jclassesInit = new LinkedListRegister<Class>(); members = new HashMap<Class,LinkedList<String>>(); mayThrowExceptions = false; if (doClasses(true, classes)) { // second pass with the real writer out = writer != null ? writer : new PrintWriter(file); doClasses(mayThrowExceptions, classes); return true; } return false; } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code public boolean generate(Class<?> ... classes) throws FileNotFoundException { // first pass using a null writer to fill up the LinkedListRegister objects out = new PrintWriter(new Writer() { @Override public void close() { } @Override public void flush() { } @Override public void write(char[] cbuf, int off, int len) { } }); functionDefinitions = new LinkedListRegister<String>(); functionPointers = new LinkedListRegister<String>(); deallocators = new LinkedListRegister<Class>(); arrayDeallocators = new LinkedListRegister<Class>(); jclasses = new LinkedListRegister<Class>(); jclassesInit = new LinkedListRegister<Class>(); members = new HashMap<Class,LinkedList<String>>(); mayThrowExceptions = false; usesAdapters = false; if (doClasses(true, true, classes)) { // second pass with the real writer out = writer != null ? writer : new PrintWriter(file); doClasses(mayThrowExceptions, usesAdapters, classes); return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { Main main = new Main(); for (int i = 0; i < args.length; i++) { if ("-help".equals(args[i]) || "--help".equals(args[i])) { printHelp(); System.exit(0); } else if ("-classpath".equals(args[i]) || "-cp".equals(args[i]) || "-lib".equals(args[i])) { main.setClassPaths(args[++i]); } else if ("-d".equals(args[i])) { main.setOutputDirectory(args[++i]); } else if ("-o".equals(args[i])) { main.setOutputName(args[++i]); } else if ("-cpp".equals(args[i]) || "-nocompile".equals(args[i])) { main.setCompile(false); } else if ("-jarprefix".equals(args[i])) { main.setJarPrefix(args[++i]); } else if ("-properties".equals(args[i])) { main.setProperties(args[++i]); } else if ("-propertyfile".equals(args[i])) { main.setPropertyFile(args[++i]); } else if (args[i].startsWith("-D")) { main.setProperty(args[i]); } else if (args[i].startsWith("-")) { System.err.println("Error: Invalid option \"" + args[i] + "\""); printHelp(); System.exit(1); } else { main.setClassesOrPackages(args[i]); } } main.build(); } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { Main main = new Main(); for (int i = 0; i < args.length; i++) { if ("-help".equals(args[i]) || "--help".equals(args[i])) { printHelp(); System.exit(0); } else if ("-classpath".equals(args[i]) || "-cp".equals(args[i]) || "-lib".equals(args[i])) { main.classPaths(args[++i]); } else if ("-d".equals(args[i])) { main.outputDirectory(args[++i]); } else if ("-o".equals(args[i])) { main.outputName(args[++i]); } else if ("-cpp".equals(args[i]) || "-nocompile".equals(args[i])) { main.compile(false); } else if ("-jarprefix".equals(args[i])) { main.jarPrefix(args[++i]); } else if ("-properties".equals(args[i])) { main.properties(args[++i]); } else if ("-propertyfile".equals(args[i])) { main.propertyFile(args[++i]); } else if (args[i].startsWith("-D")) { main.property(args[i]); } else if (args[i].startsWith("-")) { System.err.println("Error: Invalid option \"" + args[i] + "\""); printHelp(); System.exit(1); } else { main.classesOrPackages(args[i]); } } main.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void parse(File outputFile, Context context, String[] includePath, String ... includes) throws IOException, ParserException { ArrayList<Token> tokenList = new ArrayList<Token>(); for (String include : includes) { File file = null; String filename = include; if (filename.startsWith("<") && filename.endsWith(">")) { filename = filename.substring(1, filename.length() - 1); } else { File f = new File(filename); if (f.exists()) { file = f; } } if (file == null && includePath != null) { for (String path : includePath) { File f = new File(path, filename); if (f.exists()) { file = f; break; } } } if (file == null) { file = new File(filename); } Info info = infoMap.getFirst(file.getName()); if (info != null && info.skip) { continue; } else if (!file.exists()) { throw new FileNotFoundException("Could not parse \"" + file + "\": File does not exist"); } logger.info("Parsing " + file); Token token = new Token(); token.type = Token.COMMENT; token.value = "\n// Parsed from " + include + "\n\n"; tokenList.add(token); Tokenizer tokenizer = new Tokenizer(file); while (!(token = tokenizer.nextToken()).isEmpty()) { if (token.type == -1) { token.type = Token.COMMENT; } tokenList.add(token); } if (lineSeparator == null) { lineSeparator = tokenizer.lineSeparator; } tokenizer.close(); token = new Token(); token.type = Token.COMMENT; token.spacing = "\n"; tokenList.add(token); } tokens = new TokenIndexer(infoMap, tokenList.toArray(new Token[tokenList.size()])); final String newline = lineSeparator != null ? lineSeparator : "\n"; Writer out = outputFile != null ? new FileWriter(outputFile) { @Override public Writer append(CharSequence text) throws IOException { return super.append(((String)text).replace("\n", newline).replace("\\u", "\\u005Cu")); }} : new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }; LinkedList<Info> infoList = leafInfoMap.get(null); for (Info info : infoList) { if (info.javaText != null && !info.javaText.startsWith("import")) { out.append(info.javaText + "\n"); } } out.append(" static { Loader.load(); }\n"); DeclarationList declList = new DeclarationList(); containers(context, declList); declarations(context, declList); for (Declaration d : declList) { out.append(d.text); } out.append("\n}\n").close(); } #location 78 #vulnerability type RESOURCE_LEAK
#fixed code Parser(Parser p, String text) { this.logger = p.logger; this.properties = p.properties; this.infoMap = p.infoMap; this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize()); this.lineSeparator = p.lineSeparator; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean generate(Class<?> ... classes) throws FileNotFoundException { // first pass using a null writer to fill up the LinkedListRegister objects out = new PrintWriter(new Writer() { @Override public void close() { } @Override public void flush() { } @Override public void write(char[] cbuf, int off, int len) { } }); functionDefinitions = new LinkedListRegister<String>(); functionPointers = new LinkedListRegister<String>(); deallocators = new LinkedListRegister<Class>(); arrayDeallocators = new LinkedListRegister<Class>(); jclasses = new LinkedListRegister<Class>(); jclassesInit = new LinkedListRegister<Class>(); members = new HashMap<Class,LinkedList<String>>(); if (doClasses(classes)) { // second pass with the real writer out = writer != null ? writer : new PrintWriter(file); doClasses(classes); return true; } return false; } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code public boolean generate(Class<?> ... classes) throws FileNotFoundException { // first pass using a null writer to fill up the LinkedListRegister objects out = new PrintWriter(new Writer() { @Override public void close() { } @Override public void flush() { } @Override public void write(char[] cbuf, int off, int len) { } }); functionDefinitions = new LinkedListRegister<String>(); functionPointers = new LinkedListRegister<String>(); deallocators = new LinkedListRegister<Class>(); arrayDeallocators = new LinkedListRegister<Class>(); jclasses = new LinkedListRegister<Class>(); jclassesInit = new LinkedListRegister<Class>(); members = new HashMap<Class,LinkedList<String>>(); mayThrowExceptions = false; if (doClasses(true, classes)) { // second pass with the real writer out = writer != null ? writer : new PrintWriter(file); doClasses(mayThrowExceptions, classes); return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void parse(File outputFile, Context context, String[] includePath, String ... includes) throws IOException, ParserException { ArrayList<Token> tokenList = new ArrayList<Token>(); for (String include : includes) { File file = null; String filename = include; if (filename.startsWith("<") && filename.endsWith(">")) { filename = filename.substring(1, filename.length() - 1); } else { File f = new File(filename); if (f.exists()) { file = f; } } if (file == null && includePath != null) { for (String path : includePath) { File f = new File(path, filename); if (f.exists()) { file = f; break; } } } if (file == null) { file = new File(filename); } Info info = infoMap.getFirst(file.getName()); if (info != null && info.skip) { continue; } else if (!file.exists()) { throw new FileNotFoundException("Could not parse \"" + file + "\": File does not exist"); } logger.info("Parsing " + file); Token token = new Token(); token.type = Token.COMMENT; token.value = "\n// Parsed from " + include + "\n\n"; tokenList.add(token); Tokenizer tokenizer = new Tokenizer(file); while (!(token = tokenizer.nextToken()).isEmpty()) { if (token.type == -1) { token.type = Token.COMMENT; } tokenList.add(token); } if (lineSeparator == null) { lineSeparator = tokenizer.lineSeparator; } tokenizer.close(); token = new Token(); token.type = Token.COMMENT; token.spacing = "\n"; tokenList.add(token); } tokens = new TokenIndexer(infoMap, tokenList.toArray(new Token[tokenList.size()])); final String newline = lineSeparator != null ? lineSeparator : "\n"; Writer out = outputFile != null ? new FileWriter(outputFile) { @Override public Writer append(CharSequence text) throws IOException { return super.append(((String)text).replace("\n", newline).replace("\\u", "\\u005Cu")); }} : new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }; LinkedList<Info> infoList = leafInfoMap.get(null); for (Info info : infoList) { if (info.javaText != null && !info.javaText.startsWith("import")) { out.append(info.javaText + "\n"); } } out.append(" static { Loader.load(); }\n"); DeclarationList declList = new DeclarationList(); containers(context, declList); declarations(context, declList); for (Declaration d : declList) { out.append(d.text); } out.append("\n}\n").close(); } #location 78 #vulnerability type RESOURCE_LEAK
#fixed code Parser(Parser p, String text) { this.logger = p.logger; this.properties = p.properties; this.infoMap = p.infoMap; this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize()); this.lineSeparator = p.lineSeparator; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String load(Class cls, Properties properties, boolean pathsFirst) { if (!isLoadLibraries() || cls == null) { return null; } // Find the top enclosing class, to match the library filename cls = getEnclosingClass(cls); ClassProperties p = loadProperties(cls, properties, true); // Force initialization of all the target classes in case they need it List<String> targets = p.get("target"); if (targets.isEmpty()) { if (p.getInheritedClasses() != null) { for (Class c : p.getInheritedClasses()) { targets.add(c.getName()); } } targets.add(cls.getName()); } for (String s : targets) { try { if (logger.isDebugEnabled()) { logger.debug("Loading class " + s); } Class.forName(s, true, cls.getClassLoader()); } catch (ClassNotFoundException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to load class " + s + ": " + ex); } Error e = new NoClassDefFoundError(ex.toString()); e.initCause(ex); throw e; } } String cacheDir = null; try { cacheDir = getCacheDir().getCanonicalPath(); } catch (IOException e) { // no cache dir, no worries } // Preload native libraries desired by our class List<String> preloads = new ArrayList<String>(); preloads.addAll(p.get("platform.preload")); preloads.addAll(p.get("platform.link")); UnsatisfiedLinkError preloadError = null; for (String preload : preloads) { try { URL[] urls = findLibrary(cls, p, preload, pathsFirst); String filename = loadLibrary(urls, preload); if (cacheDir != null && filename.startsWith(cacheDir)) { createLibraryLink(filename, p, preload); } } catch (UnsatisfiedLinkError e) { preloadError = e; } } try { String library = p.getProperty("platform.library"); URL[] urls = findLibrary(cls, p, library, pathsFirst); String filename = loadLibrary(urls, library); if (cacheDir != null && filename.startsWith(cacheDir)) { createLibraryLink(filename, p, library); } return filename; } catch (UnsatisfiedLinkError e) { if (preloadError != null && e.getCause() == null) { e.initCause(preloadError); } throw e; } } #location 52 #vulnerability type NULL_DEREFERENCE
#fixed code public static String load(Class cls, Properties properties, boolean pathsFirst) { if (!isLoadLibraries() || cls == null) { return null; } // Find the top enclosing class, to match the library filename cls = getEnclosingClass(cls); ClassProperties p = loadProperties(cls, properties, true); // Force initialization of all the target classes in case they need it List<String> targets = p.get("target"); if (targets.isEmpty()) { if (p.getInheritedClasses() != null) { for (Class c : p.getInheritedClasses()) { targets.add(c.getName()); } } targets.add(cls.getName()); } for (String s : targets) { try { if (logger.isDebugEnabled()) { logger.debug("Loading class " + s); } Class.forName(s, true, cls.getClassLoader()); } catch (ClassNotFoundException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to load class " + s + ": " + ex); } Error e = new NoClassDefFoundError(ex.toString()); e.initCause(ex); throw e; } } String cacheDir = null; try { cacheDir = getCacheDir().getCanonicalPath(); } catch (IOException e) { // no cache dir, no worries } // Preload native libraries desired by our class List<String> preloads = new ArrayList<String>(); preloads.addAll(p.get("platform.preload")); preloads.addAll(p.get("platform.link")); UnsatisfiedLinkError preloadError = null; for (String preload : preloads) { try { URL[] urls = findLibrary(cls, p, preload, pathsFirst); String filename = loadLibrary(urls, preload); if (cacheDir != null && filename != null && filename.startsWith(cacheDir)) { createLibraryLink(filename, p, preload); } } catch (UnsatisfiedLinkError e) { preloadError = e; } } try { String library = p.getProperty("platform.library"); URL[] urls = findLibrary(cls, p, library, pathsFirst); String filename = loadLibrary(urls, library); if (cacheDir != null && filename != null && filename.startsWith(cacheDir)) { createLibraryLink(filename, p, library); } return filename; } catch (UnsatisfiedLinkError e) { if (preloadError != null && e.getCause() == null) { e.initCause(preloadError); } throw e; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void init(long allocatedAddress, int allocatedCapacity, long deallocatorAddress) { address = allocatedAddress; position = 0; limit = allocatedCapacity; capacity = allocatedCapacity; deallocator(new NativeDeallocator(this, deallocatorAddress)); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void init(long allocatedAddress, int allocatedCapacity, long ownerAddress, long deallocatorAddress) { address = allocatedAddress; position = 0; limit = allocatedCapacity; capacity = allocatedCapacity; deallocator(new NativeDeallocator(this, ownerAddress, deallocatorAddress)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean generate(String sourceFilename, String headerFilename, String loadSuffix, String baseLoadSuffix, String classPath, Class<?> ... classes) throws IOException { try { // first pass using a null writer to fill up the IndexedSet objects out = new PrintWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }); out2 = null; callbacks = new IndexedSet<String>(); functions = new IndexedSet<Class>(); deallocators = new IndexedSet<Class>(); arrayDeallocators = new IndexedSet<Class>(); jclasses = new IndexedSet<Class>(); members = new HashMap<Class,Set<String>>(); virtualFunctions = new HashMap<Class,Set<String>>(); virtualMembers = new HashMap<Class,Set<String>>(); annotationCache = new HashMap<Method,MethodInformation>(); mayThrowExceptions = false; usesAdapters = false; passesStrings = false; if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) { for (Class<?> cls : baseClasses) { jclasses.index(cls); } } if (classes(true, true, true, loadSuffix, baseLoadSuffix, classPath, classes)) { // second pass with a real writer File sourceFile = new File(sourceFilename); File sourceDir = sourceFile.getParentFile(); if (sourceDir != null) { sourceDir.mkdirs(); } out = encoding != null ? new PrintWriter(sourceFile, encoding) : new PrintWriter(sourceFile); if (headerFilename != null) { logger.info("Generating " + headerFilename); File headerFile = new File(headerFilename); File headerDir = headerFile.getParentFile(); if (headerDir != null) { headerDir.mkdirs(); } out2 = encoding != null ? new PrintWriter(headerFile, encoding) : new PrintWriter(headerFile); } return classes(mayThrowExceptions, usesAdapters, passesStrings, loadSuffix, baseLoadSuffix, classPath, classes); } else { return false; } } finally { if (out != null) { out.close(); } if (out2 != null) { out2.close(); } } } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code public boolean generate(String sourceFilename, String headerFilename, String loadSuffix, String baseLoadSuffix, String classPath, Class<?> ... classes) throws IOException { try { // first pass using a null writer to fill up the IndexedSet objects out = new PrintWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }); out2 = null; callbacks = new IndexedSet<String>(); functions = new IndexedSet<Class>(); deallocators = new IndexedSet<Class>(); arrayDeallocators = new IndexedSet<Class>(); jclasses = new IndexedSet<Class>(); members = new HashMap<Class,Set<String>>(); virtualFunctions = new HashMap<Class,Set<String>>(); virtualMembers = new HashMap<Class,Set<String>>(); annotationCache = new HashMap<Method,MethodInformation>(); mayThrowExceptions = false; usesAdapters = false; passesStrings = false; if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) { for (Class<?> cls : baseClasses) { jclasses.index(cls); } } if (classes(true, true, true, true, loadSuffix, baseLoadSuffix, classPath, classes)) { // second pass with a real writer File sourceFile = new File(sourceFilename); File sourceDir = sourceFile.getParentFile(); if (sourceDir != null) { sourceDir.mkdirs(); } out = encoding != null ? new PrintWriter(sourceFile, encoding) : new PrintWriter(sourceFile); if (headerFilename != null) { logger.info("Generating " + headerFilename); File headerFile = new File(headerFilename); File headerDir = headerFile.getParentFile(); if (headerDir != null) { headerDir.mkdirs(); } out2 = encoding != null ? new PrintWriter(headerFile, encoding) : new PrintWriter(headerFile); } return classes(mayThrowExceptions, usesAdapters, passesStrings, accessesEnums, loadSuffix, baseLoadSuffix, classPath, classes); } else { return false; } } finally { if (out != null) { out.close(); } if (out2 != null) { out2.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Token[] expand(Token[] array, int index) { if (index < array.length && infoMap.containsKey(array[index].value)) { // if we hit a token whose info.cppText starts with #define (a macro), expand it int startIndex = index; Info info = infoMap.getFirst(array[index].value); if (info != null && info.cppText != null) { try { Tokenizer tokenizer = new Tokenizer(info.cppText, array[index].file, array[index].lineNumber); if (!tokenizer.nextToken().match('#') || !tokenizer.nextToken().match(Token.DEFINE) || !tokenizer.nextToken().match(info.cppNames[0])) { return array; } // copy the array of tokens up to this point List<Token> tokens = new ArrayList<Token>(); for (int i = 0; i < index; i++) { tokens.add(array[i]); } List<String> params = new ArrayList<String>(); List<Token>[] args = null; Token token = tokenizer.nextToken(); if (info.cppNames[0].equals("__COUNTER__")) { token.value = Integer.toString(counter++); } // pick up the parameters and arguments of the macro if it has any String name = array[index].value; if (token.match('(')) { token = tokenizer.nextToken(); while (!token.isEmpty()) { if (token.match(Token.IDENTIFIER)) { params.add(token.value); } else if (token.match(')')) { token = tokenizer.nextToken(); break; } token = tokenizer.nextToken(); } index++; if (params.size() > 0 && (index >= array.length || !array[index].match('('))) { return array; } name += array[index].spacing + array[index]; args = new List[params.size()]; int count = 0, count2 = 0; for (index++; index < array.length; index++) { Token token2 = array[index]; name += token2.spacing + token2; if (count2 == 0 && token2.match(')')) { break; } else if (count2 == 0 && token2.match(',')) { count++; continue; } else if (token2.match('(','[','{')) { count2++; } else if (token2.match(')',']','}')) { count2--; } if (count < args.length) { if (args[count] == null) { args[count] = new ArrayList<Token>(); } args[count].add(token2); } } // expand the arguments of the macros as well for (int i = 0; i < args.length; i++) { if (infoMap.containsKey(args[i].get(0).value)) { args[i] = Arrays.asList(expand(args[i].toArray(new Token[args[i].size()]), 0)); } } } int startToken = tokens.size(); // expand the token in question, unless we should skip it info = infoMap.getFirst(name); while ((info == null || !info.skip) && !token.isEmpty()) { boolean foundArg = false; for (int i = 0; i < params.size(); i++) { if (params.get(i).equals(token.value)) { String s = token.spacing; for (Token arg : args[i]) { // clone tokens here to avoid potential problems with concatenation below Token t = new Token(arg); if (s != null) { t.spacing += s; } tokens.add(t); s = null; } foundArg = true; break; } } if (!foundArg) { if (token.type == -1) { token.type = Token.COMMENT; } tokens.add(token); } token = tokenizer.nextToken(); } // concatenate tokens as required for (int i = startToken; i < tokens.size(); i++) { if (tokens.get(i).match("##") && i > 0 && i + 1 < tokens.size()) { tokens.get(i - 1).value += tokens.get(i + 1).value; tokens.remove(i); tokens.remove(i); i--; } } // copy the rest of the tokens from this point on for (index++; index < array.length; index++) { tokens.add(array[index]); } if ((info == null || !info.skip) && startToken < tokens.size()) { tokens.get(startToken).spacing = array[startIndex].spacing; } array = tokens.toArray(new Token[tokens.size()]); } catch (IOException ex) { throw new RuntimeException(ex); } } } return array; } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code TokenIndexer(InfoMap infoMap, Token[] array, boolean isCFile) { this.infoMap = infoMap; this.array = array; this.isCFile = isCFile; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static File cacheResource(URL resourceURL, String target) throws IOException { // Find appropriate subdirectory in cache for the resource ... File urlFile = new File(resourceURL.getPath()); String name = urlFile.getName(); long size, timestamp; File cacheSubdir = getCacheDir().getCanonicalFile(); URLConnection urlConnection = resourceURL.openConnection(); if (urlConnection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); File jarFileFile = new File(jarFile.getName()); File jarEntryFile = new File(jarEntry.getName()); size = jarEntry.getSize(); timestamp = jarEntry.getTime(); cacheSubdir = new File(cacheSubdir, jarFileFile.getName() + File.separator + jarEntryFile.getParent()); } else { size = urlFile.length(); timestamp = urlFile.lastModified(); cacheSubdir = new File(cacheSubdir, name); } if (resourceURL.getRef() != null) { // ... get the URL fragment to let users rename library files ... name = resourceURL.getRef(); } // ... then check if it has not already been extracted, and if not ... File file = new File(cacheSubdir, name); if (target != null && target.length() > 0) { // ... create symbolic link to already extracted library or ... try { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link to " + target); } Path path = file.toPath(), targetPath = Paths.get(target); if ((!file.exists() || !Files.isSymbolicLink(path)) && targetPath.isAbsolute() && !targetPath.equals(path)) { file.delete(); Files.createSymbolicLink(path, targetPath); } } catch (IOException e) { // ... (probably an unsupported operation on Windows, but DLLs never need links) ... return null; } } else if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... then extract it from our resources ... if (logger.isDebugEnabled()) { logger.debug("Extracting " + resourceURL); } file.delete(); extractResource(resourceURL, file, null, null); file.setLastModified(timestamp); } else while (System.currentTimeMillis() - file.lastModified() >= 0 && System.currentTimeMillis() - file.lastModified() < 1000) { // ... else wait until the file is at least 1 second old ... try { Thread.sleep(1000); } catch (InterruptedException ex) { // ... and reset interrupt to be nice. Thread.currentThread().interrupt(); } } return file; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public static File cacheResource(URL resourceURL, String target) throws IOException { // Find appropriate subdirectory in cache for the resource ... File urlFile = new File(resourceURL.getPath()); String name = urlFile.getName(); long size, timestamp; File cacheSubdir = getCacheDir().getCanonicalFile(); URLConnection urlConnection = resourceURL.openConnection(); if (urlConnection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); File jarFileFile = new File(jarFile.getName()); File jarEntryFile = new File(jarEntry.getName()); size = jarEntry.getSize(); timestamp = jarEntry.getTime(); cacheSubdir = new File(cacheSubdir, jarFileFile.getName() + File.separator + jarEntryFile.getParent()); } else { size = urlFile.length(); timestamp = urlFile.lastModified(); cacheSubdir = new File(cacheSubdir, name); } if (resourceURL.getRef() != null) { // ... get the URL fragment to let users rename library files ... name = resourceURL.getRef(); } // ... then check if it has not already been extracted, and if not ... File file = new File(cacheSubdir, name); if (target != null && target.length() > 0) { // ... create symbolic link to already extracted library or ... Path path = file.toPath(), targetPath = Paths.get(target); try { if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path); } file.delete(); Files.createSymbolicLink(path, targetPath); } } catch (IOException | UnsupportedOperationException e) { // ... (probably an unsupported operation on Windows, but DLLs never need links) ... if (logger.isDebugEnabled()) { logger.debug("Failed to create symbolic link " + path + ": " + e); } return null; } } else if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... then extract it from our resources ... if (logger.isDebugEnabled()) { logger.debug("Extracting " + resourceURL); } file.delete(); extractResource(resourceURL, file, null, null); file.setLastModified(timestamp); } else while (System.currentTimeMillis() - file.lastModified() >= 0 && System.currentTimeMillis() - file.lastModified() < 1000) { // ... else wait until the file is at least 1 second old ... try { Thread.sleep(1000); } catch (InterruptedException ex) { // ... and reset interrupt to be nice. Thread.currentThread().interrupt(); } } return file; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public File parse(File outputDirectory, String[] classPath, Class cls) throws IOException, Exception { Loader.ClassProperties allProperties = Loader.loadProperties(cls, properties, true); Loader.ClassProperties clsProperties = Loader.loadProperties(cls, properties, false); LinkedList<File> allFiles = allProperties.getHeaderFiles(); LinkedList<File> clsFiles = clsProperties.getHeaderFiles(); LinkedList<String> allTargets = allProperties.get("target"); LinkedList<String> clsTargets = clsProperties.get("target"); LinkedList<String> clsHelpers = clsProperties.get("helper"); String target = clsTargets.getFirst(); // there can only be one LinkedList<Class> allInherited = allProperties.getInheritedClasses(); infoMap = new Parser.InfoMap(); for (Class c : allInherited) { try { ((InfoMapper)c.newInstance()).map(infoMap); } catch (ClassCastException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { // fail silently as if the interface wasn't implemented } } leafInfoMap = new Parser.InfoMap(); try { ((InfoMapper)cls.newInstance()).map(leafInfoMap); } catch (ClassCastException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { // fail silently as if the interface wasn't implemented } infoMap.putAll(leafInfoMap); String version = Generator.class.getPackage().getImplementationVersion(); if (version == null) { version = "unknown"; } String text = "// Targeted by JavaCPP version " + version + "\n\n"; int n = target.lastIndexOf('.'); if (n >= 0) { text += "package " + target.substring(0, n) + ";\n\n"; } LinkedList<Info> infoList = leafInfoMap.get(null); for (Info info : infoList) { if (info.javaText != null && info.javaText.startsWith("import")) { text += info.javaText + "\n"; } } text += "import com.googlecode.javacpp.*;\n" + "import com.googlecode.javacpp.annotation.*;\n" + "import java.nio.*;\n\n"; for (String s : allTargets) { if (!target.equals(s)) { text += "import static " + s + ".*;\n"; } } if (allTargets.size() > 1) { text += "\n"; } text += "public class " + target.substring(n + 1) + " extends " + (clsHelpers.size() > 0 ? clsHelpers.getFirst() : cls.getCanonicalName()) + " {"; leafInfoMap.putFirst(new Info().javaText(text)); String targetPath = target.replace('.', File.separatorChar); File targetFile = new File(outputDirectory, targetPath + ".java"); logger.info("Targeting " + targetFile); Context context = new Context(); String[] includePath = classPath; n = targetPath.lastIndexOf(File.separatorChar); if (n >= 0) { includePath = classPath.clone(); for (int i = 0; i < includePath.length; i++) { includePath[i] += File.separator + targetPath.substring(0, n); } } for (File f : allFiles) { if (!clsFiles.contains(f)) { parse(null, context, includePath, f); } } parse(targetFile, context, includePath, clsFiles.toArray(new File[clsFiles.size()])); return targetFile; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public File parse(File outputDirectory, String[] classPath, Class cls) throws IOException, Exception { Loader.ClassProperties allProperties = Loader.loadProperties(cls, properties, true); Loader.ClassProperties clsProperties = Loader.loadProperties(cls, properties, false); LinkedList<String> clsIncludes = new LinkedList<String>(); clsIncludes.addAll(clsProperties.get("platform.include")); clsIncludes.addAll(clsProperties.get("platform.cinclude")); LinkedList<String> allIncludes = new LinkedList<String>(); allIncludes.addAll(allProperties.get("platform.include")); allIncludes.addAll(allProperties.get("platform.cinclude")); LinkedList<File> allFiles = findHeaderFiles(allProperties, allIncludes); LinkedList<File> clsFiles = findHeaderFiles(allProperties, clsIncludes); LinkedList<String> allTargets = allProperties.get("target"); LinkedList<String> clsTargets = clsProperties.get("target"); LinkedList<String> clsHelpers = clsProperties.get("helper"); String target = clsTargets.getFirst(); // there can only be one LinkedList<Class> allInherited = allProperties.getInheritedClasses(); infoMap = new Parser.InfoMap(); for (Class c : allInherited) { try { ((InfoMapper)c.newInstance()).map(infoMap); } catch (ClassCastException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { // fail silently as if the interface wasn't implemented } } leafInfoMap = new Parser.InfoMap(); try { ((InfoMapper)cls.newInstance()).map(leafInfoMap); } catch (ClassCastException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { // fail silently as if the interface wasn't implemented } infoMap.putAll(leafInfoMap); String version = Generator.class.getPackage().getImplementationVersion(); if (version == null) { version = "unknown"; } String text = "// Targeted by JavaCPP version " + version + "\n\n"; int n = target.lastIndexOf('.'); if (n >= 0) { text += "package " + target.substring(0, n) + ";\n\n"; } LinkedList<Info> infoList = leafInfoMap.get(null); for (Info info : infoList) { if (info.javaText != null && info.javaText.startsWith("import")) { text += info.javaText + "\n"; } } text += "import com.googlecode.javacpp.*;\n" + "import com.googlecode.javacpp.annotation.*;\n" + "import java.nio.*;\n\n"; for (String s : allTargets) { if (!target.equals(s)) { text += "import static " + s + ".*;\n"; } } if (allTargets.size() > 1) { text += "\n"; } text += "public class " + target.substring(n + 1) + " extends " + (clsHelpers.size() > 0 ? clsHelpers.getFirst() : cls.getCanonicalName()) + " {"; leafInfoMap.putFirst(new Info().javaText(text)); String targetPath = target.replace('.', File.separatorChar); File targetFile = new File(outputDirectory, targetPath + ".java"); logger.info("Targeting " + targetFile); Context context = new Context(); String[] includePath = classPath; n = targetPath.lastIndexOf(File.separatorChar); if (n >= 0) { includePath = classPath.clone(); for (int i = 0; i < includePath.length; i++) { includePath[i] += File.separator + targetPath.substring(0, n); } } for (File f : allFiles) { if (!clsFiles.contains(f)) { parse(null, context, includePath, f); } } parse(targetFile, context, includePath, clsFiles.toArray(new File[clsFiles.size()])); return targetFile; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static int offsetof(Class<? extends Pointer> type, String member) { // Should we synchronize that? return memberOffsets.get(type).get(member); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public static int offsetof(Class<? extends Pointer> type, String member) { // Should we synchronize that? HashMap<String,Integer> offsets = memberOffsets.get(type); while (offsets == null && type.getSuperclass() != null) { type = type.getSuperclass().asSubclass(Pointer.class); offsets = memberOffsets.get(type); } return offsets.get(member); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static File extractResource(URL resourceURL, File directory, String prefix, String suffix) throws IOException { InputStream is = resourceURL != null ? resourceURL.openStream() : null; if (is == null) { return null; } File file = null; boolean fileExisted = false; try { if (prefix == null && suffix == null) { if (directory == null) { directory = new File(System.getProperty("java.io.tmpdir")); } file = new File(directory, new File(resourceURL.getPath()).getName()); fileExisted = file.exists(); } else { file = File.createTempFile(prefix, suffix, directory); } FileOutputStream os = new FileOutputStream(file); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } is.close(); os.close(); } catch (IOException e) { if (file != null && !fileExisted) { file.delete(); } throw e; } return file; } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public static File extractResource(URL resourceURL, File directory, String prefix, String suffix) throws IOException { InputStream is = resourceURL != null ? resourceURL.openStream() : null; OutputStream os = null; if (is == null) { return null; } File file = null; boolean fileExisted = false; try { if (prefix == null && suffix == null) { if (directory == null) { directory = new File(System.getProperty("java.io.tmpdir")); } file = new File(directory, new File(resourceURL.getPath()).getName()); fileExisted = file.exists(); } else { file = File.createTempFile(prefix, suffix, directory); } os = new FileOutputStream(file); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } is.close(); os.close(); } catch (IOException e) { if (file != null && !fileExisted) { file.delete(); } throw e; } finally { is.close(); if (os != null) { os.close(); } } return file; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ByteBuffer asByteBuffer() { if (isNull()) { return null; } if (limit > 0 && limit < position) { throw new IllegalArgumentException("limit < position: (" + limit + " < " + position + ")"); } int valueSize = sizeof(); long arrayPosition = position; long arrayLimit = limit; position = valueSize * arrayPosition; limit = valueSize * (arrayLimit <= 0 ? arrayPosition + 1 : arrayLimit); ByteBuffer b = asDirectBuffer().order(ByteOrder.nativeOrder()); position = arrayPosition; limit = arrayLimit; return b; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public ByteBuffer asByteBuffer() { if (isNull()) { return null; } if (limit > 0 && limit < position) { throw new IllegalArgumentException("limit < position: (" + limit + " < " + position + ")"); } int size = sizeof(); Pointer p = new Pointer(); p.address = address; return p.position(size * position) .limit(size * (limit <= 0 ? position + 1 : limit)) .asDirectBuffer().order(ByteOrder.nativeOrder()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute() throws MojoExecutionException { final Log log = getLog(); try { log.info("Executing JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("classPath: " + classPath); log.debug("classPaths: " + Arrays.deepToString(classPaths)); log.debug("outputDirectory: " + outputDirectory); log.debug("outputName: " + outputName); log.debug("compile: " + compile); log.debug("header: " + header); log.debug("copyLibs: " + copyLibs); log.debug("jarPrefix: " + jarPrefix); log.debug("properties: " + properties); log.debug("propertyFile: " + propertyFile); log.debug("propertyKeysAndValues: " + propertyKeysAndValues); log.debug("classOrPackageName: " + classOrPackageName); log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); log.debug("environmentVariables: " + environmentVariables); log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); log.debug("skip: " + skip); } if (skip) { log.info("Skipped execution of JavaCPP Builder"); return; } if (classPaths != null && classPath != null) { classPaths = Arrays.copyOf(classPaths, classPaths.length + 1); classPaths[classPaths.length - 1] = classPath; } else if (classPath != null) { classPaths = new String[] { classPath }; } if (classOrPackageNames != null && classOrPackageName != null) { classOrPackageNames = Arrays.copyOf(classOrPackageNames, classOrPackageNames.length + 1); classOrPackageNames[classOrPackageNames.length - 1] = classOrPackageName; } else if (classOrPackageName != null) { classOrPackageNames = new String[] { classOrPackageName }; } Logger logger = new Logger() { @Override public void debug(CharSequence cs) { log.debug(cs); } @Override public void info (CharSequence cs) { log.info(cs); } @Override public void warn (CharSequence cs) { log.warn(cs); } @Override public void error(CharSequence cs) { log.error(cs); } }; Builder builder = new Builder(logger) .classPaths(classPaths) .outputDirectory(outputDirectory) .outputName(outputName) .compile(compile) .header(header) .copyLibs(copyLibs) .jarPrefix(jarPrefix) .properties(properties) .propertyFile(propertyFile) .properties(propertyKeysAndValues) .classesOrPackages(classOrPackageNames) .environmentVariables(environmentVariables) .compilerOptions(compilerOptions); project.getProperties().putAll(builder.properties); File[] outputFiles = builder.build(); log.info("Successfully executed JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); } } catch (Exception e) { log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); } } #location 64 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void execute() throws MojoExecutionException { final Log log = getLog(); try { log.info("Executing JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("classPath: " + classPath); log.debug("classPaths: " + Arrays.deepToString(classPaths)); log.debug("includePath: " + includePath); log.debug("includePaths: " + Arrays.deepToString(includePaths)); log.debug("linkPath: " + linkPath); log.debug("linkPaths: " + Arrays.deepToString(linkPaths)); log.debug("preloadPath: " + preloadPath); log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths)); log.debug("outputDirectory: " + outputDirectory); log.debug("outputName: " + outputName); log.debug("compile: " + compile); log.debug("header: " + header); log.debug("copyLibs: " + copyLibs); log.debug("jarPrefix: " + jarPrefix); log.debug("properties: " + properties); log.debug("propertyFile: " + propertyFile); log.debug("propertyKeysAndValues: " + propertyKeysAndValues); log.debug("classOrPackageName: " + classOrPackageName); log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); log.debug("environmentVariables: " + environmentVariables); log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); log.debug("skip: " + skip); } if (skip) { log.info("Skipped execution of JavaCPP Builder"); return; } classPaths = merge(classPaths, classPath); classOrPackageNames = merge(classOrPackageNames, classOrPackageName); Logger logger = new Logger() { @Override public void debug(CharSequence cs) { log.debug(cs); } @Override public void info (CharSequence cs) { log.info(cs); } @Override public void warn (CharSequence cs) { log.warn(cs); } @Override public void error(CharSequence cs) { log.error(cs); } }; Builder builder = new Builder(logger) .classPaths(classPaths) .outputDirectory(outputDirectory) .outputName(outputName) .compile(compile) .header(header) .copyLibs(copyLibs) .jarPrefix(jarPrefix) .properties(properties) .propertyFile(propertyFile) .properties(propertyKeysAndValues) .classesOrPackages(classOrPackageNames) .environmentVariables(environmentVariables) .compilerOptions(compilerOptions); Properties properties = builder.properties; String separator = properties.getProperty("platform.path.separator"); for (String s : merge(includePaths, includePath)) { String v = properties.getProperty("platform.includepath", ""); properties.setProperty("platform.includepath", v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); } for (String s : merge(linkPaths, linkPath)) { String v = properties.getProperty("platform.linkpath", ""); properties.setProperty("platform.linkpath", v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); } for (String s : merge(preloadPaths, preloadPath)) { String v = properties.getProperty("platform.preloadpath", ""); properties.setProperty("platform.preloadpath", v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); } project.getProperties().putAll(properties); File[] outputFiles = builder.build(); log.info("Successfully executed JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); } } catch (Exception e) { log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static File cacheResource(URL resourceURL, String target) throws IOException { // Find appropriate subdirectory in cache for the resource ... File urlFile; try { urlFile = new File(new URI(resourceURL.toString().split("#")[0])); } catch (IllegalArgumentException | URISyntaxException e) { urlFile = new File(resourceURL.getPath()); } String name = urlFile.getName(); boolean reference = false; long size, timestamp; File cacheDir = getCacheDir(); File cacheSubdir = cacheDir.getCanonicalFile(); String s = System.getProperty("org.bytedeco.javacpp.cachedir.nosubdir", "false").toLowerCase(); boolean noSubdir = s.equals("true") || s.equals("t") || s.equals(""); URLConnection urlConnection = resourceURL.openConnection(); if (urlConnection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); File jarFileFile = new File(jarFile.getName()); File jarEntryFile = new File(jarEntry.getName()); size = jarEntry.getSize(); timestamp = jarEntry.getTime(); if (!noSubdir) { String subdirName = jarFileFile.getName(); String parentName = jarEntryFile.getParent(); if (parentName != null) { subdirName = subdirName + File.separator + parentName; } cacheSubdir = new File(cacheSubdir, subdirName); } } else { size = urlFile.length(); timestamp = urlFile.lastModified(); if (!noSubdir) { cacheSubdir = new File(cacheSubdir, urlFile.getParentFile().getName()); } } if (resourceURL.getRef() != null) { // ... get the URL fragment to let users rename library files ... String newName = resourceURL.getRef(); // ... but create a symbolic link only if the name does not change ... reference = newName.equals(name); name = newName; } File file = new File(cacheSubdir, name); File lockFile = new File(cacheDir, ".lock"); FileChannel lockChannel = null; FileLock lock = null; ReentrantLock threadLock = null; if (target != null && target.length() > 0) { // ... create symbolic link to already extracted library or ... try { Path path = file.toPath(), targetPath = Paths.get(target); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + targetPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, targetPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, targetPath); } } } } catch (IOException | RuntimeException e) { // ... (probably an unsupported operation on Windows, but DLLs never need links, // or other (filesystem?) exception: for example, // "sun.nio.fs.UnixException: No such file or directory" on File.toPath()) ... if (logger.isDebugEnabled()) { logger.debug("Failed to create symbolic link " + file + ": " + e); } return null; } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } else { if (urlFile.exists() && reference) { // ... try to create a symbolic link to the existing file, if we can, ... try { Path path = file.toPath(), urlPath = urlFile.toPath(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + urlPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, urlPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, urlPath); } } } return file; } catch (IOException | RuntimeException e) { // ... (let's try to copy the file instead, such as on Windows) ... if (logger.isDebugEnabled()) { logger.debug("Could not create symbolic link " + file + ": " + e); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } // ... check if it has not already been extracted, and if not ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... add lock to avoid two JVMs access cacheDir simultaneously and ... try { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " before extracting"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); // ... check if other JVM has extracted it before this JVM get the lock ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... extract it from our resources ... if (logger.isDebugEnabled()) { logger.debug("Extracting " + resourceURL); } file.delete(); extractResource(resourceURL, file, null, null); file.setLastModified(timestamp); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } } return file; } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code public static File cacheResource(URL resourceURL, String target) throws IOException { // Find appropriate subdirectory in cache for the resource ... File urlFile; try { urlFile = new File(new URI(resourceURL.toString().split("#")[0])); } catch (IllegalArgumentException | URISyntaxException e) { urlFile = new File(resourceURL.getPath()); } String name = urlFile.getName(); boolean reference = false; long size, timestamp; File cacheDir = getCacheDir(); File cacheSubdir = cacheDir.getCanonicalFile(); String s = System.getProperty("org.bytedeco.javacpp.cachedir.nosubdir", "false").toLowerCase(); boolean noSubdir = s.equals("true") || s.equals("t") || s.equals(""); URLConnection urlConnection = resourceURL.openConnection(); if (urlConnection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); File jarFileFile = new File(jarFile.getName()); File jarEntryFile = new File(jarEntry.getName()); size = jarEntry.getSize(); timestamp = jarEntry.getTime(); if (!noSubdir) { String subdirName = jarFileFile.getName(); String parentName = jarEntryFile.getParent(); if (parentName != null) { subdirName = subdirName + File.separator + parentName; } cacheSubdir = new File(cacheSubdir, subdirName); } } else if (urlConnection instanceof HttpURLConnection) { size = urlConnection.getContentLength(); timestamp = urlConnection.getLastModified(); if (!noSubdir) { String path = resourceURL.getHost() + resourceURL.getPath(); cacheSubdir = new File(cacheSubdir, path.substring(0, path.lastIndexOf('/') + 1)); } } else { size = urlFile.length(); timestamp = urlFile.lastModified(); if (!noSubdir) { cacheSubdir = new File(cacheSubdir, urlFile.getParentFile().getName()); } } if (resourceURL.getRef() != null) { // ... get the URL fragment to let users rename library files ... String newName = resourceURL.getRef(); // ... but create a symbolic link only if the name does not change ... reference = newName.equals(name); name = newName; } File file = new File(cacheSubdir, name); File lockFile = new File(cacheDir, ".lock"); FileChannel lockChannel = null; FileLock lock = null; ReentrantLock threadLock = null; if (target != null && target.length() > 0) { // ... create symbolic link to already extracted library or ... try { Path path = file.toPath(), targetPath = Paths.get(target); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(targetPath)) && targetPath.isAbsolute() && !targetPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + targetPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, targetPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, targetPath); } } } } catch (IOException | RuntimeException e) { // ... (probably an unsupported operation on Windows, but DLLs never need links, // or other (filesystem?) exception: for example, // "sun.nio.fs.UnixException: No such file or directory" on File.toPath()) ... if (logger.isDebugEnabled()) { logger.debug("Failed to create symbolic link " + file + ": " + e); } return null; } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } else { if (urlFile.exists() && reference) { // ... try to create a symbolic link to the existing file, if we can, ... try { Path path = file.toPath(), urlPath = urlFile.toPath(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " to create symbolic link"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); if ((!file.exists() || !Files.isSymbolicLink(path) || !Files.readSymbolicLink(path).equals(urlPath)) && urlPath.isAbsolute() && !urlPath.equals(path)) { if (logger.isDebugEnabled()) { logger.debug("Creating symbolic link " + path + " to " + urlPath); } try { file.getParentFile().mkdirs(); Files.createSymbolicLink(path, urlPath); } catch (java.nio.file.FileAlreadyExistsException e) { file.delete(); Files.createSymbolicLink(path, urlPath); } } } return file; } catch (IOException | RuntimeException e) { // ... (let's try to copy the file instead, such as on Windows) ... if (logger.isDebugEnabled()) { logger.debug("Could not create symbolic link " + file + ": " + e); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } // ... check if it has not already been extracted, and if not ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... add lock to avoid two JVMs access cacheDir simultaneously and ... try { if (logger.isDebugEnabled()) { logger.debug("Locking " + cacheDir + " before extracting"); } threadLock = new ReentrantLock(); threadLock.lock(); lockChannel = new FileOutputStream(lockFile).getChannel(); lock = lockChannel.lock(); // ... check if other JVM has extracted it before this JVM get the lock ... if (!file.exists() || file.length() != size || file.lastModified() != timestamp || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { // ... extract it from our resources ... if (logger.isDebugEnabled()) { logger.debug("Extracting " + resourceURL); } file.delete(); extractResource(resourceURL, file, null, null); file.setLastModified(timestamp); } } finally { if (lock != null) { lock.release(); } if (lockChannel != null) { lockChannel.close(); } if (threadLock != null) { threadLock.unlock(); } } } } return file; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String load(Class cls) { if (!loadLibraries || cls == null) { return null; } // Find the top enclosing class, to match the library filename Properties p = (Properties)getProperties().clone(); cls = appendProperties(p, cls); // Force initialization of the class in case it needs it try { cls = Class.forName(cls.getName(), true, cls.getClassLoader()); } catch (ClassNotFoundException ex) { Error e = new NoClassDefFoundError(ex.toString()); e.initCause(ex); throw e; } // Preload native libraries desired by our class String pathSeparator = p.getProperty("path.separator"); String platformRoot = p.getProperty("platform.root"); if (platformRoot != null && !platformRoot.endsWith(File.separator)) { platformRoot += File.separator; } String preloadPath = p.getProperty("loader.preloadpath"); String preloadLibraries = p.getProperty("loader.preload"); UnsatisfiedLinkError preloadError = null; if (preloadLibraries != null) { String[] preloadPaths = preloadPath == null ? null : preloadPath.split(pathSeparator); if (preloadPaths != null && platformRoot != null) { for (int i = 0; i < preloadPaths.length; i++) { if (!new File(preloadPaths[i]).isAbsolute()) { preloadPaths[i] = platformRoot + preloadPaths[i]; } } } String[] libnames = preloadLibraries.split(pathSeparator); for (int i = 0; i < libnames.length; i++) { try { loadLibrary(cls, preloadPaths, libnames[i]); } catch (UnsatisfiedLinkError e) { preloadError = e; } } } try { return loadLibrary(cls, null, p.getProperty("loader.library")); } catch (UnsatisfiedLinkError e) { if (preloadError != null) { e.initCause(preloadError); } throw e; } } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code public static String load(Class cls) { if (!loadLibraries || cls == null) { return null; } // Find the top enclosing class, to match the library filename Properties p = (Properties)getProperties().clone(); String pathSeparator = p.getProperty("path.separator"); String platformRoot = p.getProperty("platform.root"); if (platformRoot != null && !platformRoot.endsWith(File.separator)) { platformRoot += File.separator; } cls = appendProperties(p, cls); appendProperty(p, "loader.preloadpath", pathSeparator, p.getProperty("compiler.linkpath")); appendProperty(p, "loader.preload", pathSeparator, p.getProperty("compiler.link")); // Force initialization of the class in case it needs it try { cls = Class.forName(cls.getName(), true, cls.getClassLoader()); } catch (ClassNotFoundException ex) { Error e = new NoClassDefFoundError(ex.toString()); e.initCause(ex); throw e; } // Preload native libraries desired by our class String preloadPath = p.getProperty("loader.preloadpath"); String preload = p.getProperty("loader.preload"); String[] preloadPaths = preloadPath == null ? null : preloadPath.split(pathSeparator); String[] preloads = preload == null ? null : preload .split(pathSeparator); UnsatisfiedLinkError preloadError = null; for (int i = 0; preloadPaths != null && platformRoot != null && i < preloadPaths.length; i++) { if (!new File(preloadPaths[i]).isAbsolute()) { preloadPaths[i] = platformRoot + preloadPaths[i]; } } for (int i = 0; preloads != null && i < preloads.length; i++) { try { loadLibrary(cls, preloadPaths, preloads[i]); } catch (UnsatisfiedLinkError e) { preloadError = e; } } try { return loadLibrary(cls, null, p.getProperty("loader.library")); } catch (UnsatisfiedLinkError e) { if (preloadError != null) { e.initCause(preloadError); } throw e; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean checkPlatform(Platform platform, String[] defaultNames) { if (platform == null) { return true; } if (defaultNames == null) { defaultNames = new String[0]; } String platform2 = properties.getProperty("platform"); String[][] names = { platform.value().length > 0 ? platform.value() : defaultNames, platform.not() }; boolean[] matches = { false, false }; for (int i = 0; i < names.length; i++) { for (String s : names[i]) { if (platform2.startsWith(s)) { matches[i] = true; break; } } } if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) { return true; } return false; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code boolean classes(boolean handleExceptions, boolean defineAdapters, boolean convertStrings, String loadSuffix, String baseLoadSuffix, String classPath, Class<?> ... classes) { String version = Generator.class.getPackage().getImplementationVersion(); if (version == null) { version = "unknown"; } String warning = "// Generated by JavaCPP version " + version + ": DO NOT EDIT THIS FILE"; out.println(warning); out.println(); if (out2 != null) { out2.println(warning); out2.println(); } ClassProperties clsProperties = Loader.loadProperties(classes, properties, true); for (String s : clsProperties.get("platform.pragma")) { out.println("#pragma " + s); } for (String s : clsProperties.get("platform.define")) { out.println("#define " + s); } out.println(); out.println("#ifdef _WIN32"); out.println(" #define _JAVASOFT_JNI_MD_H_"); out.println(); out.println(" #define JNIEXPORT __declspec(dllexport)"); out.println(" #define JNIIMPORT __declspec(dllimport)"); out.println(" #define JNICALL __stdcall"); out.println(); out.println(" typedef int jint;"); out.println(" typedef long long jlong;"); out.println(" typedef signed char jbyte;"); out.println("#elif defined(__GNUC__) && !defined(__ANDROID__)"); out.println(" #define _JAVASOFT_JNI_MD_H_"); out.println(); out.println(" #define JNIEXPORT __attribute__((visibility(\"default\")))"); out.println(" #define JNIIMPORT"); out.println(" #define JNICALL"); out.println(); out.println(" typedef int jint;"); out.println(" typedef long long jlong;"); out.println(" typedef signed char jbyte;"); out.println("#endif"); out.println(); out.println("#include <jni.h>"); if (out2 != null) { out2.println("#include <jni.h>"); } out.println(); out.println("#ifdef __ANDROID__"); out.println(" #include <android/log.h>"); out.println("#elif defined(__APPLE__) && defined(__OBJC__)"); out.println(" #include <TargetConditionals.h>"); out.println(" #include <Foundation/Foundation.h>"); out.println("#endif"); out.println(); out.println("#ifdef __linux__"); out.println(" #include <malloc.h>"); out.println(" #include <sys/types.h>"); out.println(" #include <sys/stat.h>"); out.println(" #include <sys/sysinfo.h>"); out.println(" #include <fcntl.h>"); out.println(" #include <unistd.h>"); out.println(" #include <dlfcn.h>"); out.println("#elif defined(__APPLE__)"); out.println(" #include <sys/types.h>"); out.println(" #include <sys/sysctl.h>"); out.println(" #include <mach/mach_init.h>"); out.println(" #include <mach/mach_host.h>"); out.println(" #include <mach/task.h>"); out.println(" #include <unistd.h>"); out.println(" #include <dlfcn.h>"); out.println("#elif defined(_WIN32)"); out.println(" #define NOMINMAX"); out.println(" #include <windows.h>"); out.println(" #include <psapi.h>"); out.println("#endif"); out.println(); out.println("#if defined(__ANDROID__) || TARGET_OS_IPHONE"); out.println(" #define NewWeakGlobalRef(obj) NewGlobalRef(obj)"); out.println(" #define DeleteWeakGlobalRef(obj) DeleteGlobalRef(obj)"); out.println("#endif"); out.println(); out.println("#include <limits.h>"); out.println("#include <stddef.h>"); out.println("#ifndef _WIN32"); out.println(" #include <stdint.h>"); out.println("#endif"); out.println("#include <stdio.h>"); out.println("#include <stdlib.h>"); out.println("#include <string.h>"); out.println("#include <exception>"); out.println("#include <memory>"); out.println("#include <new>"); if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) { out.println(); out.println("#if defined(NATIVE_ALLOCATOR) && defined(NATIVE_DEALLOCATOR)"); out.println(" void* operator new(std::size_t size, const std::nothrow_t&) throw() {"); out.println(" return NATIVE_ALLOCATOR(size);"); out.println(" }"); out.println(" void* operator new[](std::size_t size, const std::nothrow_t&) throw() {"); out.println(" return NATIVE_ALLOCATOR(size);"); out.println(" }"); out.println(" void* operator new(std::size_t size) throw(std::bad_alloc) {"); out.println(" return NATIVE_ALLOCATOR(size);"); out.println(" }"); out.println(" void* operator new[](std::size_t size) throw(std::bad_alloc) {"); out.println(" return NATIVE_ALLOCATOR(size);"); out.println(" }"); out.println(" void operator delete(void* ptr) throw() {"); out.println(" NATIVE_DEALLOCATOR(ptr);"); out.println(" }"); out.println(" void operator delete[](void* ptr) throw() {"); out.println(" NATIVE_DEALLOCATOR(ptr);"); out.println(" }"); out.println("#endif"); } out.println(); out.println("#define jlong_to_ptr(a) ((void*)(uintptr_t)(a))"); out.println("#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))"); out.println(); out.println("#if defined(_MSC_VER)"); out.println(" #define JavaCPP_noinline __declspec(noinline)"); out.println(" #define JavaCPP_hidden /* hidden by default */"); out.println("#elif defined(__GNUC__)"); out.println(" #define JavaCPP_noinline __attribute__((noinline)) __attribute__ ((unused))"); out.println(" #define JavaCPP_hidden __attribute__((visibility(\"hidden\"))) __attribute__ ((unused))"); out.println("#else"); out.println(" #define JavaCPP_noinline"); out.println(" #define JavaCPP_hidden"); out.println("#endif"); out.println(); if (loadSuffix == null) { loadSuffix = ""; String p = clsProperties.getProperty("platform.library.static", "false").toLowerCase(); if (p.equals("true") || p.equals("t") || p.equals("")) { loadSuffix = "_" + clsProperties.getProperty("platform.library"); } } if (classes != null) { List exclude = clsProperties.get("platform.exclude"); List[] include = { clsProperties.get("platform.include"), clsProperties.get("platform.cinclude") }; for (int i = 0; i < include.length; i++) { if (include[i] != null && include[i].size() > 0) { if (i == 1) { out.println("extern \"C\" {"); if (out2 != null) { out2.println("#ifdef __cplusplus"); out2.println("extern \"C\" {"); out2.println("#endif"); } } for (String s : (List<String>)include[i]) { if (exclude.contains(s)) { continue; } String line = "#include "; if (!s.startsWith("<") && !s.startsWith("\"")) { line += '"'; } line += s; if (!s.endsWith(">") && !s.endsWith("\"")) { line += '"'; } out.println(line); if (out2 != null) { out2.println(line); } } if (i == 1) { out.println("}"); if (out2 != null) { out2.println("#ifdef __cplusplus"); out2.println("}"); out2.println("#endif"); } } out.println(); } } } out.println("static JavaVM* JavaCPP_vm = NULL;"); out.println("static bool JavaCPP_haveAllocObject = false;"); out.println("static bool JavaCPP_haveNonvirtual = false;"); out.println("static const char* JavaCPP_classNames[" + jclasses.size() + "] = {"); Iterator<Class> classIterator = jclasses.iterator(); int maxMemberSize = 0; while (classIterator.hasNext()) { Class c = classIterator.next(); out.print(" \"" + c.getName().replace('.','/') + "\""); if (classIterator.hasNext()) { out.println(","); } Set<String> m = members.get(c); if (m != null && m.size() > maxMemberSize) { maxMemberSize = m.size(); } } out.println(" };"); out.println("static jclass JavaCPP_classes[" + jclasses.size() + "] = { NULL };"); out.println("static jfieldID JavaCPP_addressFID = NULL;"); out.println("static jfieldID JavaCPP_positionFID = NULL;"); out.println("static jfieldID JavaCPP_limitFID = NULL;"); out.println("static jfieldID JavaCPP_capacityFID = NULL;"); out.println("static jfieldID JavaCPP_deallocatorFID = NULL;"); out.println("static jfieldID JavaCPP_ownerAddressFID = NULL;"); out.println("static jmethodID JavaCPP_initMID = NULL;"); out.println("static jmethodID JavaCPP_arrayMID = NULL;"); out.println("static jmethodID JavaCPP_stringMID = NULL;"); out.println("static jmethodID JavaCPP_getBytesMID = NULL;"); out.println("static jmethodID JavaCPP_toStringMID = NULL;"); out.println(); out.println("static inline void JavaCPP_log(const char* fmt, ...) {"); out.println(" va_list ap;"); out.println(" va_start(ap, fmt);"); out.println("#ifdef __ANDROID__"); out.println(" __android_log_vprint(ANDROID_LOG_ERROR, \"javacpp\", fmt, ap);"); out.println("#elif defined(__APPLE__) && defined(__OBJC__)"); out.println(" NSLogv([NSString stringWithUTF8String:fmt], ap);"); out.println("#else"); out.println(" vfprintf(stderr, fmt, ap);"); out.println(" fprintf(stderr, \"\\n\");"); out.println("#endif"); out.println(" va_end(ap);"); out.println("}"); out.println(); if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) { out.println("static inline jboolean JavaCPP_trimMemory() {"); out.println("#if defined(__linux__) && !defined(__ANDROID__)"); out.println(" return (jboolean)malloc_trim(0);"); out.println("#else"); out.println(" return 0;"); out.println("#endif"); out.println("}"); out.println(); out.println("static inline jlong JavaCPP_physicalBytes() {"); out.println(" jlong size = 0;"); out.println("#ifdef __linux__"); out.println(" static int fd = open(\"/proc/self/statm\", O_RDONLY, 0);"); out.println(" if (fd >= 0) {"); out.println(" char line[256];"); out.println(" char* s;"); out.println(" int n;"); out.println(" lseek(fd, 0, SEEK_SET);"); out.println(" if ((n = read(fd, line, sizeof(line))) > 0 && (s = (char*)memchr(line, ' ', n)) != NULL) {"); out.println(" size = (jlong)(atoll(s + 1) * getpagesize());"); out.println(" }"); out.println(" // no close(fd);"); out.println(" }"); out.println("#elif defined(__APPLE__)"); out.println(" task_basic_info info;"); out.println(" mach_msg_type_number_t count = TASK_BASIC_INFO_COUNT;"); out.println(" if (task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&info, &count) == KERN_SUCCESS) {"); out.println(" size = (jlong)info.resident_size;"); out.println(" }"); out.println("#elif defined(_WIN32)"); out.println(" PROCESS_MEMORY_COUNTERS counters;"); out.println(" if (GetProcessMemoryInfo(GetCurrentProcess(), &counters, sizeof(counters))) {"); out.println(" size = (jlong)counters.WorkingSetSize;"); out.println(" }"); out.println("#endif"); out.println(" return size;"); out.println("}"); out.println(); out.println("static inline jlong JavaCPP_totalPhysicalBytes() {"); out.println(" jlong size = 0;"); out.println("#ifdef __linux__"); out.println(" struct sysinfo info;"); out.println(" if (sysinfo(&info) == 0) {"); out.println(" size = info.totalram;"); out.println(" }"); out.println("#elif defined(__APPLE__)"); out.println(" size_t length = sizeof(size);"); out.println(" sysctlbyname(\"hw.memsize\", &size, &length, NULL, 0);"); out.println("#elif defined(_WIN32)"); out.println(" MEMORYSTATUSEX status;"); out.println(" status.dwLength = sizeof(status);"); out.println(" if (GlobalMemoryStatusEx(&status)) {"); out.println(" size = status.ullTotalPhys;"); out.println(" }"); out.println("#endif"); out.println(" return size;"); out.println("}"); out.println(); out.println("static inline jlong JavaCPP_availablePhysicalBytes() {"); out.println(" jlong size = 0;"); out.println("#ifdef __linux__"); out.println(" int fd = open(\"/proc/meminfo\", O_RDONLY, 0);"); out.println(" if (fd >= 0) {"); out.println(" char temp[4096];"); out.println(" char *s;"); out.println(" int n;"); out.println(" if ((n = read(fd, temp, sizeof(temp))) > 0 && (s = (char*)memmem(temp, n, \"MemAvailable:\", 13)) != NULL) {"); out.println(" size = (jlong)(atoll(s + 13) * 1024);"); out.println(" }"); out.println(" close(fd);"); out.println(" }"); out.println(" if (size == 0) {"); out.println(" struct sysinfo info;"); out.println(" if (sysinfo(&info) == 0) {"); out.println(" size = info.freeram;"); out.println(" }"); out.println(" }"); out.println("#elif defined(__APPLE__)"); out.println(" vm_statistics_data_t info;"); out.println(" mach_msg_type_number_t count = HOST_VM_INFO_COUNT;"); out.println(" if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&info, &count) == KERN_SUCCESS) {"); out.println(" size = (jlong)info.free_count * getpagesize();"); out.println(" }"); out.println("#elif defined(_WIN32)"); out.println(" MEMORYSTATUSEX status;"); out.println(" status.dwLength = sizeof(status);"); out.println(" if (GlobalMemoryStatusEx(&status)) {"); out.println(" size = status.ullAvailPhys;"); out.println(" }"); out.println("#endif"); out.println(" return size;"); out.println("}"); out.println(); out.println("static inline jint JavaCPP_totalProcessors() {"); out.println(" jint total = 0;"); out.println("#ifdef __linux__"); out.println(" total = sysconf(_SC_NPROCESSORS_CONF);"); out.println("#elif defined(__APPLE__)"); out.println(" size_t length = sizeof(total);"); out.println(" sysctlbyname(\"hw.logicalcpu_max\", &total, &length, NULL, 0);"); out.println("#elif defined(_WIN32)"); out.println(" SYSTEM_INFO info;"); out.println(" GetSystemInfo(&info);"); out.println(" total = info.dwNumberOfProcessors;"); out.println("#endif"); out.println(" return total;"); out.println("}"); out.println(); out.println("static inline jint JavaCPP_totalCores() {"); out.println(" jint total = 0;"); out.println("#ifdef __linux__"); out.println(" const int n = sysconf(_SC_NPROCESSORS_CONF);"); out.println(" int pids[n], cids[n];"); out.println(" for (int i = 0; i < n; i++) {"); out.println(" int fd = 0, pid = 0, cid = 0;"); out.println(" char temp[256];"); out.println(" sprintf(temp, \"/sys/devices/system/cpu/cpu%d/topology/physical_package_id\", i);"); out.println(" if ((fd = open(temp, O_RDONLY, 0)) >= 0) {"); out.println(" if (read(fd, temp, sizeof(temp)) > 0) {"); out.println(" pid = atoi(temp);"); out.println(" }"); out.println(" close(fd);"); out.println(" }"); out.println(" sprintf(temp, \"/sys/devices/system/cpu/cpu%d/topology/core_id\", i);"); out.println(" if ((fd = open(temp, O_RDONLY, 0)) >= 0) {"); out.println(" if (read(fd, temp, sizeof(temp)) > 0) {"); out.println(" cid = atoi(temp);"); out.println(" }"); out.println(" close(fd);"); out.println(" }"); out.println(" bool found = false;"); out.println(" for (int j = 0; j < total; j++) {"); out.println(" if (pids[j] == pid && cids[j] == cid) {"); out.println(" found = true;"); out.println(" break;"); out.println(" }"); out.println(" }"); out.println(" if (!found) {"); out.println(" pids[total] = pid;"); out.println(" cids[total] = cid;"); out.println(" total++;"); out.println(" }"); out.println(" }"); out.println("#elif defined(__APPLE__)"); out.println(" size_t length = sizeof(total);"); out.println(" sysctlbyname(\"hw.physicalcpu_max\", &total, &length, NULL, 0);"); out.println("#elif defined(_WIN32)"); out.println(" SYSTEM_LOGICAL_PROCESSOR_INFORMATION *info = NULL;"); out.println(" DWORD length = 0;"); out.println(" BOOL success = GetLogicalProcessorInformation(info, &length);"); out.println(" while (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {"); out.println(" info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION*)realloc(info, length);"); out.println(" success = GetLogicalProcessorInformation(info, &length);"); out.println(" }"); out.println(" if (success && info != NULL) {"); out.println(" length /= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);"); out.println(" for (DWORD i = 0; i < length; i++) {"); out.println(" if (info[i].Relationship == RelationProcessorCore) {"); out.println(" total++;"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" free(info);"); out.println("#endif"); out.println(" return total;"); out.println("}"); out.println(); out.println("static inline jint JavaCPP_totalChips() {"); out.println(" jint total = 0;"); out.println("#ifdef __linux__"); out.println(" const int n = sysconf(_SC_NPROCESSORS_CONF);"); out.println(" int pids[n];"); out.println(" for (int i = 0; i < n; i++) {"); out.println(" int fd = 0, pid = 0;"); out.println(" char temp[256];"); out.println(" sprintf(temp, \"/sys/devices/system/cpu/cpu%d/topology/physical_package_id\", i);"); out.println(" if ((fd = open(temp, O_RDONLY, 0)) >= 0) {"); out.println(" if (read(fd, temp, sizeof(temp)) > 0) {"); out.println(" pid = atoi(temp);"); out.println(" }"); out.println(" close(fd);"); out.println(" }"); out.println(" bool found = false;"); out.println(" for (int j = 0; j < total; j++) {"); out.println(" if (pids[j] == pid) {"); out.println(" found = true;"); out.println(" break;"); out.println(" }"); out.println(" }"); out.println(" if (!found) {"); out.println(" pids[total] = pid;"); out.println(" total++;"); out.println(" }"); out.println(" }"); out.println("#elif defined(__APPLE__)"); out.println(" size_t length = sizeof(total);"); out.println(" sysctlbyname(\"hw.packages\", &total, &length, NULL, 0);"); out.println("#elif defined(_WIN32)"); out.println(" SYSTEM_LOGICAL_PROCESSOR_INFORMATION *info = NULL;"); out.println(" DWORD length = 0;"); out.println(" BOOL success = GetLogicalProcessorInformation(info, &length);"); out.println(" while (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {"); out.println(" info = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION*)realloc(info, length);"); out.println(" success = GetLogicalProcessorInformation(info, &length);"); out.println(" }"); out.println(" if (success && info != NULL) {"); out.println(" length /= sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);"); out.println(" for (DWORD i = 0; i < length; i++) {"); out.println(" if (info[i].Relationship == RelationProcessorPackage) {"); out.println(" total++;"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" free(info);"); out.println("#endif"); out.println(" return total;"); out.println("}"); out.println(); out.println("static inline void* JavaCPP_addressof(const char* name) {"); out.println(" void *address = NULL;"); out.println("#if defined(__linux__) || defined(__APPLE__)"); out.println(" address = dlsym(RTLD_DEFAULT, name);"); out.println("#elif defined(_WIN32)"); out.println(" HANDLE process = GetCurrentProcess();"); out.println(" HMODULE *modules = NULL;"); out.println(" DWORD length = 0, needed = 0;"); out.println(" BOOL success = EnumProcessModules(process, modules, length, &needed);"); out.println(" while (success && needed > length) {"); out.println(" modules = (HMODULE*)realloc(modules, length = needed);"); out.println(" success = EnumProcessModules(process, modules, length, &needed);"); out.println(" }"); out.println(" if (success && modules != NULL) {"); out.println(" length = needed / sizeof(HMODULE);"); out.println(" for (DWORD i = 0; i < length; i++) {"); out.println(" address = (void*)GetProcAddress(modules[i], name);"); out.println(" if (address != NULL) {"); out.println(" break;"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" free(modules);"); out.println("#endif"); out.println(" return address;"); out.println("}"); out.println(); } out.println("static JavaCPP_noinline jclass JavaCPP_getClass(JNIEnv* env, int i) {"); out.println(" if (JavaCPP_classes[i] == NULL && env->PushLocalFrame(1) == 0) {"); out.println(" jclass cls = env->FindClass(JavaCPP_classNames[i]);"); out.println(" if (cls == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error loading class %s.\", JavaCPP_classNames[i]);"); out.println(" return NULL;"); out.println(" }"); out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);"); out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);"); out.println(" return NULL;"); out.println(" }"); out.println(" env->PopLocalFrame(NULL);"); out.println(" }"); out.println(" return JavaCPP_classes[i];"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jfieldID JavaCPP_getFieldID(JNIEnv* env, int i, const char* name, const char* sig) {"); out.println(" jclass cls = JavaCPP_getClass(env, i);"); out.println(" if (cls == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" jfieldID fid = env->GetFieldID(cls, name, sig);"); out.println(" if (fid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting field ID of %s/%s\", JavaCPP_classNames[i], name);"); out.println(" return NULL;"); out.println(" }"); out.println(" return fid;"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jmethodID JavaCPP_getMethodID(JNIEnv* env, int i, const char* name, const char* sig) {"); out.println(" jclass cls = JavaCPP_getClass(env, i);"); out.println(" if (cls == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" jmethodID mid = env->GetMethodID(cls, name, sig);"); out.println(" if (mid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting method ID of %s/%s\", JavaCPP_classNames[i], name);"); out.println(" return NULL;"); out.println(" }"); out.println(" return mid;"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jmethodID JavaCPP_getStaticMethodID(JNIEnv* env, int i, const char* name, const char* sig) {"); out.println(" jclass cls = JavaCPP_getClass(env, i);"); out.println(" if (cls == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" jmethodID mid = env->GetStaticMethodID(cls, name, sig);"); out.println(" if (mid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting static method ID of %s/%s\", JavaCPP_classNames[i], name);"); out.println(" return NULL;"); out.println(" }"); out.println(" return mid;"); out.println("}"); out.println(); out.println("static JavaCPP_noinline jobject JavaCPP_createPointer(JNIEnv* env, int i, jclass cls = NULL) {"); out.println(" if (cls == NULL && (cls = JavaCPP_getClass(env, i)) == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" if (JavaCPP_haveAllocObject) {"); out.println(" return env->AllocObject(cls);"); out.println(" } else {"); out.println(" jmethodID mid = env->GetMethodID(cls, \"<init>\", \"(Lorg/bytedeco/javacpp/Pointer;)V\");"); out.println(" if (mid == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting Pointer constructor of %s, while VM does not support AllocObject()\", JavaCPP_classNames[i]);"); out.println(" return NULL;"); out.println(" }"); out.println(" return env->NewObject(cls, mid, NULL);"); out.println(" }"); out.println("}"); out.println(); out.println("static JavaCPP_noinline void JavaCPP_initPointer(JNIEnv* env, jobject obj, const void* ptr, jlong size, void* owner, void (*deallocator)(void*)) {"); out.println(" if (deallocator != NULL) {"); out.println(" jvalue args[4];"); out.println(" args[0].j = ptr_to_jlong(ptr);"); out.println(" args[1].j = size;"); out.println(" args[2].j = ptr_to_jlong(owner);"); out.println(" args[3].j = ptr_to_jlong(deallocator);"); out.println(" if (JavaCPP_haveNonvirtual) {"); out.println(" env->CallNonvirtualVoidMethodA(obj, JavaCPP_getClass(env, " + jclasses.index(Pointer.class) + "), JavaCPP_initMID, args);"); out.println(" } else {"); out.println(" env->CallVoidMethodA(obj, JavaCPP_initMID, args);"); out.println(" }"); out.println(" } else {"); out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(ptr));"); out.println(" env->SetLongField(obj, JavaCPP_limitFID, (jlong)size);"); out.println(" env->SetLongField(obj, JavaCPP_capacityFID, (jlong)size);"); out.println(" }"); out.println("}"); out.println(); if (handleExceptions || convertStrings) { out.println("static JavaCPP_noinline jstring JavaCPP_createString(JNIEnv* env, const char* ptr) {"); out.println(" if (ptr == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println("#ifdef MODIFIED_UTF8_STRING"); out.println(" return env->NewStringUTF(ptr);"); out.println("#else"); out.println(" size_t length = strlen(ptr);"); out.println(" jbyteArray bytes = env->NewByteArray(length < INT_MAX ? length : INT_MAX);"); out.println(" env->SetByteArrayRegion(bytes, 0, length < INT_MAX ? length : INT_MAX, (signed char*)ptr);"); out.println(" return (jstring)env->NewObject(JavaCPP_getClass(env, " + jclasses.index(String.class) + "), JavaCPP_stringMID, bytes);"); out.println("#endif"); out.println("}"); out.println(); } if (convertStrings) { out.println("static JavaCPP_noinline const char* JavaCPP_getStringBytes(JNIEnv* env, jstring str) {"); out.println(" if (str == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println("#ifdef MODIFIED_UTF8_STRING"); out.println(" return env->GetStringUTFChars(str, NULL);"); out.println("#else"); out.println(" jbyteArray bytes = (jbyteArray)env->CallObjectMethod(str, JavaCPP_getBytesMID);"); out.println(" if (bytes == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error getting bytes from string.\");"); out.println(" return NULL;"); out.println(" }"); out.println(" jsize length = env->GetArrayLength(bytes);"); out.println(" signed char* ptr = new (std::nothrow) signed char[length + 1];"); out.println(" if (ptr != NULL) {"); out.println(" env->GetByteArrayRegion(bytes, 0, length, ptr);"); out.println(" ptr[length] = 0;"); out.println(" }"); out.println(" return (const char*)ptr;"); out.println("#endif"); out.println("}"); out.println(); out.println("static JavaCPP_noinline void JavaCPP_releaseStringBytes(JNIEnv* env, jstring str, const char* ptr) {"); out.println("#ifdef MODIFIED_UTF8_STRING"); out.println(" if (str != NULL) {"); out.println(" env->ReleaseStringUTFChars(str, ptr);"); out.println(" }"); out.println("#else"); out.println(" delete[] ptr;"); out.println("#endif"); out.println("}"); out.println(); } out.println("class JavaCPP_hidden JavaCPP_exception : public std::exception {"); out.println("public:"); out.println(" JavaCPP_exception(const char* str) throw() {"); out.println(" if (str == NULL) {"); out.println(" strcpy(msg, \"Unknown exception.\");"); out.println(" } else {"); out.println(" strncpy(msg, str, sizeof(msg));"); out.println(" msg[sizeof(msg) - 1] = 0;"); out.println(" }"); out.println(" }"); out.println(" virtual const char* what() const throw() { return msg; }"); out.println(" char msg[1024];"); out.println("};"); out.println(); if (handleExceptions) { out.println("#ifndef GENERIC_EXCEPTION_CLASS"); out.println("#define GENERIC_EXCEPTION_CLASS std::exception"); out.println("#endif"); out.println("static JavaCPP_noinline jthrowable JavaCPP_handleException(JNIEnv* env, int i) {"); out.println(" jstring str = NULL;"); out.println(" try {"); out.println(" throw;"); out.println(" } catch (GENERIC_EXCEPTION_CLASS& e) {"); out.println(" str = JavaCPP_createString(env, e.what());"); out.println(" } catch (...) {"); out.println(" str = JavaCPP_createString(env, \"Unknown exception.\");"); out.println(" }"); out.println(" jmethodID mid = JavaCPP_getMethodID(env, i, \"<init>\", \"(Ljava/lang/String;)V\");"); out.println(" if (mid == NULL) {"); out.println(" return NULL;"); out.println(" }"); out.println(" return (jthrowable)env->NewObject(JavaCPP_getClass(env, i), mid, str);"); out.println("}"); out.println(); } Class deallocator, nativeDeallocator; try { deallocator = Class.forName(Pointer.class.getName() + "$Deallocator", false, Pointer.class.getClassLoader()); nativeDeallocator = Class.forName(Pointer.class.getName() + "$NativeDeallocator", false, Pointer.class.getClassLoader()); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } if (defineAdapters) { out.println("static JavaCPP_noinline void* JavaCPP_getPointerOwner(JNIEnv* env, jobject obj) {"); out.println(" if (obj != NULL) {"); out.println(" jobject deallocator = env->GetObjectField(obj, JavaCPP_deallocatorFID);"); out.println(" if (deallocator != NULL && env->IsInstanceOf(deallocator, JavaCPP_getClass(env, " + jclasses.index(nativeDeallocator) + "))) {"); out.println(" return jlong_to_ptr(env->GetLongField(deallocator, JavaCPP_ownerAddressFID));"); out.println(" }"); out.println(" }"); out.println(" return NULL;"); out.println("}"); out.println(); out.println("#include <vector>"); out.println("template<typename P, typename T = P> class JavaCPP_hidden VectorAdapter {"); out.println("public:"); out.println(" VectorAdapter(const P* ptr, typename std::vector<T>::size_type size, void* owner) : ptr((P*)ptr), size(size), owner(owner),"); out.println(" vec2(ptr ? std::vector<T>((P*)ptr, (P*)ptr + size) : std::vector<T>()), vec(vec2) { }"); out.println(" VectorAdapter(const std::vector<T>& vec) : ptr(0), size(0), owner(0), vec2(vec), vec(vec2) { }"); out.println(" VectorAdapter( std::vector<T>& vec) : ptr(0), size(0), owner(0), vec(vec) { }"); out.println(" VectorAdapter(const std::vector<T>* vec) : ptr(0), size(0), owner(0), vec(*(std::vector<T>*)vec) { }"); out.println(" void assign(P* ptr, typename std::vector<T>::size_type size, void* owner) {"); out.println(" this->ptr = ptr;"); out.println(" this->size = size;"); out.println(" this->owner = owner;"); out.println(" vec.assign(ptr, ptr + size);"); out.println(" }"); out.println(" static void deallocate(void* owner) { operator delete(owner); }"); out.println(" operator P*() {"); out.println(" if (vec.size() > size) {"); out.println(" ptr = (P*)(operator new(sizeof(P) * vec.size(), std::nothrow_t()));"); out.println(" }"); out.println(" if (ptr) {"); out.println(" std::copy(vec.begin(), vec.end(), ptr);"); out.println(" }"); out.println(" size = vec.size();"); out.println(" owner = ptr;"); out.println(" return ptr;"); out.println(" }"); out.println(" operator const P*() { return &vec[0]; }"); out.println(" operator std::vector<T>&() { return vec; }"); out.println(" operator std::vector<T>*() { return ptr ? &vec : 0; }"); out.println(" P* ptr;"); out.println(" typename std::vector<T>::size_type size;"); out.println(" void* owner;"); out.println(" std::vector<T> vec2;"); out.println(" std::vector<T>& vec;"); out.println("};"); out.println(); out.println("#include <string>"); out.println("class JavaCPP_hidden StringAdapter {"); out.println("public:"); out.println(" StringAdapter(const char* ptr, size_t size, void* owner) : ptr((char*)ptr), size(size), owner(owner),"); out.println(" str2(ptr ? (char*)ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0), str(str2) { }"); out.println(" StringAdapter(const signed char* ptr, size_t size, void* owner) : ptr((char*)ptr), size(size), owner(owner),"); out.println(" str2(ptr ? (char*)ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0), str(str2) { }"); out.println(" StringAdapter(const unsigned char* ptr, size_t size, void* owner) : ptr((char*)ptr), size(size), owner(owner),"); out.println(" str2(ptr ? (char*)ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0), str(str2) { }"); out.println(" StringAdapter(const std::string& str) : ptr(0), size(0), owner(0), str2(str), str(str2) { }"); out.println(" StringAdapter( std::string& str) : ptr(0), size(0), owner(0), str(str) { }"); out.println(" StringAdapter(const std::string* str) : ptr(0), size(0), owner(0), str(*(std::string*)str) { }"); out.println(" void assign(char* ptr, size_t size, void* owner) {"); out.println(" this->ptr = ptr;"); out.println(" this->size = size;"); out.println(" this->owner = owner;"); out.println(" str.assign(ptr ? ptr : \"\", ptr ? (size > 0 ? size : strlen((char*)ptr)) : 0);"); out.println(" }"); out.println(" void assign(const char* ptr, size_t size, void* owner) { assign((char*)ptr, size, owner); }"); out.println(" void assign(const signed char* ptr, size_t size, void* owner) { assign((char*)ptr, size, owner); }"); out.println(" void assign(const unsigned char* ptr, size_t size, void* owner) { assign((char*)ptr, size, owner); }"); out.println(" static void deallocate(void* owner) { delete[] (char*)owner; }"); out.println(" operator char*() {"); out.println(" const char* data = str.data();"); out.println(" if (str.size() > size) {"); out.println(" ptr = new (std::nothrow) char[str.size()+1];"); out.println(" if (ptr) memset(ptr, 0, str.size()+1);"); out.println(" }"); out.println(" if (ptr && memcmp(ptr, data, str.size()) != 0) {"); out.println(" memcpy(ptr, data, str.size());"); out.println(" if (size > str.size()) ptr[str.size()] = 0;"); out.println(" }"); out.println(" size = str.size();"); out.println(" owner = ptr;"); out.println(" return ptr;"); out.println(" }"); out.println(" operator signed char*() { return (signed char*)(operator char*)(); }"); out.println(" operator unsigned char*() { return (unsigned char*)(operator char*)(); }"); out.println(" operator const char*() { return str.c_str(); }"); out.println(" operator const signed char*() { return (signed char*)str.c_str(); }"); out.println(" operator const unsigned char*() { return (unsigned char*)str.c_str(); }"); out.println(" operator std::string&() { return str; }"); out.println(" operator std::string*() { return ptr ? &str : 0; }"); out.println(" char* ptr;"); out.println(" size_t size;"); out.println(" void* owner;"); out.println(" std::string str2;"); out.println(" std::string& str;"); out.println("};"); out.println(); out.println("#ifdef SHARED_PTR_NAMESPACE"); out.println("template<class T> class SharedPtrAdapter {"); out.println("public:"); out.println(" typedef SHARED_PTR_NAMESPACE::shared_ptr<T> S;"); out.println(" SharedPtrAdapter(const T* ptr, size_t size, void* owner) : ptr((T*)ptr), size(size), owner(owner),"); out.println(" sharedPtr2(owner != NULL && owner != ptr ? *(S*)owner : S((T*)ptr)), sharedPtr(sharedPtr2) { }"); out.println(" SharedPtrAdapter(const S& sharedPtr) : ptr(0), size(0), owner(0), sharedPtr2(sharedPtr), sharedPtr(sharedPtr2) { }"); out.println(" SharedPtrAdapter( S& sharedPtr) : ptr(0), size(0), owner(0), sharedPtr(sharedPtr) { }"); out.println(" SharedPtrAdapter(const S* sharedPtr) : ptr(0), size(0), owner(0), sharedPtr(*(S*)sharedPtr) { }"); out.println(" void assign(T* ptr, size_t size, S* owner) {"); out.println(" this->ptr = ptr;"); out.println(" this->size = size;"); out.println(" this->owner = owner;"); out.println(" this->sharedPtr = owner != NULL && owner != ptr ? *(S*)owner : S((T*)ptr);"); out.println(" }"); out.println(" static void deallocate(void* owner) { delete (S*)owner; }"); out.println(" operator typename SHARED_PTR_NAMESPACE::remove_const<T>::type*() {"); out.println(" ptr = sharedPtr.get();"); out.println(" if (owner == NULL || owner == ptr) {"); out.println(" owner = new S(sharedPtr);"); out.println(" }"); out.println(" return ptr;"); out.println(" }"); out.println(" operator const T*() { return sharedPtr.get(); }"); out.println(" operator S&() { return sharedPtr; }"); out.println(" operator S*() { return &sharedPtr; }"); out.println(" T* ptr;"); out.println(" size_t size;"); out.println(" void* owner;"); out.println(" S sharedPtr2;"); out.println(" S& sharedPtr;"); out.println("};"); out.println("#endif"); out.println(); out.println("#ifdef UNIQUE_PTR_NAMESPACE"); out.println("template<class T> class UniquePtrAdapter {"); out.println("public:"); out.println(" typedef UNIQUE_PTR_NAMESPACE::unique_ptr<T> U;"); out.println(" UniquePtrAdapter(const T* ptr, size_t size, void* owner) : ptr((T*)ptr), size(size), owner(owner),"); out.println(" uniquePtr2(owner != NULL && owner != ptr ? U() : U((T*)ptr)),"); out.println(" uniquePtr(owner != NULL && owner != ptr ? *(U*)owner : uniquePtr2) { }"); out.println(" UniquePtrAdapter(const U& uniquePtr) : ptr(0), size(0), owner(0), uniquePtr((U&)uniquePtr) { }"); out.println(" UniquePtrAdapter( U& uniquePtr) : ptr(0), size(0), owner(0), uniquePtr(uniquePtr) { }"); out.println(" UniquePtrAdapter(const U* uniquePtr) : ptr(0), size(0), owner(0), uniquePtr(*(U*)uniquePtr) { }"); out.println(" void assign(T* ptr, size_t size, U* owner) {"); out.println(" this->ptr = ptr;"); out.println(" this->size = size;"); out.println(" this->owner = owner;"); out.println(" this->uniquePtr = owner != NULL && owner != ptr ? *(U*)owner : U((T*)ptr);"); out.println(" }"); out.println(" static void deallocate(void* owner) { delete (U*)owner; }"); out.println(" operator typename UNIQUE_PTR_NAMESPACE::remove_const<T>::type*() {"); out.println(" ptr = uniquePtr.get();"); out.println(" if (owner == NULL || owner == ptr) {"); out.println(" owner = new U(UNIQUE_PTR_NAMESPACE::move(uniquePtr));"); out.println(" }"); out.println(" return ptr;"); out.println(" }"); out.println(" operator const T*() { return uniquePtr.get(); }"); out.println(" operator U&() { return uniquePtr; }"); out.println(" operator U*() { return &uniquePtr; }"); out.println(" T* ptr;"); out.println(" size_t size;"); out.println(" void* owner;"); out.println(" U uniquePtr2;"); out.println(" U& uniquePtr;"); out.println("};"); out.println("#endif"); out.println(); } if (!functions.isEmpty() || !virtualFunctions.isEmpty()) { out.println("static JavaCPP_noinline void JavaCPP_detach(bool detach) {"); out.println("#ifndef NO_JNI_DETACH_THREAD"); out.println(" if (detach && JavaCPP_vm->DetachCurrentThread() != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not detach the JavaVM from the current thread.\");"); out.println(" }"); out.println("#endif"); out.println("}"); out.println(); if (!loadSuffix.isEmpty()) { out.println("extern \"C\" {"); out.println("JNIEXPORT jint JNICALL JNI_OnLoad" + loadSuffix + "(JavaVM* vm, void* reserved);"); out.println("}"); } out.println("static JavaCPP_noinline bool JavaCPP_getEnv(JNIEnv** env) {"); out.println(" bool attached = false;"); out.println(" JavaVM *vm = JavaCPP_vm;"); out.println(" if (vm == NULL) {"); if (out2 != null) { out.println("#if !defined(__ANDROID__) && !TARGET_OS_IPHONE"); out.println(" int size = 1;"); out.println(" if (JNI_GetCreatedJavaVMs(&vm, 1, &size) != JNI_OK || size == 0) {"); out.println("#endif"); } out.println(" JavaCPP_log(\"Could not get any created JavaVM.\");"); out.println(" *env = NULL;"); out.println(" return false;"); if (out2 != null) { out.println("#if !defined(__ANDROID__) && !TARGET_OS_IPHONE"); out.println(" }"); out.println("#endif"); } out.println(" }"); out.println(" if (vm->GetEnv((void**)env, " + JNI_VERSION + ") != JNI_OK) {"); out.println(" struct {"); out.println(" JNIEnv **env;"); out.println(" operator JNIEnv**() { return env; } // Android JNI"); out.println(" operator void**() { return (void**)env; } // standard JNI"); out.println(" } env2 = { env };"); out.println(" if (vm->AttachCurrentThread(env2, NULL) != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not attach the JavaVM to the current thread.\");"); out.println(" *env = NULL;"); out.println(" return false;"); out.println(" }"); out.println(" attached = true;"); out.println(" }"); out.println(" if (JavaCPP_vm == NULL) {"); out.println(" if (JNI_OnLoad" + loadSuffix + "(vm, NULL) < 0) {"); out.println(" JavaCPP_detach(attached);"); out.println(" *env = NULL;"); out.println(" return false;"); out.println(" }"); out.println(" }"); out.println(" return attached;"); out.println("}"); out.println(); } for (Class c : functions) { String[] typeName = cppTypeName(c); String[] returnConvention = typeName[0].split("\\("); returnConvention[1] = constValueTypeName(returnConvention[1]); String parameterDeclaration = typeName[1].substring(1); String instanceTypeName = functionClassName(c); out.println("struct JavaCPP_hidden " + instanceTypeName + " {"); out.println(" " + instanceTypeName + "() : ptr(NULL), obj(NULL) { }"); if (parameterDeclaration != null && parameterDeclaration.length() > 0) { out.println(" " + returnConvention[0] + "operator()" + parameterDeclaration + ";"); } out.println(" " + typeName[0] + "ptr" + typeName[1] + ";"); out.println(" jobject obj; static jmethodID mid;"); out.println("};"); out.println("jmethodID " + instanceTypeName + "::mid = NULL;"); } out.println(); for (Class c : jclasses) { Set<String> functionList = virtualFunctions.get(c); if (functionList == null) { continue; } Set<String> memberList = virtualMembers.get(c); String[] typeName = cppTypeName(c); String valueTypeName = valueTypeName(typeName); String subType = "JavaCPP_" + mangle(valueTypeName); out.println("class JavaCPP_hidden " + subType + " : public " + valueTypeName + " {"); out.println("public:"); out.println(" jobject obj;"); for (String s : functionList) { out.println(" static jmethodID " + s + ";"); } out.println(); for (String s : memberList) { out.println(s); } out.println("};"); for (String s : functionList) { out.println("jmethodID " + subType + "::" + s + " = NULL;"); } } out.println(); for (String s : callbacks) { out.println(s); } out.println(); for (Class c : deallocators) { String name = "JavaCPP_" + mangle(c.getName()); out.print("static void " + name + "_deallocate(void *p) { "); if (FunctionPointer.class.isAssignableFrom(c)) { String typeName = functionClassName(c) + "*"; out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((jweak)((" + typeName + ")p)->obj); delete (" + typeName + ")p; JavaCPP_detach(a); }"); } else if (virtualFunctions.containsKey(c)) { String[] typeName = cppTypeName(c); String valueTypeName = valueTypeName(typeName); String subType = "JavaCPP_" + mangle(valueTypeName); out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((jweak)((" + subType + "*)p)->obj); delete (" + subType + "*)p; JavaCPP_detach(a); }"); } else { String[] typeName = cppTypeName(c); out.println("delete (" + typeName[0] + typeName[1] + ")p; }"); } } for (Class c : arrayDeallocators) { String name = "JavaCPP_" + mangle(c.getName()); String[] typeName = cppTypeName(c); out.println("static void " + name + "_deallocateArray(void* p) { delete[] (" + typeName[0] + typeName[1] + ")p; }"); } out.println(); out.println("static const char* JavaCPP_members[" + jclasses.size() + "][" + maxMemberSize + 1 + "] = {"); classIterator = jclasses.iterator(); while (classIterator.hasNext()) { out.print(" { "); Set<String> m = members.get(classIterator.next()); Iterator<String> memberIterator = m == null ? null : m.iterator(); if (memberIterator == null || !memberIterator.hasNext()) { out.print("NULL"); } else while (memberIterator.hasNext()) { out.print("\"" + memberIterator.next() + "\""); if (memberIterator.hasNext()) { out.print(", "); } } out.print(" }"); if (classIterator.hasNext()) { out.println(","); } } out.println(" };"); out.println("static int JavaCPP_offsets[" + jclasses.size() + "][" + maxMemberSize + 1 + "] = {"); classIterator = jclasses.iterator(); while (classIterator.hasNext()) { out.print(" { "); Class c = classIterator.next(); Set<String> m = members.get(c); Iterator<String> memberIterator = m == null ? null : m.iterator(); if (memberIterator == null || !memberIterator.hasNext()) { out.print("-1"); } else while (memberIterator.hasNext()) { String[] typeName = cppTypeName(c); String valueTypeName = valueTypeName(typeName); String memberName = memberIterator.next(); if ("sizeof".equals(memberName)) { if ("void".equals(valueTypeName)) { valueTypeName = "void*"; } out.print("sizeof(" + valueTypeName + ")"); } else { out.print("offsetof(" + valueTypeName + ", " + memberName + ")"); } if (memberIterator.hasNext()) { out.print(", "); } } out.print(" }"); if (classIterator.hasNext()) { out.println(","); } } out.println(" };"); out.print("static int JavaCPP_memberOffsetSizes[" + jclasses.size() + "] = { "); classIterator = jclasses.iterator(); while (classIterator.hasNext()) { Set<String> m = members.get(classIterator.next()); out.print(m == null ? 1 : m.size()); if (classIterator.hasNext()) { out.print(", "); } } out.println(" };"); out.println(); out.println("extern \"C\" {"); if (out2 != null) { out2.println(); out2.println("#ifdef __cplusplus"); out2.println("extern \"C\" {"); out2.println("#endif"); out2.println("JNIIMPORT int JavaCPP_init" + loadSuffix + "(int argc, const char *argv[]);"); out.println(); out.println("JNIEXPORT int JavaCPP_init" + loadSuffix + "(int argc, const char *argv[]) {"); out.println("#if defined(__ANDROID__) || TARGET_OS_IPHONE"); out.println(" return JNI_OK;"); out.println("#else"); out.println(" if (JavaCPP_vm != NULL) {"); out.println(" return JNI_OK;"); out.println(" }"); out.println(" int err;"); out.println(" JavaVM *vm;"); out.println(" JNIEnv *env;"); out.println(" int nOptions = 1 + (argc > 255 ? 255 : argc);"); out.println(" JavaVMOption options[256] = { { NULL } };"); out.println(" options[0].optionString = (char*)\"-Djava.class.path=" + classPath.replace('\\', '/') + "\";"); out.println(" for (int i = 1; i < nOptions && argv != NULL; i++) {"); out.println(" options[i].optionString = (char*)argv[i - 1];"); out.println(" }"); out.println(" JavaVMInitArgs vm_args = { " + JNI_VERSION + ", nOptions, options };"); out.println(" return (err = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args)) == JNI_OK && vm != NULL && (err = JNI_OnLoad" + loadSuffix + "(vm, NULL)) >= 0 ? JNI_OK : err;"); out.println("#endif"); out.println("}"); } if (baseLoadSuffix != null && !baseLoadSuffix.isEmpty()) { out.println(); out.println("JNIEXPORT jint JNICALL JNI_OnLoad" + baseLoadSuffix + "(JavaVM* vm, void* reserved);"); out.println("JNIEXPORT void JNICALL JNI_OnUnload" + baseLoadSuffix + "(JavaVM* vm, void* reserved);"); } out.println(); // XXX: JNI_OnLoad() should ideally be protected by some mutex out.println("JNIEXPORT jint JNICALL JNI_OnLoad" + loadSuffix + "(JavaVM* vm, void* reserved) {"); if (baseLoadSuffix != null && !baseLoadSuffix.isEmpty()) { out.println(" if (JNI_OnLoad" + baseLoadSuffix + "(vm, reserved) == JNI_ERR) {"); out.println(" return JNI_ERR;"); out.println(" }"); } out.println(" JNIEnv* env;"); out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnLoad" + loadSuffix + "().\");"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" if (JavaCPP_vm == vm) {"); out.println(" return env->GetVersion();"); out.println(" }"); out.println(" JavaCPP_vm = vm;"); out.println(" JavaCPP_haveAllocObject = env->functions->AllocObject != NULL;"); out.println(" JavaCPP_haveNonvirtual = env->functions->CallNonvirtualVoidMethodA != NULL;"); out.println(" jmethodID putMemberOffsetMID = JavaCPP_getStaticMethodID(env, " + jclasses.index(Loader.class) + ", \"putMemberOffset\", \"(Ljava/lang/String;Ljava/lang/String;I)Ljava/lang/Class;\");"); out.println(" if (putMemberOffsetMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" for (int i = 0; i < " + jclasses.size() + " && !env->ExceptionCheck(); i++) {"); out.println(" for (int j = 0; j < JavaCPP_memberOffsetSizes[i] && !env->ExceptionCheck(); j++) {"); out.println(" if (env->PushLocalFrame(3) == 0) {"); out.println(" jvalue args[3];"); out.println(" args[0].l = env->NewStringUTF(JavaCPP_classNames[i]);"); out.println(" args[1].l = JavaCPP_members[i][j] == NULL ? NULL : env->NewStringUTF(JavaCPP_members[i][j]);"); out.println(" args[2].i = JavaCPP_offsets[i][j];"); out.println(" jclass cls = (jclass)env->CallStaticObjectMethodA(JavaCPP_getClass(env, " + jclasses.index(Loader.class) + "), putMemberOffsetMID, args);"); out.println(" if (cls == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error putting member offsets for class %s.\", JavaCPP_classNames[i]);"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);"); // cache here for custom class loaders out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {"); out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" env->PopLocalFrame(NULL);"); out.println(" }"); out.println(" }"); out.println(" }"); out.println(" JavaCPP_addressFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"address\", \"J\");"); out.println(" if (JavaCPP_addressFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_positionFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"position\", \"J\");"); out.println(" if (JavaCPP_positionFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_limitFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"limit\", \"J\");"); out.println(" if (JavaCPP_limitFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_capacityFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"capacity\", \"J\");"); out.println(" if (JavaCPP_capacityFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_deallocatorFID = JavaCPP_getFieldID(env, " + jclasses.index(Pointer.class) + ", \"deallocator\", \"" + signature(deallocator) + "\");"); out.println(" if (JavaCPP_deallocatorFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_ownerAddressFID = JavaCPP_getFieldID(env, " + jclasses.index(nativeDeallocator) + ", \"ownerAddress\", \"J\");"); out.println(" if (JavaCPP_ownerAddressFID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_initMID = JavaCPP_getMethodID(env, " + jclasses.index(Pointer.class) + ", \"init\", \"(JJJJ)V\");"); out.println(" if (JavaCPP_initMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_arrayMID = JavaCPP_getMethodID(env, " + jclasses.index(Buffer.class) + ", \"array\", \"()Ljava/lang/Object;\");"); out.println(" if (JavaCPP_arrayMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_stringMID = JavaCPP_getMethodID(env, " + jclasses.index(String.class) + ", \"<init>\", \"([B)V\");"); out.println(" if (JavaCPP_stringMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_getBytesMID = JavaCPP_getMethodID(env, " + jclasses.index(String.class) + ", \"getBytes\", \"()[B\");"); out.println(" if (JavaCPP_getBytesMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" JavaCPP_toStringMID = JavaCPP_getMethodID(env, " + jclasses.index(Object.class) + ", \"toString\", \"()Ljava/lang/String;\");"); out.println(" if (JavaCPP_toStringMID == NULL) {"); out.println(" return JNI_ERR;"); out.println(" }"); out.println(" return env->GetVersion();"); out.println("}"); out.println(); if (out2 != null) { out2.println("JNIIMPORT int JavaCPP_uninit" + loadSuffix + "();"); out2.println(); out.println("JNIEXPORT int JavaCPP_uninit" + loadSuffix + "() {"); out.println("#if defined(__ANDROID__) || TARGET_OS_IPHONE"); out.println(" return JNI_OK;"); out.println("#else"); out.println(" JavaVM *vm = JavaCPP_vm;"); out.println(" JNI_OnUnload" + loadSuffix + "(JavaCPP_vm, NULL);"); out.println(" return vm->DestroyJavaVM();"); out.println("#endif"); out.println("}"); } out.println(); out.println("JNIEXPORT void JNICALL JNI_OnUnload" + loadSuffix + "(JavaVM* vm, void* reserved) {"); out.println(" JNIEnv* env;"); out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {"); out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnUnLoad" + loadSuffix + "().\");"); out.println(" return;"); out.println(" }"); out.println(" for (int i = 0; i < " + jclasses.size() + "; i++) {"); out.println(" env->DeleteWeakGlobalRef((jweak)JavaCPP_classes[i]);"); out.println(" JavaCPP_classes[i] = NULL;"); out.println(" }"); if (baseLoadSuffix != null && !baseLoadSuffix.isEmpty()) { out.println(" JNI_OnUnload" + baseLoadSuffix + "(vm, reserved);"); } out.println(" JavaCPP_vm = NULL;"); out.println("}"); out.println(); boolean supportedPlatform = false; LinkedHashSet<Class> allClasses = new LinkedHashSet<Class>(); if (baseLoadSuffix == null || baseLoadSuffix.isEmpty()) { supportedPlatform = true; allClasses.addAll(baseClasses); } if (classes != null) { allClasses.addAll(Arrays.asList(classes)); for (Class<?> cls : classes) { supportedPlatform |= checkPlatform(cls); } } boolean didSomethingUseful = false; for (Class<?> cls : allClasses) { try { didSomethingUseful |= methods(cls); } catch (NoClassDefFoundError e) { logger.warn("Could not generate code for class " + cls.getCanonicalName() + ": " + e); } } out.println("}"); out.println(); if (out2 != null) { out2.println("#ifdef __cplusplus"); out2.println("}"); out2.println("#endif"); } return supportedPlatform; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected <P extends Pointer> P deallocator(Deallocator deallocator) { if (this.deallocator != null) { if (logger.isDebugEnabled()) { logger.debug("Predeallocating " + this); } this.deallocator.deallocate(); this.deallocator = null; } if (deallocator != null && !deallocator.equals(null)) { this.deallocator = deallocator; DeallocatorReference r = deallocator instanceof DeallocatorReference ? (DeallocatorReference)deallocator : new DeallocatorReference(this, deallocator); int count = 0; while (count++ < maxRetries && maxBytes > 0 && DeallocatorReference.totalBytes + r.bytes > maxBytes) { try { // try to get some more memory back System.gc(); Thread.sleep(100); } catch (InterruptedException ex) { // reset interrupt to be nice Thread.currentThread().interrupt(); break; } } if (maxBytes > 0 && DeallocatorReference.totalBytes + r.bytes > maxBytes) { deallocate(); throw new OutOfMemoryError("Cannot allocate " + DeallocatorReference.totalBytes + " + " + r.bytes + " bytes (> Pointer.maxBytes)"); } if (logger.isDebugEnabled()) { logger.debug("Registering " + this); } r.add(); } return (P)this; } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected <P extends Pointer> P deallocator(Deallocator deallocator) { if (this.deallocator != null) { if (logger.isDebugEnabled()) { logger.debug("Predeallocating " + this); } this.deallocator.deallocate(); this.deallocator = null; } if (deallocator != null && !deallocator.equals(null)) { this.deallocator = deallocator; DeallocatorReference r = deallocator instanceof DeallocatorReference ? (DeallocatorReference)deallocator : new DeallocatorReference(this, deallocator); boolean lowMemory = false; try { if (maxBytes > 0 && DeallocatorReference.totalBytes + r.bytes > maxBytes) { lowMemory = true; lowMemoryCount.incrementAndGet(); } if (lowMemoryCount.get() > 0) { // synchronize allocation across threads when low on memory synchronized (lowMemoryCount) { int count = 0; while (count++ < maxRetries && DeallocatorReference.totalBytes + r.bytes > maxBytes) { // try to get some more memory back System.gc(); Thread.sleep(100); } if (count >= maxRetries && DeallocatorReference.totalBytes + r.bytes > maxBytes) { deallocate(); throw new OutOfMemoryError("Cannot allocate " + DeallocatorReference.totalBytes + " + " + r.bytes + " bytes (> Pointer.maxBytes)"); } } } } catch (InterruptedException ex) { // reset interrupt to be nice Thread.currentThread().interrupt(); } finally { if (lowMemory) { lowMemoryCount.decrementAndGet(); } } if (logger.isDebugEnabled()) { logger.debug("Registering " + this); } r.add(); } return (P)this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute() throws MojoExecutionException { final Log log = getLog(); try { log.info("Executing JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("classPath: " + classPath); log.debug("classPaths: " + Arrays.deepToString(classPaths)); log.debug("outputDirectory: " + outputDirectory); log.debug("outputName: " + outputName); log.debug("compile: " + compile); log.debug("header: " + header); log.debug("copyLibs: " + copyLibs); log.debug("jarPrefix: " + jarPrefix); log.debug("properties: " + properties); log.debug("propertyFile: " + propertyFile); log.debug("propertyKeysAndValues: " + propertyKeysAndValues); log.debug("classOrPackageName: " + classOrPackageName); log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); log.debug("environmentVariables: " + environmentVariables); log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); log.debug("skip: " + skip); } if (skip) { log.info("Skipped execution of JavaCPP Builder"); return; } if (classPaths != null && classPath != null) { classPaths = Arrays.copyOf(classPaths, classPaths.length + 1); classPaths[classPaths.length - 1] = classPath; } else if (classPath != null) { classPaths = new String[] { classPath }; } if (classOrPackageNames != null && classOrPackageName != null) { classOrPackageNames = Arrays.copyOf(classOrPackageNames, classOrPackageNames.length + 1); classOrPackageNames[classOrPackageNames.length - 1] = classOrPackageName; } else if (classOrPackageName != null) { classOrPackageNames = new String[] { classOrPackageName }; } Logger logger = new Logger() { @Override public void debug(CharSequence cs) { log.debug(cs); } @Override public void info (CharSequence cs) { log.info(cs); } @Override public void warn (CharSequence cs) { log.warn(cs); } @Override public void error(CharSequence cs) { log.error(cs); } }; Builder builder = new Builder(logger) .classPaths(classPaths) .outputDirectory(outputDirectory) .outputName(outputName) .compile(compile) .header(header) .copyLibs(copyLibs) .jarPrefix(jarPrefix) .properties(properties) .propertyFile(propertyFile) .properties(propertyKeysAndValues) .classesOrPackages(classOrPackageNames) .environmentVariables(environmentVariables) .compilerOptions(compilerOptions); project.getProperties().putAll(builder.properties); File[] outputFiles = builder.build(); log.info("Successfully executed JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); } } catch (Exception e) { log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); } } #location 58 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void execute() throws MojoExecutionException { final Log log = getLog(); try { log.info("Executing JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("classPath: " + classPath); log.debug("classPaths: " + Arrays.deepToString(classPaths)); log.debug("includePath: " + includePath); log.debug("includePaths: " + Arrays.deepToString(includePaths)); log.debug("linkPath: " + linkPath); log.debug("linkPaths: " + Arrays.deepToString(linkPaths)); log.debug("preloadPath: " + preloadPath); log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths)); log.debug("outputDirectory: " + outputDirectory); log.debug("outputName: " + outputName); log.debug("compile: " + compile); log.debug("header: " + header); log.debug("copyLibs: " + copyLibs); log.debug("jarPrefix: " + jarPrefix); log.debug("properties: " + properties); log.debug("propertyFile: " + propertyFile); log.debug("propertyKeysAndValues: " + propertyKeysAndValues); log.debug("classOrPackageName: " + classOrPackageName); log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); log.debug("environmentVariables: " + environmentVariables); log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); log.debug("skip: " + skip); } if (skip) { log.info("Skipped execution of JavaCPP Builder"); return; } classPaths = merge(classPaths, classPath); classOrPackageNames = merge(classOrPackageNames, classOrPackageName); Logger logger = new Logger() { @Override public void debug(CharSequence cs) { log.debug(cs); } @Override public void info (CharSequence cs) { log.info(cs); } @Override public void warn (CharSequence cs) { log.warn(cs); } @Override public void error(CharSequence cs) { log.error(cs); } }; Builder builder = new Builder(logger) .classPaths(classPaths) .outputDirectory(outputDirectory) .outputName(outputName) .compile(compile) .header(header) .copyLibs(copyLibs) .jarPrefix(jarPrefix) .properties(properties) .propertyFile(propertyFile) .properties(propertyKeysAndValues) .classesOrPackages(classOrPackageNames) .environmentVariables(environmentVariables) .compilerOptions(compilerOptions); Properties properties = builder.properties; String separator = properties.getProperty("platform.path.separator"); for (String s : merge(includePaths, includePath)) { String v = properties.getProperty("platform.includepath", ""); properties.setProperty("platform.includepath", v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); } for (String s : merge(linkPaths, linkPath)) { String v = properties.getProperty("platform.linkpath", ""); properties.setProperty("platform.linkpath", v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); } for (String s : merge(preloadPaths, preloadPath)) { String v = properties.getProperty("platform.preloadpath", ""); properties.setProperty("platform.preloadpath", v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); } project.getProperties().putAll(properties); File[] outputFiles = builder.build(); log.info("Successfully executed JavaCPP Builder"); if (log.isDebugEnabled()) { log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); } } catch (Exception e) { log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean generate(String sourceFilename, String headerFilename, String classPath, Class<?> ... classes) throws FileNotFoundException { // first pass using a null writer to fill up the IndexedSet objects out = new PrintWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }); out2 = null; callbacks = new IndexedSet<String>(); functions = new IndexedSet<Class>(); deallocators = new IndexedSet<Class>(); arrayDeallocators = new IndexedSet<Class>(); jclasses = new IndexedSet<Class>(); members = new HashMap<Class,Set<String>>(); virtualFunctions = new HashMap<Class,Set<String>>(); virtualMembers = new HashMap<Class,Set<String>>(); annotationCache = new HashMap<Method,MethodInformation>(); mayThrowExceptions = false; usesAdapters = false; passesStrings = false; for (Class<?> cls : baseClasses) { jclasses.index(cls); } if (classes(true, true, true, classPath, classes)) { // second pass with a real writer File sourceFile = new File(sourceFilename); File sourceDir = sourceFile.getParentFile(); if (sourceDir != null) { sourceDir.mkdirs(); } out = new PrintWriter(sourceFile); if (headerFilename != null) { File headerFile = new File(headerFilename); File headerDir = headerFile.getParentFile(); if (headerDir != null) { headerDir.mkdirs(); } out2 = new PrintWriter(headerFile); } return classes(mayThrowExceptions, usesAdapters, passesStrings, classPath, classes); } else { return false; } } #location 32 #vulnerability type RESOURCE_LEAK
#fixed code public boolean generate(String sourceFilename, String headerFilename, String classPath, Class<?> ... classes) throws IOException { // first pass using a null writer to fill up the IndexedSet objects out = new PrintWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) { } @Override public void flush() { } @Override public void close() { } }); out2 = null; callbacks = new IndexedSet<String>(); functions = new IndexedSet<Class>(); deallocators = new IndexedSet<Class>(); arrayDeallocators = new IndexedSet<Class>(); jclasses = new IndexedSet<Class>(); members = new HashMap<Class,Set<String>>(); virtualFunctions = new HashMap<Class,Set<String>>(); virtualMembers = new HashMap<Class,Set<String>>(); annotationCache = new HashMap<Method,MethodInformation>(); mayThrowExceptions = false; usesAdapters = false; passesStrings = false; for (Class<?> cls : baseClasses) { jclasses.index(cls); } if (classes(true, true, true, classPath, classes)) { // second pass with a real writer File sourceFile = new File(sourceFilename); File sourceDir = sourceFile.getParentFile(); if (sourceDir != null) { sourceDir.mkdirs(); } out = encoding != null ? new PrintWriter(sourceFile, encoding) : new PrintWriter(sourceFile); if (headerFilename != null) { File headerFile = new File(headerFilename); File headerDir = headerFile.getParentFile(); if (headerDir != null) { headerDir.mkdirs(); } out2 = encoding != null ? new PrintWriter(headerFile, encoding) : new PrintWriter(headerFile); } return classes(mayThrowExceptions, usesAdapters, passesStrings, classPath, classes); } else { return false; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Token[] expand(Token[] array, int index) { if (index < array.length && infoMap.containsKey(array[index].value)) { // if we hit a token whose info.cppText starts with #define (a macro), expand it int startIndex = index; Info info = infoMap.getFirst(array[index].value); if (info != null && info.cppText != null) { try { Tokenizer tokenizer = new Tokenizer(info.cppText, array[index].file, array[index].lineNumber); if (!tokenizer.nextToken().match('#') || !tokenizer.nextToken().match(Token.DEFINE) || !tokenizer.nextToken().match(info.cppNames[0])) { return array; } // copy the array of tokens up to this point List<Token> tokens = new ArrayList<Token>(); for (int i = 0; i < index; i++) { tokens.add(array[i]); } List<String> params = new ArrayList<String>(); List<Token>[] args = null; Token token = tokenizer.nextToken(); if (info.cppNames[0].equals("__COUNTER__")) { token.value = Integer.toString(counter++); } // pick up the parameters and arguments of the macro if it has any String name = array[index].value; if (token.match('(')) { token = tokenizer.nextToken(); while (!token.isEmpty()) { if (token.match(Token.IDENTIFIER)) { params.add(token.value); } else if (token.match(')')) { token = tokenizer.nextToken(); break; } token = tokenizer.nextToken(); } index++; if (params.size() > 0 && (index >= array.length || !array[index].match('('))) { return array; } name += array[index].spacing + array[index]; args = new List[params.size()]; int count = 0, count2 = 0; for (index++; index < array.length; index++) { Token token2 = array[index]; name += token2.spacing + token2; if (count2 == 0 && token2.match(')')) { break; } else if (count2 == 0 && token2.match(',')) { count++; continue; } else if (token2.match('(','[','{')) { count2++; } else if (token2.match(')',']','}')) { count2--; } if (count < args.length) { if (args[count] == null) { args[count] = new ArrayList<Token>(); } args[count].add(token2); } } // expand the arguments of the macros as well for (int i = 0; i < args.length; i++) { if (infoMap.containsKey(args[i].get(0).value)) { args[i] = Arrays.asList(expand(args[i].toArray(new Token[args[i].size()]), 0)); } } } int startToken = tokens.size(); // expand the token in question, unless we should skip it info = infoMap.getFirst(name); while ((info == null || !info.skip) && !token.isEmpty()) { boolean foundArg = false; for (int i = 0; i < params.size(); i++) { if (params.get(i).equals(token.value)) { String s = token.spacing; for (Token arg : args[i]) { // clone tokens here to avoid potential problems with concatenation below Token t = new Token(arg); if (s != null) { t.spacing += s; } tokens.add(t); s = null; } foundArg = true; break; } } if (!foundArg) { if (token.type == -1) { token.type = Token.COMMENT; } tokens.add(token); } token = tokenizer.nextToken(); } // concatenate tokens as required for (int i = startToken; i < tokens.size(); i++) { if (tokens.get(i).match("##") && i > 0 && i + 1 < tokens.size()) { tokens.get(i - 1).value += tokens.get(i + 1).value; tokens.remove(i); tokens.remove(i); i--; } } // copy the rest of the tokens from this point on for (index++; index < array.length; index++) { tokens.add(array[index]); } if ((info == null || !info.skip) && startToken < tokens.size()) { tokens.get(startToken).spacing = array[startIndex].spacing; } array = tokens.toArray(new Token[tokens.size()]); } catch (IOException ex) { throw new RuntimeException(ex); } } } return array; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code TokenIndexer(InfoMap infoMap, Token[] array, boolean isCFile) { this.infoMap = infoMap; this.array = array; this.isCFile = isCFile; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BytePointer putString(String s, String charsetName) throws UnsupportedEncodingException { byte[] bytes = s.getBytes(charsetName); //capacity(bytes.length+1); asBuffer().put(bytes).put((byte)0); return this; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public BytePointer putString(String s, String charsetName) throws UnsupportedEncodingException { byte[] bytes = s.getBytes(charsetName); //capacity(bytes.length+1); put(bytes).put(bytes.length, (byte)0); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Task> assignTasks(TaskTracker taskTracker) throws IOException { HttpHost tracker = new HttpHost(taskTracker.getStatus().getHost(), taskTracker.getStatus().getHttpPort()); if (!mesosTrackers.containsKey(tracker)) { LOG.info("Unknown/exited TaskTracker: " + tracker + ". "); return null; } // Let the underlying task scheduler do the actual task scheduling. List<Task> tasks = taskScheduler.assignTasks(taskTracker); // The Hadoop Fair Scheduler is known to return null. if (tasks == null) { return null; } // Keep track of which TaskTracker contains which tasks. for (Task task : tasks) { mesosTrackers.get(tracker).jobs.add(task.getJobID()); } return tasks; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public List<Task> assignTasks(TaskTracker taskTracker) throws IOException { HttpHost tracker = new HttpHost(taskTracker.getStatus().getHost(), taskTracker.getStatus().getHttpPort()); if (!mesosTrackers.containsKey(tracker)) { LOG.info("Unknown/exited TaskTracker: " + tracker + ". "); return null; } MesosTracker mesosTracker = mesosTrackers.get(tracker); // Make sure we're not asked to assign tasks to any task trackers that have // been stopped. This could happen while the task tracker has not been // removed from the cluster e.g still in the heartbeat timeout period. synchronized (this) { if (mesosTracker.stopped) { LOG.info("Asked to assign tasks to stopped tracker " + tracker + "."); return null; } } // Let the underlying task scheduler do the actual task scheduling. List<Task> tasks = taskScheduler.assignTasks(taskTracker); // The Hadoop Fair Scheduler is known to return null. if (tasks == null) { return null; } // Keep track of which TaskTracker contains which tasks. for (Task task : tasks) { mesosTracker.jobs.add(task.getJobID()); } return tasks; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public <T> T get(String claimName, Class<T> requiredType) { Object value = get(claimName); if (value == null) { return null; } if (Claims.EXPIRATION.equals(claimName) || Claims.ISSUED_AT.equals(claimName) || Claims.NOT_BEFORE.equals(claimName) ) { value = getDate(claimName); } if (requiredType == Date.class && value instanceof Long) { value = new Date((Long)value); } if (!requiredType.isInstance(value)) { throw new RequiredTypeException("Expected value to be of type: " + requiredType + ", but was " + value.getClass()); } return requiredType.cast(value); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public <T> T get(String claimName, Class<T> requiredType) { Object value = get(claimName); if (value == null) { return null; } if (Claims.EXPIRATION.equals(claimName) || Claims.ISSUED_AT.equals(claimName) || Claims.NOT_BEFORE.equals(claimName) ) { value = getDate(claimName); } return castClaimValue(value, requiredType); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected byte[] doDecompress(byte[] compressed) throws IOException { byte[] buffer = new byte[512]; ByteArrayOutputStream outputStream = null; GZIPInputStream gzipInputStream = null; ByteArrayInputStream inputStream = null; try { inputStream = new ByteArrayInputStream(compressed); gzipInputStream = new GZIPInputStream(inputStream); outputStream = new ByteArrayOutputStream(); int read = gzipInputStream.read(buffer); while (read != -1) { outputStream.write(buffer, 0, read); read = gzipInputStream.read(buffer); } return outputStream.toByteArray(); } finally { Objects.nullSafeClose(inputStream, gzipInputStream, outputStream); } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected byte[] doDecompress(byte[] compressed) throws IOException { return readAndClose(new GZIPInputStream(new ByteArrayInputStream(compressed))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public boolean updateRule(@PathVariable String id, @RequestBody RouteDTO routeDTO, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { //TODO Exception } routeDTO.setVersion(route.getVersion()); routeDTO.setService(route.getService()); Route newRoute = convertRouteDTOtoRoute(routeDTO, id); routeService.updateRoute(newRoute); return true; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public boolean updateRule(@PathVariable String id, @RequestBody RouteDTO routeDTO, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { throw new ResourceNotFoundException("Unknown ID!"); } routeDTO.setVersion(route.getVersion()); routeDTO.setService(route.getService()); Route newRoute = convertRouteDTOtoRoute(routeDTO, id); routeService.updateRoute(newRoute); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/{id}", method = RequestMethod.GET) public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { // TODO throw exception } RouteDTO routeDTO = new RouteDTO(); routeDTO.setDynamic(route.isDynamic()); routeDTO.setConditions(new String[]{route.getRule()}); routeDTO.setEnabled(route.isEnabled()); routeDTO.setForce(route.isForce()); routeDTO.setGroup(route.getGroup()); routeDTO.setPriority(route.getPriority()); routeDTO.setRuntime(route.isRuntime()); routeDTO.setService(route.getService()); routeDTO.setId(route.getHash()); return routeDTO; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/{id}", method = RequestMethod.GET) public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { // TODO throw exception } RouteDTO routeDTO = convertRoutetoRouteDTO(route, id); return routeDTO; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/{id}", method = RequestMethod.GET) public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { // TODO throw exception } RouteDTO routeDTO = convertRoutetoRouteDTO(route, id); return routeDTO; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/{id}", method = RequestMethod.GET) public RouteDTO detailRoute(@PathVariable String id, @PathVariable String env) { Route route = routeService.findRoute(id); if (route == null) { throw new ResourceNotFoundException("Unknown ID!"); } RouteDTO routeDTO = convertRoutetoRouteDTO(route, id); return routeDTO; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/{id}", method = RequestMethod.GET) public OverrideDTO detailOverride(@PathVariable String id, @PathVariable String env) { Override override = overrideService.findById(id); if (override == null) { //TODO throw exception } OverrideDTO overrideDTO = new OverrideDTO(); overrideDTO.setAddress(override.getAddress()); overrideDTO.setApp(override.getApplication()); overrideDTO.setEnabled(override.isEnabled()); overrideDTO.setService(override.getService()); paramsToOverrideDTO(override, overrideDTO); return overrideDTO; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/{id}", method = RequestMethod.GET) public OverrideDTO detailOverride(@PathVariable String id, @PathVariable String env) { Override override = overrideService.findById(id); if (override == null) { throw new ResourceNotFoundException("Unknown ID!"); } OverrideDTO overrideDTO = new OverrideDTO(); overrideDTO.setAddress(override.getAddress()); overrideDTO.setApp(override.getApplication()); overrideDTO.setEnabled(override.isEnabled()); overrideDTO.setService(override.getService()); paramsToOverrideDTO(override, overrideDTO); return overrideDTO; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void addToWindow(Datum newDatum) { if (window.size() == 0) { // We don't know what weight to use for the first datum, so we wait // until we have the second one to actually process it. window.add(new DatumWithInfo(newDatum, 0)); } else { int weight = newDatum.getTime() - getLatestDatum().getTime(); if (window.size() == 1) { windowSum = new ArrayRealVector(newDatum.getMetrics() .getDimension()); // Remove and re-add first datum with the correct weight Datum first = window.remove().getDatum(); // Assume same weight for first as for second addDatumWithWeight(first, weight); } addDatumWithWeight(newDatum, weight); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void addToWindow(Datum newDatum) { if (window.size() == 0) { // We don't know what weight to use for the first datum, so we wait // until we have the second one to actually process it. window.add(new DatumWithInfo(newDatum, 0)); } else { int weight = newDatum.getTime(timeColumn) - getLatestDatum().getTime(timeColumn); if (window.size() == 1) { windowSum = new ArrayRealVector(newDatum.getMetrics() .getDimension()); // Remove and re-add first datum with the correct weight Datum first = window.remove().getDatum(); // Assume same weight for first as for second addDatumWithWeight(first, weight); } addDatumWithWeight(newDatum, weight); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDumpSmall() throws Exception { MacroBaseConf conf = new MacroBaseConf(); ArrayList<Integer> attrs = new ArrayList<>(); attrs.add(1); attrs.add(2); OutlierClassifier dummy = new OutlierClassifier() { MBStream<OutlierClassificationResult> result = new MBStream<>(); @Override public MBStream<OutlierClassificationResult> getStream() throws Exception { return result; } @Override public void initialize() throws Exception { } @Override public void consume(List<Datum> records) throws Exception { for(Datum r : records) { result.add(new OutlierClassificationResult(r, true)); } } @Override public void shutdown() throws Exception { } }; File f = folder.newFile("testDumpSmall"); DumpClassifier dumper = new DumpClassifier(conf, dummy, f.getAbsolutePath()); List<Datum> data = new ArrayList<>(); data.add(new Datum(attrs, new ArrayRealVector())); data.add(new Datum(attrs, new ArrayRealVector())); dumper.consume(data); List<OutlierClassificationResult> results = dumper.getStream().drain(); assertEquals(results.size(), data.size()); OutlierClassificationResult first = results.get(0); assertEquals(true, first.isOutlier()); assertEquals(1, first.getDatum().getAttributes().get(0).intValue()); Path filePath = Paths.get(dumper.getFilePath()); assertTrue(Files.exists(filePath)); Files.deleteIfExists(Paths.get(dumper.getFilePath())); } #location 52 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDumpSmall() throws Exception { MacroBaseConf conf = new MacroBaseConf(); ArrayList<Integer> attrs = new ArrayList<>(); attrs.add(1); attrs.add(2); OutlierClassifier dummy = new OutlierClassifier() { MBStream<OutlierClassificationResult> result = new MBStream<>(); @Override public MBStream<OutlierClassificationResult> getStream() throws Exception { return result; } @Override public void initialize() throws Exception { } @Override public void consume(List<Datum> records) throws Exception { for(Datum r : records) { result.add(new OutlierClassificationResult(r, true)); } } @Override public void shutdown() throws Exception { } }; File f = folder.newFile("testDumpSmall"); DumpClassifier dumper = new DumpClassifier(conf, dummy, f.getAbsolutePath()); List<Datum> data = new ArrayList<>(); data.add(new Datum(attrs, new ArrayRealVector())); data.add(new Datum(attrs, new ArrayRealVector())); dumper.consume(data); List<OutlierClassificationResult> results = dumper.getStream().drain(); dumper.shutdown(); assertEquals(results.size(), data.size()); OutlierClassificationResult first = results.get(0); assertEquals(true, first.isOutlier()); assertEquals(1, first.getDatum().getAttributes().get(0).intValue()); Path filePath = Paths.get(dumper.getFilePath()); assertTrue(Files.exists(filePath)); Files.deleteIfExists(Paths.get(dumper.getFilePath())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ColumnValue getAttribute(int encodedAttr) { int matchingColumn = integerToColumn.get(encodedAttr); String columnName = attributeDimensionNameMap.get(matchingColumn); String columnValue = integerEncoding.get(matchingColumn).inverse().get(encodedAttr); return new ColumnValue(columnName, columnValue); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public ColumnValue getAttribute(int encodedAttr) { int matchingColumn = integerToColumn.get(encodedAttr); String columnName = attributeDimensionNameMap.get(matchingColumn); Map<String, Integer> columnEncoding = integerEncoding.get(matchingColumn); String columnValue = null; for(Map.Entry<String, Integer> ce : columnEncoding.entrySet()) { if(ce.getValue() == encodedAttr) { columnValue = ce.getKey(); } } return new ColumnValue(columnName, columnValue); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<AnalysisResult> run() throws Exception { final int batchSize = conf.getInt(MacroBaseConf.TUPLE_BATCH_SIZE, MacroBaseDefaults.TUPLE_BATCH_SIZE); Stopwatch sw = Stopwatch.createStarted(); DataIngester ingester = conf.constructIngester(); List<Datum> data = ingester.getStream().drain(); System.gc(); final long loadMs = sw.elapsed(TimeUnit.MILLISECONDS); MBStream<Datum> streamData = new MBStream<>(data); MBOperator<Datum, OutlierClassificationResult> ocr = new EWFeatureTransform(conf) .then(new EWAppxPercentileOutlierClassifier(conf), batchSize); while(streamData.remaining() > 0) { ocr.consume(streamData.drain(batchSize)); } MBStream<OutlierClassificationResult> ocrs = ocr.getStream(); Summarizer summarizer = new EWStreamingSummarizer(conf); summarizer.consume(ocrs.drain()); Summary result = summarizer.getStream().drain().get(0); final long totalMs = sw.elapsed(TimeUnit.MILLISECONDS) - loadMs; final long summarizeMs = result.getCreationTimeMs(); final long executeMs = totalMs - result.getCreationTimeMs(); log.info("took {}ms ({} tuples/sec)", totalMs, (result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000); return Arrays.asList(new AnalysisResult(result.getNumOutliers(), result.getNumInliers(), loadMs, executeMs, summarizeMs, result.getItemsets())); } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<AnalysisResult> run() throws Exception { final int batchSize = conf.getInt(MacroBaseConf.TUPLE_BATCH_SIZE, MacroBaseDefaults.TUPLE_BATCH_SIZE); Stopwatch sw = Stopwatch.createStarted(); DataIngester ingester = conf.constructIngester(); List<Datum> data = ingester.getStream().drain(); System.gc(); final long loadMs = sw.elapsed(TimeUnit.MILLISECONDS); MBStream<Datum> streamData = new MBStream<>(data); Summarizer summarizer = new EWStreamingSummarizer(conf); MBOperator<Datum, Summary> pipeline = new EWFeatureTransform(conf) .then(new EWAppxPercentileOutlierClassifier(conf), batchSize) .then(summarizer, batchSize); while(streamData.remaining() > 0) { pipeline.consume(streamData.drain(batchSize)); } Summary result = summarizer.summarize().getStream().drain().get(0); final long totalMs = sw.elapsed(TimeUnit.MILLISECONDS) - loadMs; final long summarizeMs = result.getCreationTimeMs(); final long executeMs = totalMs - result.getCreationTimeMs(); log.info("took {}ms ({} tuples/sec)", totalMs, (result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000); return Arrays.asList(new AnalysisResult(result.getNumOutliers(), result.getNumInliers(), loadMs, executeMs, summarizeMs, result.getItemsets())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @POST @Consumes(MediaType.APPLICATION_JSON) public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) { FormattedRowSetResponse response = new FormattedRowSetResponse(); try { conf.set(MacroBaseConf.DB_URL, request.pgUrl); conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery); HashMap<String, String> preds = new HashMap<>(); request.columnValues.stream().forEach(a -> preds.put(a.column, a.value)); if(request.returnType == RETURNTYPE.SQL) { response.response = getLoader().getRowsSql(request.baseQuery, preds, request.limit, request.offset)+";"; return response; } RowSet r = getLoader().getRows(request.baseQuery, preds, request.limit, request.offset); if (request.returnType == RETURNTYPE.JSON) { response.response = new ObjectMapper().writeValueAsString(r); } else { assert (request.returnType == RETURNTYPE.CSV); StringWriter sw = new StringWriter(); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); if(r.getRows().isEmpty()) { printer.printRecord(preds.keySet()); } else { printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray()); for (RowSet.Row row : r.getRows()) { printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray()); } } response.response = sw.toString(); } } catch (Exception e) { log.error("An error occurred while processing a request:", e); response.errorMessage = ExceptionUtils.getStackTrace(e); } return response; } #location 38 #vulnerability type RESOURCE_LEAK
#fixed code @POST @Consumes(MediaType.APPLICATION_JSON) public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) { FormattedRowSetResponse response = new FormattedRowSetResponse(); try { conf.set(MacroBaseConf.DB_URL, request.pgUrl); conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery); HashMap<String, String> preds = new HashMap<>(); request.columnValues.stream().forEach(a -> preds.put(a.column, a.value)); if(request.returnType == RETURNTYPE.SQL) { response.response = ((SQLIngester) getLoader()).getRowsSql(request.baseQuery, preds, request.limit, request.offset)+";"; return response; } RowSet r = getLoader().getRows(request.baseQuery, preds, request.limit, request.offset); if (request.returnType == RETURNTYPE.JSON) { response.response = new ObjectMapper().writeValueAsString(r); } else { assert (request.returnType == RETURNTYPE.CSV); StringWriter sw = new StringWriter(); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); if(r.getRows().isEmpty()) { printer.printRecord(preds.keySet()); } else { printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray()); for (RowSet.Row row : r.getRows()) { printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray()); } } response.response = sw.toString(); } } catch (Exception e) { log.error("An error occurred while processing a request:", e); response.errorMessage = ExceptionUtils.getStackTrace(e); } return response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @POST @Consumes(MediaType.APPLICATION_JSON) public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) { FormattedRowSetResponse response = new FormattedRowSetResponse(); try { conf.set(MacroBaseConf.DB_URL, request.pgUrl); conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery); HashMap<String, String> preds = new HashMap<>(); request.columnValues.stream().forEach(a -> preds.put(a.column, a.value)); if(request.returnType == RETURNTYPE.SQL) { response.response = getLoader().getRowsSql(request.baseQuery, preds, request.limit, request.offset)+";"; return response; } RowSet r = getLoader().getRows(request.baseQuery, preds, request.limit, request.offset); if (request.returnType == RETURNTYPE.JSON) { response.response = new ObjectMapper().writeValueAsString(r); } else { assert (request.returnType == RETURNTYPE.CSV); StringWriter sw = new StringWriter(); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); if(r.getRows().isEmpty()) { printer.printRecord(preds.keySet()); } else { printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray()); for (RowSet.Row row : r.getRows()) { printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray()); } } response.response = sw.toString(); } } catch (Exception e) { log.error("An error occurred while processing a request:", e); response.errorMessage = ExceptionUtils.getStackTrace(e); } return response; } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code @POST @Consumes(MediaType.APPLICATION_JSON) public FormattedRowSetResponse getRowsFormatted(RowSetRequest request) { FormattedRowSetResponse response = new FormattedRowSetResponse(); try { conf.set(MacroBaseConf.DB_URL, request.pgUrl); conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery); HashMap<String, String> preds = new HashMap<>(); request.columnValues.stream().forEach(a -> preds.put(a.column, a.value)); if(request.returnType == RETURNTYPE.SQL) { response.response = ((SQLIngester) getLoader()).getRowsSql(request.baseQuery, preds, request.limit, request.offset)+";"; return response; } RowSet r = getLoader().getRows(request.baseQuery, preds, request.limit, request.offset); if (request.returnType == RETURNTYPE.JSON) { response.response = new ObjectMapper().writeValueAsString(r); } else { assert (request.returnType == RETURNTYPE.CSV); StringWriter sw = new StringWriter(); CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); if(r.getRows().isEmpty()) { printer.printRecord(preds.keySet()); } else { printer.printRecord(r.getRows().get(0).getColumnValues().stream().map(a -> a.getColumn()).toArray()); for (RowSet.Row row : r.getRows()) { printer.printRecord(row.getColumnValues().stream().map(a -> a.getValue()).toArray()); } } response.response = sw.toString(); } } catch (Exception e) { log.error("An error occurred while processing a request:", e); response.errorMessage = ExceptionUtils.getStackTrace(e); } return response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public AnalysisResult run() throws Exception { long startMs = System.currentTimeMillis(); DataIngester ingester = conf.constructIngester(); List<Datum> data = ingester.getStream().drain(); long loadEndMs = System.currentTimeMillis(); FeatureTransform featureTransform = new EWFeatureTransform(conf); featureTransform.consume(ingester.getStream().drain()); OutlierClassifier outlierClassifier = new EWAppxPercentileOutlierClassifier(conf); outlierClassifier.consume(featureTransform.getStream().drain()); Summarizer summarizer = new EWStreamingSummarizer(conf); summarizer.consume(outlierClassifier.getStream().drain()); Summary result = summarizer.getStream().drain().get(0); final long endMs = System.currentTimeMillis(); final long loadMs = loadEndMs - startMs; final long totalMs = endMs - loadEndMs; final long summarizeMs = result.getCreationTimeMs(); final long executeMs = totalMs - result.getCreationTimeMs(); log.info("took {}ms ({} tuples/sec)", totalMs, (result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000); return new AnalysisResult(result.getNumOutliers(), result.getNumInliers(), loadMs, executeMs, summarizeMs, result.getItemsets()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public AnalysisResult run() throws Exception { long startMs = System.currentTimeMillis(); DataIngester ingester = conf.constructIngester(); List<Datum> data = ingester.getStream().drain(); long loadEndMs = System.currentTimeMillis(); MBStream<OutlierClassificationResult> ocrs = MBOperatorChain.begin(data) .then(new EWFeatureTransform(conf)) .then(new EWAppxPercentileOutlierClassifier(conf)).executeMiniBatchUntilFixpoint(1000); Summarizer summarizer = new EWStreamingSummarizer(conf); summarizer.consume(ocrs.drain()); Summary result = summarizer.getStream().drain().get(0); final long endMs = System.currentTimeMillis(); final long loadMs = loadEndMs - startMs; final long totalMs = endMs - loadEndMs; final long summarizeMs = result.getCreationTimeMs(); final long executeMs = totalMs - result.getCreationTimeMs(); log.info("took {}ms ({} tuples/sec)", totalMs, (result.getNumInliers()+result.getNumOutliers())/(double)totalMs*1000); return new AnalysisResult(result.getNumOutliers(), result.getNumInliers(), loadMs, executeMs, summarizeMs, result.getItemsets()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldHandleErrorResponse() throws Exception { //given final HttpResponse errorResponse = new HttpResponse(401, "{\n" + " \"error\": {\n" + " \"message\": \"Invalid OAuth access token.\",\n" + " \"type\": \"OAuthException\",\n" + " \"code\": 190,\n" + " \"fbtrace_id\": \"BLBz/WZt8dN\"\n" + " }\n" + "}"); when(mockHttpClient.execute(eq(GET), anyString(), (String) isNull())).thenReturn(errorResponse); //when MessengerApiException messengerApiException = null; try { this.userProfileClient.queryUserProfile("USER_ID"); } catch (MessengerApiException e) { messengerApiException = e; } //then assertThat(messengerApiException, is(notNullValue())); assertThat(messengerApiException.getMessage(), is(equalTo("Invalid OAuth access token."))); assertThat(messengerApiException.getType(), is(equalTo("OAuthException"))); assertThat(messengerApiException.getCode(), is(equalTo(190))); assertThat(messengerApiException.getFbTraceId(), is(equalTo("BLBz/WZt8dN"))); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void shouldHandleErrorResponse() throws Exception { //given final HttpResponse errorResponse = new HttpResponse(401, "{\n" + " \"error\": {\n" + " \"message\": \"Invalid OAuth access token.\",\n" + " \"type\": \"OAuthException\",\n" + " \"code\": 190,\n" + " \"fbtrace_id\": \"BLBz/WZt8dN\"\n" + " }\n" + "}"); when(mockHttpClient.execute(eq(GET), anyString(), isNull())).thenReturn(errorResponse); //when MessengerApiException messengerApiException = null; try { messenger.queryUserProfileById("USER_ID"); } catch (MessengerApiException e) { messengerApiException = e; } //then assertThat(messengerApiException, is(notNullValue())); assertThat(messengerApiException.getMessage(), is(equalTo("Invalid OAuth access token."))); assertThat(messengerApiException.getType(), is(equalTo("OAuthException"))); assertThat(messengerApiException.getCode(), is(equalTo(190))); assertThat(messengerApiException.getFbTraceId(), is(equalTo("BLBz/WZt8dN"))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ app = new ClueApplication(idxLocation, false); String cmd = args[1]; String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } else{ app = new ClueApplication(idxLocation, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine().trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine().trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() throws IOException { BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine(); if (line == null || line.isEmpty()) continue; line = line.trim(); String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); handleCommand(cmd, cmdArgs, System.out); } } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public void run() throws IOException { while(true){ System.out.print("> "); String line = ctx.readCommand(); if (line == null || line.isEmpty()) continue; line = line.trim(); String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); handleCommand(cmd, cmdArgs, System.out); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute(String[] args, PrintStream out) throws Exception { String field = null; String termVal = null; try{ field = args[0]; } catch(Exception e){ field = null; } if (field != null){ String[] parts = field.split(":"); if (parts.length > 1){ field = parts[0]; termVal = parts[1]; } } IndexReader reader = ctx.getIndexReader(); List<AtomicReaderContext> leaves = reader.leaves(); TreeMap<BytesRef,TermsEnum> termMap = null; HashMap<BytesRef,AtomicInteger> termCountMap = new HashMap<BytesRef,AtomicInteger>(); for (AtomicReaderContext leaf : leaves){ AtomicReader atomicReader = leaf.reader(); Terms terms = atomicReader.fields().terms(field); if (terms == null) { continue; } if (termMap == null){ termMap = new TreeMap<BytesRef,TermsEnum>(terms.getComparator()); } TermsEnum te = terms.iterator(null); BytesRef termBytes; if (termVal != null){ te.seekCeil(new BytesRef(termVal)); termBytes = te.term(); } else{ termBytes = te.next(); } while(true){ if (termBytes == null) break; AtomicInteger count = termCountMap.get(termBytes); if (count == null){ termCountMap.put(termBytes, new AtomicInteger(te.docFreq())); termMap.put(termBytes, te); break; } count.getAndAdd(te.docFreq()); termBytes = te.next(); } } while(!termMap.isEmpty()){ Entry<BytesRef,TermsEnum> entry = termMap.pollFirstEntry(); if (entry == null) break; BytesRef key = entry.getKey(); AtomicInteger count = termCountMap.remove(key); out.println(key.utf8ToString()+" ("+count+") "); TermsEnum te = entry.getValue(); BytesRef nextKey = te.next(); while(true){ if (nextKey == null) break; count = termCountMap.get(nextKey); if (count == null){ termCountMap.put(nextKey, new AtomicInteger(te.docFreq())); termMap.put(nextKey, te); break; } count.getAndAdd(te.docFreq()); nextKey = te.next(); } } out.flush(); } #location 61 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void execute(String[] args, PrintStream out) throws Exception { String field = null; String termVal = null; try{ field = args[0]; } catch(Exception e){ field = null; } if (field != null){ String[] parts = field.split(":"); if (parts.length > 1){ field = parts[0]; termVal = parts[1]; } } IndexReader reader = ctx.getIndexReader(); List<AtomicReaderContext> leaves = reader.leaves(); TreeMap<BytesRef,TermsEnum> termMap = null; HashMap<BytesRef,AtomicInteger> termCountMap = new HashMap<BytesRef,AtomicInteger>(); for (AtomicReaderContext leaf : leaves){ AtomicReader atomicReader = leaf.reader(); if (field == null){ continue; } Terms terms = atomicReader.fields().terms(field); if (terms == null) { continue; } if (termMap == null){ termMap = new TreeMap<BytesRef,TermsEnum>(terms.getComparator()); } TermsEnum te = terms.iterator(null); BytesRef termBytes; if (termVal != null){ te.seekCeil(new BytesRef(termVal)); termBytes = te.term(); } else{ termBytes = te.next(); } while(true){ if (termBytes == null) break; AtomicInteger count = termCountMap.get(termBytes); if (count == null){ termCountMap.put(termBytes, new AtomicInteger(te.docFreq())); termMap.put(termBytes, te); break; } count.getAndAdd(te.docFreq()); termBytes = te.next(); } } while(termMap != null && !termMap.isEmpty()){ Entry<BytesRef,TermsEnum> entry = termMap.pollFirstEntry(); if (entry == null) break; BytesRef key = entry.getKey(); AtomicInteger count = termCountMap.remove(key); out.println(key.utf8ToString()+" ("+count+") "); TermsEnum te = entry.getValue(); BytesRef nextKey = te.next(); while(true){ if (nextKey == null) break; count = termCountMap.get(nextKey); if (count == null){ termCountMap.put(nextKey, new AtomicInteger(te.docFreq())); termMap.put(nextKey, te); break; } count.getAndAdd(te.docFreq()); nextKey = te.next(); } } out.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } ClueConfiguration config = ClueConfiguration.load(); String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, config, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, config, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, config, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine(); if (line == null || line.isEmpty()) continue; line = line.trim(); String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } } #location 35 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, true); app.run(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ app = new ClueApplication(idxLocation, false); String cmd = args[1]; String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } else{ app = new ClueApplication(idxLocation, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine().trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } } } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { if (args.length < 1){ System.out.println("usage: <index location> <command> <command args>"); System.exit(1); } String idxLocation = args[0]; ClueApplication app = null; if (args.length > 1){ String cmd = args[1]; if ("readonly".equalsIgnoreCase(cmd)) { if (args.length > 2) { cmd = args[2]; app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 3]; System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length); app.ctx.setReadOnlyMode(true); app.handleCommand(cmd, cmdArgs, System.out); } } else { app = new ClueApplication(idxLocation, false); String[] cmdArgs; cmdArgs = new String[args.length - 2]; System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } return; } app = new ClueApplication(idxLocation, true); BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.print("> "); String line = inReader.readLine().trim(); if (line.isEmpty()) continue; String[] parts = line.split("\\s"); if (parts.length > 0){ String cmd = parts[0]; String[] cmdArgs = new String[parts.length - 1]; System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length); app.handleCommand(cmd, cmdArgs, System.out); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void printScreen() { if (error != null && error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public static void printScreen() { if (error == null || error || !error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void printScreen() { if (error != null && error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public static void printScreen() { if (error == null || error || !error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void printScreen() { if (error != null && error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public static void printScreen() { if (error == null || error || !error) { printScreenWithOld(); } else { try { String[] args = new String[]{"bash", "-c", adbPath + " exec-out screencap -p > " + screenshotLocation}; String os = System.getProperty("os.name"); if (os.toLowerCase().startsWith("win")) { args[0] = "cmd"; args[1] = "/c"; } Process p1 = Runtime.getRuntime().exec(args); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p1.getErrorStream())); String s; while ((s = bufferedReader.readLine()) != null) System.out.println(s); p1.waitFor(); checkScreenSuccess(); } catch (IOException e) { e.printStackTrace(); error = true; printScreenWithOld(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code public static void buildSysGenProfilingFile() { long startMills = System.currentTimeMillis(); String filePath = ProfilingConfig.getInstance().getSysProfilingParamsFile(); String tempFilePath = filePath + "_tmp"; File tempFile = new File(tempFilePath); try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tempFile, false), 8 * 1024)) { fileWriter.write("#This is a file automatically generated by MyPerf4J, please do not edit!\n"); MethodTagMaintainer tagMaintainer = MethodTagMaintainer.getInstance(); Map<Integer, MethodMetricsInfo> methodMap = MethodMetricsHistogram.methodMap; for (Map.Entry<Integer, MethodMetricsInfo> entry : methodMap.entrySet()) { Integer methodId = entry.getKey(); MethodMetricsInfo info = entry.getValue(); if (info.getCount() <= 0) { continue; } MethodTag methodTag = tagMaintainer.getMethodTag(methodId); fileWriter.write(methodTag.getFullDesc()); fileWriter.write('='); int mostTimeThreshold = calMostTimeThreshold(info); fileWriter.write(mostTimeThreshold + ":" + calOutThresholdCount(mostTimeThreshold)); fileWriter.newLine(); } fileWriter.flush(); File destFile = new File(filePath); boolean rename = tempFile.renameTo(destFile) && destFile.setReadOnly(); Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile(): rename " + tempFile.getName() + " to " + destFile.getName() + " " + (rename ? "success" : "fail")); } catch (Exception e) { Logger.error("MethodMetricsHistogram.buildSysGenProfilingFile()", e); } finally { Logger.debug("MethodMetricsHistogram.buildSysGenProfilingFile() finished, cost=" + (System.currentTimeMillis() - startMills) + "ms"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(roleId).secretId(secretId).build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare() .getRestTemplate()); assertThat(executor.login()).isNotNull(); getVaultOperations().write( "auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Test void authenticationStepsShouldAuthenticatePushModeWithProvidedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = "hello_world_two"; VaultResponse customSecretIdResponse = getVaultOperations().write( "auth/approle/role/with-secret-id/custom-secret-id", Collections.singletonMap("secret_id", secretId)); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) .build(); AuthenticationStepsExecutor executor = new AuthenticationStepsExecutor( AppRoleAuthentication.createAuthenticationSteps(options), prepare() .getRestTemplate()); assertThat(executor.login()).isNotNull(); getVaultOperations().write( "auth/approle/role/with-secret-id/secret-id-accessor/destroy", customSecretIdResponse.getRequiredData()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private Lease renew(Lease lease) { HttpEntity<Object> leaseRenewalEntity = getLeaseRenewalBody(lease); ResponseEntity<Map<String, Object>> entity = operations .doWithSession(restOperations -> (ResponseEntity) restOperations .exchange("sys/renew", HttpMethod.PUT, leaseRenewalEntity, Map.class)); Assert.state(entity != null && entity.getBody() != null, "Renew response must not be null"); Map<String, Object> body = entity.getBody(); String leaseId = (String) body.get("lease_id"); Number leaseDuration = (Number) body.get("lease_duration"); boolean renewable = (Boolean) body.get("renewable"); return Lease.of(leaseId, leaseDuration != null ? leaseDuration.longValue() : 0, renewable); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unchecked") private Lease renew(Lease lease) { return operations.doWithSession(restOperations -> leaseEndpoints.renew(lease, restOperations)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean isInitialized() { return requireResponse(vaultOperations.doWithVault(restOperations -> { try { Map<String, Boolean> body = restOperations.getForObject("sys/init", Map.class); Assert.state(body != null, "Initialization response must not be null"); return body.get("initialized"); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } })); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override @SuppressWarnings("unchecked") public boolean isInitialized() { return requireResponse(vaultOperations.doWithSession(restOperations -> { try { ResponseEntity<Map<String, Boolean>> body = (ResponseEntity) restOperations .exchange("sys/init", HttpMethod.GET, emptyNamespace(null), Map.class); Assert.state(body.getBody() != null, "Initialization response must not be null"); return body.getBody().get("initialized"); } catch (HttpStatusCodeException e) { throw VaultResponses.buildException(e); } })); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void shouldAuthenticatePullModeWithGeneratedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData().get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(roleId).secretId(secretId).build(); AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test void shouldAuthenticatePullModeWithGeneratedSecretId() { String roleId = getRoleId("with-secret-id"); String secretId = (String) getVaultOperations() .write(String.format("auth/approle/role/%s/secret-id", "with-secret-id"), null).getRequiredData().get("secret_id"); AppRoleAuthenticationOptions options = AppRoleAuthenticationOptions.builder() .roleId(RoleId.provided(roleId)).secretId(SecretId.provided(secretId)) .build(); AppRoleAuthentication authentication = new AppRoleAuthentication(options, prepare().getRestTemplate()); assertThat(authentication.login()).isNotNull(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean initForceBatchStatementsOrdering(TypedMap configMap) { return configMap.getTypedOr(FORCE_BATCH_STATEMENTS_ORDERING, true); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean initForceBatchStatementsOrdering(TypedMap configMap) { return configMap.getTypedOr(FORCE_BATCH_STATEMENTS_ORDERING, DEFAULT_FORCE_BATCH_STATEMENTS_ORDERING); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private TypeParsingResult parseComputedType(AnnotationTree annotationTree, FieldParsingContext context, TypeName sourceType) { final CodecInfo codecInfo = codecFactory.createCodec(sourceType, annotationTree, context); final TypeName rawTargetType = getRawType(codecInfo.targetType); final TypedMap computed = extractTypedMap(annotationTree, Computed.class).get(); final String alias = computed.getTyped("alias"); CodeBlock extractor = context.buildExtractor ? CodeBlock.builder().add("gettableData$$ -> gettableData$$.$L", TypeUtils.gettableDataGetter(rawTargetType, alias)).build() : NO_GETTER; CodeBlock typeCode = CodeBlock.builder().add("new $T<$T, $T, $T>($L, $L, $L)", COMPUTED_PROPERTY, context.entityRawType, sourceType, codecInfo.targetType, context.fieldInfoCode, extractor, codecInfo.codecCode) .build(); final ParameterizedTypeName propertyType = genericType(COMPUTED_PROPERTY, context.entityRawType, codecInfo.sourceType, codecInfo.targetType); return new TypeParsingResult(context, annotationTree.hasNext() ? annotationTree.next() : annotationTree, sourceType, codecInfo.targetType, propertyType, typeCode); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private TypeParsingResult parseComputedType(AnnotationTree annotationTree, FieldParsingContext context, TypeName sourceType) { final CodecInfo codecInfo = codecFactory.createCodec(sourceType, annotationTree, context, Optional.empty()); final TypeName rawTargetType = getRawType(codecInfo.targetType); final TypedMap computed = extractTypedMap(annotationTree, Computed.class).get(); final String alias = computed.getTyped("alias"); CodeBlock extractor = context.buildExtractor ? CodeBlock.builder().add("gettableData$$ -> gettableData$$.$L", TypeUtils.gettableDataGetter(rawTargetType, alias)).build() : NO_GETTER; CodeBlock typeCode = CodeBlock.builder().add("new $T<$T, $T, $T>($L, $L, $L)", COMPUTED_PROPERTY, context.entityRawType, sourceType, codecInfo.targetType, context.fieldInfoCode, extractor, codecInfo.codecCode) .build(); final ParameterizedTypeName propertyType = genericType(COMPUTED_PROPERTY, context.entityRawType, codecInfo.sourceType, codecInfo.targetType); return new TypeParsingResult(context, annotationTree.hasNext() ? annotationTree.next() : annotationTree, sourceType, codecInfo.targetType, propertyType, typeCode); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PreparedStatement prepareUpdateFields(Session session, EntityMeta entityMeta, List<PropertyMeta> pms) { log.trace("Generate prepared statement for UPDATE properties {}", pms); PropertyMeta idMeta = entityMeta.getIdMeta(); Update update = update(entityMeta.getTableName()); Assignments assignments = null; for (int i = 0; i < pms.size(); i++) { PropertyMeta pm = pms.get(i); if (i == 0) { assignments = update.with(set(pm.getPropertyName(), bindMarker())); } else { assignments.and(set(pm.getPropertyName(), bindMarker())); } } RegularStatement statement = prepareWhereClauseForUpdate(idMeta, assignments); return session.prepare(statement.getQueryString()); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public PreparedStatement prepareUpdateFields(Session session, EntityMeta entityMeta, List<PropertyMeta> pms) { log.trace("Generate prepared statement for UPDATE properties {}", pms); PropertyMeta idMeta = entityMeta.getIdMeta(); Update update = update(entityMeta.getTableName()); Assignments assignments = null; for (int i = 0; i < pms.size(); i++) { PropertyMeta pm = pms.get(i); if (i == 0) { assignments = update.with(set(pm.getPropertyName(), bindMarker())); } else { assignments.and(set(pm.getPropertyName(), bindMarker())); } } RegularStatement statement = prepareWhereClauseForUpdate(idMeta, assignments,true); return session.prepare(statement.getQueryString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void addInterceptorsToEntityMetas(List<Interceptor<?>> interceptors, Map<Class<?>, EntityMeta> entityMetaMap) { for (Interceptor<?> interceptor : interceptors) { Class<?> entityClass = propertyParser.inferEntityClassFromInterceptor(interceptor); EntityMeta entityMeta = entityMetaMap.get(entityClass); Validator.validateBeanMappingTrue(entityMeta != null, "The entity class '%s' is not found", entityClass.getCanonicalName()); entityMeta.forInterception().addInterceptor(interceptor); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void addInterceptorsToEntityMetas(List<Interceptor<?>> interceptors, Map<Class<?>, EntityMeta> entityMetaMap) { for (Interceptor<?> interceptor : interceptors) { Class<?> parentEntityClass = propertyParser.inferEntityClassFromInterceptor(interceptor); final Set<Class<?>> candidateEntityClasses = from(entityMetaMap.keySet()) .filter(new ChildClassOf(parentEntityClass)) .toSet(); for (Class<?> candidateEntityClass : candidateEntityClasses) { final EntityMeta entityMeta = entityMetaMap.get(candidateEntityClass); Validator.validateBeanMappingTrue(entityMeta != null, "The entity class '%s' is not found", parentEntityClass.getCanonicalName()); entityMeta.forInterception().addInterceptor(interceptor); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Map<CQLQueryType, PreparedStatement> prepareClusteredCounterQueryMap(Session session, EntityMeta meta) { PropertyMeta idMeta = meta.getIdMeta(); PropertyMeta counterMeta = meta.getFirstMeta(); String tableName = meta.getTableName(); String counterName = counterMeta.getPropertyName(); RegularStatement incrStatement = prepareWhereClauseForUpdate(idMeta, update(tableName).with(incr(counterName, 100L))); String incr = incrStatement.getQueryString().replaceAll("100", "?"); RegularStatement decrStatement = prepareWhereClauseForUpdate(idMeta, update(tableName).with(decr(counterName, 100L))); String decr = decrStatement.getQueryString().replaceAll("100", "?"); RegularStatement selectStatement = prepareWhereClauseForSelect(idMeta, select(counterName).from(tableName)); String select = selectStatement.getQueryString(); RegularStatement deleteStatement = prepareWhereClauseForDelete(idMeta, QueryBuilder.delete().from(tableName)); String delete = deleteStatement.getQueryString(); Map<CQLQueryType, PreparedStatement> clusteredCounterPSMap = new HashMap<AchillesCounter.CQLQueryType, PreparedStatement>(); clusteredCounterPSMap.put(INCR, session.prepare(incr.toString())); clusteredCounterPSMap.put(DECR, session.prepare(decr.toString())); clusteredCounterPSMap.put(SELECT, session.prepare(select.toString())); clusteredCounterPSMap.put(DELETE, session.prepare(delete.toString())); return clusteredCounterPSMap; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public Map<CQLQueryType, PreparedStatement> prepareClusteredCounterQueryMap(Session session, EntityMeta meta) { PropertyMeta idMeta = meta.getIdMeta(); PropertyMeta counterMeta = meta.getFirstMeta(); String tableName = meta.getTableName(); String counterName = counterMeta.getPropertyName(); RegularStatement incrementStatement = prepareWhereClauseForUpdate(idMeta,update(tableName) .with(incr(counterName, bindMarker())),false); RegularStatement decrementStatement = prepareWhereClauseForUpdate(idMeta,update(tableName) .with(decr(counterName, bindMarker())), false); RegularStatement selectStatement = prepareWhereClauseForSelect(idMeta, select(counterName).from(tableName)); RegularStatement deleteStatement = prepareWhereClauseForDelete(idMeta, QueryBuilder.delete().from(tableName)); Map<CQLQueryType, PreparedStatement> clusteredCounterPSMap = new HashMap<>(); clusteredCounterPSMap.put(INCR, session.prepare(incrementStatement)); clusteredCounterPSMap.put(DECR, session.prepare(decrementStatement)); clusteredCounterPSMap.put(SELECT, session.prepare(selectStatement)); clusteredCounterPSMap.put(DELETE, session.prepare(deleteStatement)); return clusteredCounterPSMap; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final boolean kubernetesEnabled = environment .getProperty("spring.cloud.kubernetes.enabled", Boolean.class, true); if (!kubernetesEnabled) { return; } final StandardPodUtils podUtils = new StandardPodUtils( new DefaultKubernetesClient()); if (podUtils.isInsideKubernetes()) { if (hasKubernetesProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'kubernetes' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'kubernetes' to list of active profiles"); } environment.addActiveProfile(KUBERNETES_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.warn( "Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { final boolean kubernetesEnabled = environment .getProperty("spring.cloud.kubernetes.enabled", Boolean.class, true); if (!kubernetesEnabled) { return; } if (isInsideKubernetes()) { if (hasKubernetesProfile(environment)) { if (LOG.isDebugEnabled()) { LOG.debug("'kubernetes' already in list of active profiles"); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Adding 'kubernetes' to list of active profiles"); } environment.addActiveProfile(KUBERNETES_PROFILE); } } else { if (LOG.isDebugEnabled()) { LOG.warn( "Not running inside kubernetes. Skipping 'kubernetes' profile activation."); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithMessageIdAndAck() throws IOException { Packet packet = decoder.decodePacket("5:1+::{\"name\":\"tobi\"}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Assert.assertEquals("tobi", packet.getName()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeWithMessageIdAndAck() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:1+::{\"name\":\"tobi\"}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Assert.assertEquals("tobi", packet.getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); File resource = resources.get(queryDecoder.path()); if (resource != null) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); if (isNotModified(req, resource)) { sendNotModified(ctx); req.release(); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(resource, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); setContentLength(res, fileLength); setContentTypeHeader(res, resource); setDateAndCacheHeaders(res, resource); // write the response header ctx.write(res); // write the content to the channel ChannelFuture writeFuture = writeContent(raf, fileLength, ctx.channel()); // close the request channel writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } super.channelRead(ctx, msg); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String resource = resources.get(queryDecoder.path()); if (resource != null) { // create ok response HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // set content type HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); // write header ctx.write(res); // create resource inputstream and check InputStream is = getClass().getResourceAsStream(resource); if (is == null) { sendError(ctx, NOT_FOUND); return; } // write the stream ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is)); // close the channel on finish writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } ctx.fireChannelRead(msg); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void disconnect() { ChannelFuture future = send(new Packet(PacketType.DISCONNECT)); future.addListener(ChannelFutureListener.CLOSE); onChannelDisconnect(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void disconnect() { ChannelFuture future = send(new Packet(PacketType.DISCONNECT)); if(future != null) { future.addListener(ChannelFutureListener.CLOSE); } onChannelDisconnect(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doReconnect(Channel channel, HttpRequest req) { isKeepAlive = isKeepAlive(req); this.channel = channel; this.connected = true; sendPayload(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void doReconnect(Channel channel, HttpRequest req) { this.isKeepAlive = HttpHeaders.isKeepAlive(req); this.origin = req.getHeader(HttpHeaders.Names.ORIGIN); this.channel = channel; this.connected = true; sendPayload(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("5:::{\"name\":\"woot\"}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("woot", packet.getName()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"woot\"}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("woot", packet.getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary, boolean jsonp) throws IOException { ByteBuf buf = buffer; if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, packet.getData()); } else { jsonSupport.writeValue(out, packet.getData()); } break; } case MESSAGE: { byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeBytes(new byte[] {','}); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ERROR) { values.add(packet.getName()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK || packet.getSubType() == PacketType.ERROR) { List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, values); } else { if (binary) { // handling websocket encoding bug ByteBuf b = allocateBuffer(allocator); try { ByteBufOutputStream os = new ByteBufOutputStream(b); jsonSupport.writeValue(os, values); CharsetEncoder enc = CharsetUtil.ISO_8859_1.newEncoder(); String str = b.toString(CharsetUtil.ISO_8859_1); if (enc.canEncode(str)) { buf.writeBytes(str.getBytes(CharsetUtil.UTF_8)); } else { buf.writeBytes(b); } } finally { b.release(); } } else { jsonSupport.writeValue(out, values); } } } break; } } if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); } } #location 64 #vulnerability type RESOURCE_LEAK
#fixed code public void encodePacket(Packet packet, ByteBuf buffer, ByteBufAllocator allocator, boolean binary, boolean jsonp) throws IOException { ByteBuf buf = buffer; if (!binary) { buf = allocateBuffer(allocator); } byte type = toChar(packet.getType().getValue()); buf.writeByte(type); switch (packet.getType()) { case PONG: { buf.writeBytes(packet.getData().toString().getBytes(CharsetUtil.UTF_8)); break; } case OPEN: { ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, packet.getData()); } else { jsonSupport.writeValue(out, packet.getData()); } break; } case MESSAGE: { byte subType = toChar(packet.getSubType().getValue()); buf.writeByte(subType); if (packet.getSubType() == PacketType.CONNECT) { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); } } else { if (!packet.getNsp().isEmpty()) { buf.writeBytes(packet.getNsp().getBytes(CharsetUtil.UTF_8)); buf.writeBytes(new byte[] {','}); } } if (packet.getAckId() != null) { byte[] ackId = toChars(packet.getAckId()); buf.writeBytes(ackId); } List<Object> values = new ArrayList<Object>(); if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ERROR) { values.add(packet.getName()); } if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.ACK || packet.getSubType() == PacketType.ERROR) { List<Object> args = packet.getData(); values.addAll(args); ByteBufOutputStream out = new ByteBufOutputStream(buf); if (jsonp) { jsonSupport.writeJsonpValue(out, values); } else { jsonSupport.writeValue(out, values); } } break; } } if (!binary) { buffer.writeByte(0); int length = buf.writerIndex(); buffer.writeBytes(longToBytes(length)); buffer.writeByte(0xff); buffer.writeBytes(buf); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeDisconnection() throws IOException { Packet packet = decoder.decodePacket("0::/woot", null); Assert.assertEquals(PacketType.DISCONNECT, packet.getType()); Assert.assertEquals("/woot", packet.getNsp()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeDisconnection() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("0::/woot", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.DISCONNECT, packet.getType()); Assert.assertEquals("/woot", packet.getNsp()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("3:::woot", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("woot", packet.getData()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:::woot", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("woot", packet.getData()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePacket("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeWithData() throws IOException { JacksonJsonSupport jsonSupport = new JacksonJsonSupport(); jsonSupport.addEventMapping("", "edwald", HashMap.class, Integer.class, String.class); PacketDecoder decoder = new PacketDecoder(jsonSupport, ackManager); Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("5:::{\"name\":\"edwald\",\"args\":[{\"a\": \"b\"},2,\"3\"]}", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.EVENT, packet.getType()); Assert.assertEquals("edwald", packet.getName()); // Assert.assertEquals(3, packet.getArgs().size()); // Map obj = (Map) packet.getArgs().get(0); // Assert.assertEquals("b", obj.get("a")); // Assert.assertEquals(2, packet.getArgs().get(1)); // Assert.assertEquals("3", packet.getArgs().get(2)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithMessageIdAndAckData() throws IOException { Packet packet = decoder.decodePacket("4:1+::{\"a\":\"b\"}", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Map obj = (Map) packet.getData(); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals(1, obj.size()); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeWithMessageIdAndAckData() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:1+::{\"a\":\"b\"}", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertEquals(Packet.ACK_DATA, packet.getAck()); Map obj = (Map) packet.getData(); Assert.assertEquals("b", obj.get("a")); Assert.assertEquals(1, obj.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithArgs() throws IOException { initExpectations(); Packet packet = decoder.decodePacket("6:::12+[\"woot\",\"wa\"]", null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(12, (long)packet.getAckId()); // Assert.assertEquals(Arrays.<Object>asList("woot", "wa"), packet.getArgs()); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeWithArgs() throws IOException { initExpectations(); Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("6:::12+[\"woot\",\"wa\"]", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(12, (long)packet.getAckId()); // Assert.assertEquals(Arrays.<Object>asList("woot", "wa"), packet.getArgs()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testUTF8Decode() throws IOException { Packet packet = decoder.decodePacket("4:::\"Привет\"", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("Привет", packet.getData()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testUTF8Decode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:::\"Привет\"", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("Привет", packet.getData()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeId() throws IOException { Packet packet = decoder.decodePacket("3:1::asdfasdf", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertTrue(packet.getArgs().isEmpty()); // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeId() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:1::asdfasdf", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(1, (long)packet.getId()); // Assert.assertTrue(packet.getArgs().isEmpty()); // Assert.assertTrue(packet.getAck().equals(Boolean.TRUE)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithQueryString() throws IOException { Packet packet = decoder.decodePacket("1::/test:?test=1", null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/test", packet.getNsp()); // Assert.assertEquals("?test=1", packet.getQs()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeWithQueryString() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("1::/test:?test=1", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/test", packet.getNsp()); // Assert.assertEquals("?test=1", packet.getQs()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("6:::140", null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(140, (long)packet.getAckId()); // Assert.assertTrue(packet.getArgs().isEmpty()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("6:::140", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.ACK, packet.getType()); Assert.assertEquals(140, (long)packet.getAckId()); // Assert.assertTrue(packet.getArgs().isEmpty()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodingNewline() throws IOException { Packet packet = decoder.decodePacket("3:::\n", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("\n", packet.getData()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodingNewline() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:::\n", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); Assert.assertEquals("\n", packet.getData()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("4:::\"2\"", null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("2", packet.getData()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("4:::\"2\"", CharsetUtil.UTF_8), null); // Assert.assertEquals(PacketType.JSON, packet.getType()); Assert.assertEquals("2", packet.getData()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePacket("1::/tobi", null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/tobi", packet.getNsp()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecode() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("1::/tobi", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.CONNECT, packet.getType()); Assert.assertEquals("/tobi", packet.getNsp()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDecodeWithIdAndEndpoint() throws IOException { Packet packet = decoder.decodePacket("3:5:/tobi", null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(5, (long)packet.getId()); // Assert.assertEquals(true, packet.getAck()); Assert.assertEquals("/tobi", packet.getNsp()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDecodeWithIdAndEndpoint() throws IOException { Packet packet = decoder.decodePackets(Unpooled.copiedBuffer("3:5:/tobi", CharsetUtil.UTF_8), null); Assert.assertEquals(PacketType.MESSAGE, packet.getType()); // Assert.assertEquals(5, (long)packet.getId()); // Assert.assertEquals(true, packet.getAck()); Assert.assertEquals("/tobi", packet.getNsp()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); File resource = resources.get(queryDecoder.path()); if (resource != null) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); if (isNotModified(req, resource)) { sendNotModified(ctx); req.release(); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(resource, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); setContentLength(res, fileLength); setContentTypeHeader(res, resource); setDateAndCacheHeaders(res, resource); // write the response header ctx.write(res); // write the content to the channel ChannelFuture writeFuture = writeContent(raf, fileLength, ctx.channel()); // close the request channel writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } super.channelRead(ctx, msg); } #location 32 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) msg; QueryStringDecoder queryDecoder = new QueryStringDecoder(req.getUri()); String resource = resources.get(queryDecoder.path()); if (resource != null) { // create ok response HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); // set content type HttpHeaders.setHeader(res, HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream"); // write header ctx.write(res); // create resource inputstream and check InputStream is = getClass().getResourceAsStream(resource); if (is == null) { sendError(ctx, NOT_FOUND); return; } // write the stream ChannelFuture writeFuture = ctx.channel().write(new ChunkedStream(is)); // close the channel on finish writeFuture.addListener(ChannelFutureListener.CLOSE); return; } } ctx.fireChannelRead(msg); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBench1() throws Exception { if (System.getProperty("skipBenchmark") != null && System.getProperty("skipBenchmark").equals("true")) { System.out.println(":: skipping naive benchmarks..."); return; } System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; Calculable calc = new ExpressionBuilder(expr).build(); double val = 0; Random rnd = new Random(); long timeout = 2; long time = System.currentTimeMillis() + (1000 * timeout); int count = 0; while (time > System.currentTimeMillis()) { calc.setVariable("x", rnd.nextDouble()); calc.setVariable("y", rnd.nextDouble()); val = calc.calculate(); count++; } System.out.println("\n:: [PostfixExpression] simple benchmark"); System.out.println("expression\t\t" + expr); double rate = count / timeout; System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); time = System.currentTimeMillis() + (1000 * timeout); double x, y; count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); } else { time = System.currentTimeMillis() + (1000 * timeout); count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); count++; } rate = count / timeout; System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); } } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testBench1() throws Exception { if (System.getProperty("skipBenchmark") != null) { System.out.println(":: skipping naive benchmarks..."); return; } System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; Calculable calc = new ExpressionBuilder(expr).build(); double val = 0; Random rnd = new Random(); long timeout = 2; long time = System.currentTimeMillis() + (1000 * timeout); int count = 0; while (time > System.currentTimeMillis()) { calc.setVariable("x", rnd.nextDouble()); calc.setVariable("y", rnd.nextDouble()); val = calc.calculate(); count++; } System.out.println("\n:: running simple benchmarks [" + timeout + " seconds]"); System.out.println("expression\t\t" + expr); double rate = count / timeout; System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); time = System.currentTimeMillis() + (1000 * timeout); double x, y; count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); count++; } rate = count / timeout; System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); if (engine == null) { System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); } else { time = System.currentTimeMillis() + (1000 * timeout); count = 0; while (time > System.currentTimeMillis()) { x = rnd.nextDouble(); y = rnd.nextDouble(); engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); count++; } rate = count / timeout; System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canUpsertWithWriteConcern() throws Exception { WriteConcern writeConcern = spy(WriteConcern.SAFE); /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}", writeConcern); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); verify(writeConcern).callGetLastError(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canUpsertWithWriteConcern() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().concern(WriteConcern.SAFE).with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); assertThat(writeResult.getLastConcern()).isEqualTo(WriteConcern.SAFE); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ String idAsString = collection.save(new People("John", "21 Jump Street")); ObjectId id = new ObjectId(idAsString); People people = collection.findOne(id).as(People.class); people.setAddress("new address"); /* when */ collection.save(people); /* then */ people = collection.findOne(id).as(People.class); assertThat(people.getId()).isEqualTo(id); assertThat(people.getAddress()).isEqualTo("new address"); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ People john = new People("John", "21 Jump Street"); collection.save(john); john.setAddress("new address"); /* when */ collection.save(john); /* then */ ObjectId johnId = john.getId(); People johnWithNewAddress = collection.findOne(johnId).as(People.class); assertThat(johnWithNewAddress.getId()).isEqualTo(johnId); assertThat(johnWithNewAddress.getAddress()).isEqualTo("new address"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canFindOne() throws Exception { /* given */ String id = collection.save(this.people); /* when */ People people = collection.findOne("{name:#}", "John").as(People.class); /* then */ assertThat(people.getId()).isEqualTo(id); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canFindOne() throws Exception { /* given */ String id = collection.save(new People("John", new Coordinate(1, 1))); /* when */ People result = collection.findOne("{name:#}", "John").as(People.class); /* then */ assertThat(result.getId()).isEqualTo(id); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ String idAsString = collection.save(new People("John", "21 Jump Street")); ObjectId id = new ObjectId(idAsString); People people = collection.findOne(id).as(People.class); people.setAddress("new address"); /* when */ collection.save(people); /* then */ people = collection.findOne(id).as(People.class); assertThat(people.getId()).isEqualTo(id); assertThat(people.getAddress()).isEqualTo("new address"); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canModifyAlreadySavedEntity() throws Exception { /* given */ People john = new People("John", "21 Jump Street"); collection.save(john); john.setAddress("new address"); /* when */ collection.save(john); /* then */ ObjectId johnId = john.getId(); People johnWithNewAddress = collection.findOne(johnId).as(People.class); assertThat(johnWithNewAddress.getId()).isEqualTo(johnId); assertThat(johnWithNewAddress.getAddress()).isEqualTo("new address"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test //https://groups.google.com/forum/?fromgroups#!topic/jongo-user/p9CEKnkKX9Q public void canUpdateIntoAnArray() throws Exception { collection.insert("{friends:[{name:'Robert'},{name:'Peter'}]}"); collection.update("{ 'friends.name' : 'Peter' }").with("{ $set : { 'friends.$' : #} }", new Friend("John")); Friends friends = collection.findOne().as(Friends.class); assertThat(friends.friends).onProperty("name").containsExactly("Robert", "John"); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test //https://groups.google.com/forum/?fromgroups#!topic/jongo-user/p9CEKnkKX9Q public void canUpdateIntoAnArray() throws Exception { collection.insert("{friends:[{name:'Robert'},{name:'Peter'}]}"); collection.update("{ 'friends.name' : 'Peter' }").with("{ $set : { 'friends.$' : #} }", new Friend("John")); Party party = collection.findOne().as(Party.class); assertThat(party.friends).onProperty("name").containsExactly("Robert", "John"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canFindOneWithObjectId() throws Exception { /* given */ People john = new People("John", "22 Wall Street Avenue"); collection.save(john); People foundPeople = collection.findOne(john.getId()).as(People.class); /* then */ assertThat(foundPeople).isNotNull(); assertThat(foundPeople.getId()).isEqualTo(john.getId()); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canFindOneWithObjectId() throws Exception { /* given */ Friend john = new Friend("John", "22 Wall Street Avenue"); collection.save(john); Friend foundFriend = collection.findOne(john.getId()).as(Friend.class); /* then */ assertThat(foundFriend).isNotNull(); assertThat(foundFriend.getId()).isEqualTo(john.getId()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canFindOneWithEmptyQuery() throws Exception { /* given */ collection.save(new People("John", "22 Wall Street Avenue")); /* when */ People people = collection.findOne().as(People.class); /* then */ assertThat(people.getName()).isEqualTo("John"); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canFindOneWithEmptyQuery() throws Exception { /* given */ collection.save(new Friend("John", "22 Wall Street Avenue")); /* when */ Friend friend = collection.findOne().as(Friend.class); /* then */ assertThat(friend.getName()).isEqualTo("John"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canSaveAnObjectWithAnObjectId() throws Exception { People john = new People(new ObjectId("47cc67093475061e3d95369d"), "John"); String id = collection.save(john); People result = collection.findOne(new ObjectId(id)).as(People.class); assertThat(result).isNotNull(); assertThat(result.getId()).isEqualTo("47cc67093475061e3d95369d"); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canSaveAnObjectWithAnObjectId() throws Exception { People john = new People(new ObjectId("47cc67093475061e3d95369d"), "John"); collection.save(john); People result = collection.findOne(new ObjectId("47cc67093475061e3d95369d")).as(People.class); assertThat(result).isNotNull(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canFindOne() throws Exception { /* given */ collection.save(new People("John", "22 Wall Street Avenue")); /* when */ People people = collection.findOne("{name:'John'}").as(People.class); /* then */ assertThat(people.getName()).isEqualTo("John"); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canFindOne() throws Exception { /* given */ collection.save(new Friend("John", "22 Wall Street Avenue")); /* when */ Friend friend = collection.findOne("{name:'John'}").as(Friend.class); /* then */ assertThat(friend.getName()).isEqualTo("John"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.upsert("{}", "{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void canUpsert() throws Exception { /* when */ WriteResult writeResult = collection.update("{}").upsert().with("{$set:{name:'John'}}"); /* then */ People john = collection.findOne("{name:'John'}").as(People.class); assertThat(john.getName()).isEqualTo("John"); assertThat(writeResult).isNotNull(); }
Below is the vulnerable code, please generate the patch based on the following information.