input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
@Override
public Event applySetIntSet(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueSet o11 = new KeyStringValueSet();
String key = parser.rdbLoadEncodedStringObject().string;
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<String> set = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
long lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (long i = 0; i < lenOfContent; i++) {
switch (encoding) {
case 2:
set.add(String.valueOf(stream.readInt(2)));
break;
case 4:
set.add(String.valueOf(stream.readInt(4)));
break;
case 8:
set.add(String.valueOf(stream.readLong(8)));
break;
default:
throw new AssertionError("expect encoding [2,4,8] but:" + encoding);
}
}
o11.setValueRdbType(RDB_TYPE_SET_INTSET);
o11.setValue(set);
o11.setDb(db);
o11.setKey(key);
return o11;
}
#location 31
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public Event applySetIntSet(RedisInputStream in, DB db, int version) throws IOException {
/*
* |<encoding>| <length-of-contents>| <contents> |
* | 4 bytes | 4 bytes | 2 bytes lement| 4 bytes element | 8 bytes element |
*/
BaseRdbParser parser = new BaseRdbParser(in);
KeyStringValueSet o11 = new KeyStringValueSet();
byte[] key = parser.rdbLoadEncodedStringObject().first();
ByteArray aux = parser.rdbLoadPlainStringObject();
RedisInputStream stream = new RedisInputStream(new ByteArrayInputStream(aux));
Set<String> set = new LinkedHashSet<>();
Set<byte[]> rawSet = new LinkedHashSet<>();
int encoding = BaseRdbParser.LenHelper.encoding(stream);
long lenOfContent = BaseRdbParser.LenHelper.lenOfContent(stream);
for (long i = 0; i < lenOfContent; i++) {
switch (encoding) {
case 2:
String element = String.valueOf(stream.readInt(2));
set.add(element);
rawSet.add(element.getBytes());
break;
case 4:
element = String.valueOf(stream.readInt(4));
set.add(element);
rawSet.add(element.getBytes());
break;
case 8:
element = String.valueOf(stream.readLong(8));
set.add(element);
rawSet.add(element.getBytes());
break;
default:
throw new AssertionError("expect encoding [2,4,8] but:" + encoding);
}
}
o11.setValueRdbType(RDB_TYPE_SET_INTSET);
o11.setValue(set);
o11.setRawValue(rawSet);
o11.setDb(db);
o11.setKey(new String(key, CHARSET));
o11.setRawKey(key);
return o11;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 58
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (hashProgress.isProgressDisplayed())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgress.hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
hashProgress.progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
hashProgress.progressOutputStop();
displayStatistics(start, state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new DefaultParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
#location 97
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new DefaultParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
String fimRepositoryDirectory = null;
boolean alwaysYes = false;
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
fimRepositoryDirectory = commandLine.getOptionValue('d');
alwaysYes = commandLine.hasOption('y');
if (command == Command.REMOVE_DUPLICATES && fimRepositoryDirectory == null)
{
System.out.println("The Fim repository directory must be provided");
printUsage();
System.exit(-1);
}
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(-1);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIM_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State state;
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (alwaysYes || confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case REMOVE_DUPLICATES:
fastCompareNotSupported(compareMode);
File repository = new File(fimRepositoryDirectory);
if (!repository.exists())
{
System.out.printf("Directory %s does not exist%n", fimRepositoryDirectory);
System.exit(-1);
}
if (repository.getCanonicalPath().equals(baseDirectory.getCanonicalPath()))
{
System.out.printf("Cannot remove duplicates from the current directory%n");
System.exit(-1);
}
File fimDir = new File(repository, StateGenerator.FIM_DIR);
if (!fimDir.exists())
{
System.out.printf("Directory %s is not a Fim repository%n", fimRepositoryDirectory);
System.exit(-1);
}
System.out.println("Searching for duplicated files using the " + fimRepositoryDirectory + " directory as master");
System.out.println("");
File otherStateDir = new File(fimDir, "states");
StateManager otherManager = new StateManager(otherStateDir, CompareMode.FULL);
State otherState = otherManager.loadLastState();
Map<String, FileState> otherHashes = new HashMap<>();
for (FileState otherFileState : otherState.getFileStates())
{
otherHashes.put(otherFileState.getHash(), otherFileState);
}
State localState = generator.generateState(message, baseDirectory);
for (FileState localFileState : localState.getFileStates())
{
FileState otherFileState = otherHashes.get(localFileState.getHash());
if (otherFileState != null)
{
System.out.printf("%s is a duplicate of %s/%s%n", localFileState.getFileName(), fimRepositoryDirectory, otherFileState.getFileName());
if (alwaysYes || confirmCommand("remove it"))
{
System.out.printf(" %s removed%n", localFileState.getFileName());
File localFile = new File(localFileState.getFileName());
localFile.delete();
}
}
}
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = new State();
state.loadFromGZipFile(stateFile);
// Replace by 'no_hash' accurately to be able to compare the FileState entry
switch (parameters.getHashMode())
{
case DONT_HASH_FILES:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_FOUR_KILO:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_MEGA:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case COMPUTE_ALL_HASH:
// Nothing to do
break;
}
return state;
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = State.loadFromGZipFile(stateFile);
adjustAccordingToHashMode(state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new GnuParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State previousState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
previousState = manager.loadPreviousState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(previousState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
previousState = manager.loadPreviousState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(previousState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadPreviousState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
previousState = manager.loadPreviousState();
manager.resetDates(previousState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
#location 106
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void main(String[] args) throws IOException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new GnuParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public DuplicateResult findDuplicates(State state)
{
DuplicateResult result = new DuplicateResult(parameters);
List<FileState> fileStates = new ArrayList<>(state.getFileStates());
Collections.sort(fileStates, fullHashComparator);
FileHash previousHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH);
for (FileState fileState : fileStates)
{
if (!previousHash.equals(fileState.getFileHash()))
{
result.addDuplicatedFiles(duplicatedFiles);
duplicatedFiles.clear();
}
previousHash = fileState.getFileHash();
duplicatedFiles.add(fileState);
}
result.addDuplicatedFiles(duplicatedFiles);
return result;
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public DuplicateResult findDuplicates(State state)
{
DuplicateResult result = new DuplicateResult(parameters);
List<FileState> fileStates = new ArrayList<>(state.getFileStates());
Collections.sort(fileStates, hashComparator);
List<FileState> duplicatedFiles = new ArrayList<>();
FileHash previousFileHash = new FileHash(FileState.NO_HASH, FileState.NO_HASH, FileState.NO_HASH);
for (FileState fileState : fileStates)
{
if (!previousFileHash.equals(fileState.getFileHash()))
{
result.addDuplicatedFiles(duplicatedFiles);
duplicatedFiles.clear();
}
previousFileHash = fileState.getFileHash();
duplicatedFiles.add(fileState);
}
result.addDuplicatedFiles(duplicatedFiles);
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new DefaultParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
#location 106
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void main(String[] args) throws IOException, NoSuchAlgorithmException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new DefaultParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
String fimRepositoryDirectory = null;
boolean alwaysYes = false;
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
fimRepositoryDirectory = commandLine.getOptionValue('d');
alwaysYes = commandLine.hasOption('y');
if (command == Command.REMOVE_DUPLICATES && fimRepositoryDirectory == null)
{
System.out.println("The Fim repository directory must be provided");
printUsage();
System.exit(-1);
}
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(-1);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIM_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State state;
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (alwaysYes || confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case REMOVE_DUPLICATES:
fastCompareNotSupported(compareMode);
File repository = new File(fimRepositoryDirectory);
if (!repository.exists())
{
System.out.printf("Directory %s does not exist%n", fimRepositoryDirectory);
System.exit(-1);
}
if (repository.getCanonicalPath().equals(baseDirectory.getCanonicalPath()))
{
System.out.printf("Cannot remove duplicates from the current directory%n");
System.exit(-1);
}
File fimDir = new File(repository, StateGenerator.FIM_DIR);
if (!fimDir.exists())
{
System.out.printf("Directory %s is not a Fim repository%n", fimRepositoryDirectory);
System.exit(-1);
}
System.out.println("Searching for duplicated files using the " + fimRepositoryDirectory + " directory as master");
System.out.println("");
File otherStateDir = new File(fimDir, "states");
StateManager otherManager = new StateManager(otherStateDir, CompareMode.FULL);
State otherState = otherManager.loadLastState();
Map<String, FileState> otherHashes = new HashMap<>();
for (FileState otherFileState : otherState.getFileStates())
{
otherHashes.put(otherFileState.getHash(), otherFileState);
}
State localState = generator.generateState(message, baseDirectory);
for (FileState localFileState : localState.getFileStates())
{
FileState otherFileState = otherHashes.get(localFileState.getHash());
if (otherFileState != null)
{
System.out.printf("%s is a duplicate of %s/%s%n", localFileState.getFileName(), fimRepositoryDirectory, otherFileState.getFileName());
if (alwaysYes || confirmCommand("remove it"))
{
System.out.printf(" %s removed%n", localFileState.getFileName());
File localFile = new File(localFileState.getFileName());
localFile.delete();
}
}
}
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 38
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public State generateState(String comment, Path rootDir, Path dirToScan) throws NoSuchAlgorithmException
{
this.rootDir = rootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(context.getHashMode()), context.getThreadCount()));
if (hashProgress.isProgressDisplayed())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgress.hashProgressLegend());
}
State state = new State();
state.setComment(comment);
state.setHashMode(context.getHashMode());
long start = System.currentTimeMillis();
hashProgress.progressOutputInit();
filesToHashQueue = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
initializeFileHashers();
Path userDir = Paths.get(System.getProperty("user.dir"));
List<FileToIgnore> globalIgnore = fimIgnoreManager.loadFimIgnore(userDir);
scanFileTree(filesToHashQueue, dirToScan, globalIgnore);
// In case the FileHashers have not already been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
state.setIgnoredFiles(fimIgnoreManager.getIgnoredFiles());
hashProgress.progressOutputStop();
displayStatistics(start, state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void outputInit() {
summedFileLength = 0;
fileCount = 0;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void outputInit() {
progressLock.lock();
try {
summedFileLength = 0;
fileCount = 0;
} finally {
progressLock.unlock();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 63
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = new State();
state.loadFromGZipFile(stateFile);
// Replace by 'no_hash' accurately to be able to compare the FileState entry
switch (parameters.getHashMode())
{
case DONT_HASH_FILES:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_FOUR_KILO:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_MEGA:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case COMPUTE_ALL_HASH:
// Nothing to do
break;
}
return state;
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = State.loadFromGZipFile(stateFile);
adjustAccordingToHashMode(state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 53
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private boolean resetDosPermissions(Path file, FileState fileState, DosFileAttributes dosFileAttributes)
{
String permissions = DosFilePermissions.toString(dosFileAttributes);
String previousPermissions = getAttribute(fileState, FileAttribute.DosFilePermissions);
if (!Objects.equals(permissions, previousPermissions))
{
DosFilePermissions.setPermissions(file, previousPermissions);
System.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions, previousPermissions);
return true;
}
return false;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private boolean resetDosPermissions(Path file, FileState fileState, DosFileAttributes dosFileAttributes)
{
String permissions = DosFilePermissions.toString(dosFileAttributes);
String previousPermissions = getAttribute(fileState, FileAttribute.DosFilePermissions);
if (previousPermissions != null && !Objects.equals(permissions, previousPermissions))
{
DosFilePermissions.setPermissions(file, previousPermissions);
System.out.printf("Set permissions: %s \t%s -> %s%n", fileState.getFileName(), permissions, previousPermissions);
return true;
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 33
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
this.fimRepositoryRootDir = fimRepositoryRootDir;
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
if (displayHashLegend())
{
System.out.printf("(Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
}
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY);
InitializeFileHashers();
scanFileTree(filesToHash, fimRepositoryRootDir);
// In case the FileHashers have not been started
startFileHashers();
waitAllFilesToBeHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void displayDifferences(PrintStream out, Context context, String actionStr,
List<Difference> differences, Consumer<Difference> displayOneDifference) {
int truncateOutput = context.getTruncateOutput();
if (truncateOutput < 1) {
return;
}
int quarter = truncateOutput / 4;
int differencesSize = differences.size();
for (int index = 0; index < differencesSize; index++) {
Difference difference = differences.get(index);
if (index >= truncateOutput && (differencesSize - index) > quarter) {
out.println(" [Too many lines. Truncating the output] ...");
int moreFiles = differencesSize - index;
out.printf(actionStr + "%d %s more%n", moreFiles, plural("file", moreFiles));
break;
}
if (displayOneDifference != null) {
displayOneDifference.accept(difference);
}
}
}
#location 16
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public static void displayDifferences(PrintStream out, Context context, String actionStr,
List<Difference> differences, Consumer<Difference> displayOneDifference) {
int truncateOutput = context.getTruncateOutput();
if (truncateOutput < 1) {
return;
}
int quarter = truncateOutput / 4;
int differencesSize = differences.size();
for (int index = 0; index < differencesSize; index++) {
Difference difference = differences.get(index);
if (index >= truncateOutput && (differencesSize - index) > quarter) {
out.println(" [Too many lines. Truncating the output] ...");
int moreFiles = differencesSize - index;
out.printf("%s%d %s more%n", actionStr, moreFiles, plural("file", moreFiles));
break;
}
if (displayOneDifference != null) {
displayOneDifference.accept(difference);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = new State();
state.loadFromGZipFile(stateFile);
// Replace by 'no_hash' accurately to be able to compare the FileState entry
switch (parameters.getHashMode())
{
case DONT_HASH_FILES:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_FOUR_KILO:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstMegaHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case HASH_ONLY_FIRST_MEGA:
for (FileState fileState : state.getFileStates())
{
fileState.getFileHash().setFirstFourKiloHash(FileState.NO_HASH);
fileState.getFileHash().setFullHash(FileState.NO_HASH);
}
break;
case COMPUTE_ALL_HASH:
// Nothing to do
break;
}
return state;
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public State loadState(int stateNumber) throws IOException
{
File stateFile = getStateFile(stateNumber);
if (!stateFile.exists())
{
throw new IllegalStateException(String.format("Unable to load State file %d from directory %s", stateNumber, stateDir));
}
State state = State.loadFromGZipFile(stateFile);
adjustAccordingToHashMode(state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 48
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 23
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public State generateState(String comment, File fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
System.out.printf(" (Hash progress legend: " + hashProgressLegend() + ")%n");
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
BlockingDeque<File> filesToHash = new LinkedBlockingDeque<>(1000);
List<FileHasher> hashers = new ArrayList<>();
executorService = Executors.newFixedThreadPool(parameters.getThreadCount());
for (int index = 0; index < parameters.getThreadCount(); index++)
{
FileHasher hasher = new FileHasher(this, filesToHash, fimRepositoryRootDir.toString());
executorService.submit(hasher);
hashers.add(hasher);
}
scanFileTree(filesToHash, fimRepositoryRootDir);
waitAllFileHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
#location 4
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public State generateState(String comment, File fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException
{
Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount()));
System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend());
State state = new State();
state.setComment(comment);
long start = System.currentTimeMillis();
progressOutputInit();
BlockingDeque<File> filesToHash = new LinkedBlockingDeque<>(1000);
List<FileHasher> hashers = new ArrayList<>();
executorService = Executors.newFixedThreadPool(parameters.getThreadCount());
for (int index = 0; index < parameters.getThreadCount(); index++)
{
FileHasher hasher = new FileHasher(this, filesToHash, fimRepositoryRootDir.toString());
executorService.submit(hasher);
hashers.add(hasher);
}
scanFileTree(filesToHash, fimRepositoryRootDir);
waitAllFileHashed();
for (FileHasher hasher : hashers)
{
state.getFileStates().addAll(hasher.getFileStates());
totalFileContentLength += hasher.getTotalFileContentLength();
totalBytesHashed += hasher.getTotalBytesHashed();
}
Collections.sort(state.getFileStates(), fileNameComparator);
progressOutputStop();
displayStatistics(start, state);
return state;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
for (Difference diff : added)
{
System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName());
}
for (Difference diff : copied)
{
System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName());
}
for (Difference diff : duplicated)
{
System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : dateModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : contentModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : attributesModified)
{
System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
for (Difference diff : renamed)
{
System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true));
}
for (Difference diff : deleted)
{
System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName());
}
for (Difference diff : corrupted)
{
System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false));
}
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
#location 43
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public CompareResult displayChanges()
{
if (lastState != null)
{
System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp()));
if (lastState.getComment().length() > 0)
{
System.out.println("Comment: " + lastState.getComment());
}
Console.newLine();
}
if (!context.isVerbose())
{
displayCounts();
return this;
}
String stateFormat = "%-17s ";
final String addedStr = String.format(stateFormat, "Added:");
displayDifferences(addedStr, added,
diff -> System.out.printf(addedStr + "%s%n", diff.getFileState().getFileName()));
final String copiedStr = String.format(stateFormat, "Copied:");
displayDifferences(copiedStr, copied,
diff -> System.out.printf(copiedStr + "%s \t(was %s)%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()));
final String duplicatedStr = String.format(stateFormat, "Duplicated:");
displayDifferences(duplicatedStr, duplicated,
diff -> System.out.printf(duplicatedStr + "%s = %s%s%n", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String dateModifiedStr = String.format(stateFormat, "Date modified:");
displayDifferences(dateModifiedStr, dateModified,
diff -> System.out.printf(dateModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String contentModifiedStr = String.format(stateFormat, "Content modified:");
displayDifferences(contentModifiedStr, contentModified,
diff -> System.out.printf(contentModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String attrsModifiedStr = String.format(stateFormat, "Attrs. modified:");
displayDifferences(attrsModifiedStr, attributesModified,
diff -> System.out.printf(attrsModifiedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
final String renamedStr = String.format(stateFormat, "Renamed:");
displayDifferences(renamedStr, renamed,
diff -> System.out.printf(renamedStr + "%s -> %s%s%n", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)));
final String deletedStr = String.format(stateFormat, "Deleted:");
displayDifferences(deletedStr, deleted,
diff -> System.out.printf(deletedStr + "%s%n", diff.getFileState().getFileName()));
final String corruptedStr = String.format(stateFormat, "Corrupted?:");
displayDifferences(corruptedStr, corrupted,
diff -> System.out.printf(corruptedStr + "%s \t%s%n", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)));
if (somethingModified())
{
Console.newLine();
}
displayCounts();
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void outputInit() {
summedFileLength = 0;
fileCount = 0;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void outputInit() {
progressLock.lock();
try {
summedFileLength = 0;
fileCount = 0;
} finally {
progressLock.unlock();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new GnuParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State previousState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
previousState = manager.loadPreviousState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(previousState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
previousState = manager.loadPreviousState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(previousState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadPreviousState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
previousState = manager.loadPreviousState();
manager.resetDates(previousState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
#location 124
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void main(String[] args) throws IOException
{
String[] filteredArgs = filterEmptyArgs(args);
if (filteredArgs.length < 1)
{
youMustSpecifyACommandToRun();
}
Command command = Command.fromName(filteredArgs[0]);
if (command == null)
{
youMustSpecifyACommandToRun();
}
CommandLineParser cmdLineGnuParser = new GnuParser();
Options options = constructOptions();
CommandLine commandLine;
boolean verbose = true;
CompareMode compareMode = CompareMode.FULL;
String message = "";
boolean useLastState = false;
int threadCount = Runtime.getRuntime().availableProcessors();
try
{
String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length);
commandLine = cmdLineGnuParser.parse(options, actionArgs);
if (commandLine.hasOption("h"))
{
printUsage();
System.exit(0);
}
else
{
verbose = !commandLine.hasOption('q');
compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL;
message = commandLine.getOptionValue('m', message);
threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount));
useLastState = commandLine.hasOption('l');
}
}
catch (Exception ex)
{
printUsage();
System.exit(-1);
}
if (compareMode == CompareMode.FAST)
{
threadCount = 1;
System.out.println("Using fast compare mode. Thread count forced to 1");
}
if (threadCount < 1)
{
System.out.println("Thread count must be at least one");
System.exit(0);
}
File baseDirectory = new File(".");
File stateDir = new File(StateGenerator.FIC_DIR, "states");
if (command == Command.INIT)
{
if (stateDir.exists())
{
System.out.println("fim repository already exist");
System.exit(0);
}
}
else
{
if (!stateDir.exists())
{
System.out.println("fim repository does not exist. Please run 'fim init' before.");
System.exit(-1);
}
}
State lastState;
State currentState;
StateGenerator generator = new StateGenerator(threadCount, compareMode);
StateManager manager = new StateManager(stateDir, compareMode);
StateComparator comparator = new StateComparator(compareMode);
DuplicateFinder finder = new DuplicateFinder();
switch (command)
{
case INIT:
fastCompareNotSupported(compareMode);
stateDir.mkdirs();
currentState = generator.generateState("Initial State", baseDirectory);
comparator.compare(null, currentState).displayChanges(verbose);
manager.createNewState(currentState);
break;
case COMMIT:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
CompareResult result = comparator.compare(lastState, currentState).displayChanges(verbose);
if (result.somethingModified())
{
System.out.println("");
if (confirmCommand("commit"))
{
manager.createNewState(currentState);
}
else
{
System.out.println("Nothing committed");
}
}
break;
case DIFF:
lastState = manager.loadLastState();
currentState = generator.generateState(message, baseDirectory);
comparator.compare(lastState, currentState).displayChanges(verbose);
break;
case FIND_DUPLICATES:
fastCompareNotSupported(compareMode);
System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : ""));
System.out.println("");
State state;
if (useLastState)
{
state = manager.loadLastState();
}
else
{
state = generator.generateState(message, baseDirectory);
}
finder.findDuplicates(state).displayDuplicates(verbose);
break;
case RESET_DATES:
fastCompareNotSupported(compareMode);
lastState = manager.loadLastState();
manager.resetDates(lastState);
break;
case LOG:
manager.displayStatesLog();
break;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getNumberOfFeatures(){
List<?> coefs = getCoefs();
NDArray input = (NDArray)coefs.get(0);
int[] shape = NDArrayUtil.getShape(input);
return shape[0];
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getNumberOfFeatures(){
List<? extends HasArray> coefs = getCoefs();
return NeuralNetworkUtil.getNumberOfFeatures(coefs);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Expression encode(int index, FieldName name){
Expression expression = new FieldRef(name);
if(withMean()){
Number mean = Iterables.get(getMean(), index);
if(Double.compare(mean.doubleValue(), 0d) != 0){
expression = PMMLUtil.createApply("-", expression, PMMLUtil.createConstant(mean));
}
} // End if
if(withStd()){
Number std = Iterables.get(getStd(), index);
if(Double.compare(std.doubleValue(), 1d) != 0){
expression = PMMLUtil.createApply("/", expression, PMMLUtil.createConstant(std));
}
}
// "($name - mean) / std"
return expression;
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public Expression encode(int index, FieldName name){
Expression expression = new FieldRef(name);
if(getWithMean()){
Number mean = Iterables.get(getMean(), index);
if(Double.compare(mean.doubleValue(), 0d) != 0){
expression = PMMLUtil.createApply("-", expression, PMMLUtil.createConstant(mean));
}
} // End if
if(gwtWithStd()){
Number std = Iterables.get(getStd(), index);
if(Double.compare(std.doubleValue(), 1d) != 0){
expression = PMMLUtil.createApply("/", expression, PMMLUtil.createConstant(std));
}
}
// "($name - mean) / std"
return expression;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private List<? extends Number> getNodeAttribute(String key){
NDArrayWrapper nodes = (NDArrayWrapper)get("nodes");
Map<String, ?> content = (Map<String, ?>)nodes.getContent();
return (List<? extends Number>)content.get(key);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private List<? extends Number> getNodeAttribute(String key){
List<? extends Number> nodeAttributes = (List<? extends Number>)ClassDictUtil.getArray(this, "nodes", key);
return nodeAttributes;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public List<?> getArray(ClassDict dict, String name, String key){
NDArrayWrapper arrayWrapper = (NDArrayWrapper)dict.get(name);
NDArray array = arrayWrapper.getContent();
return NDArrayUtil.getData(array, key);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public List<?> getArray(ClassDict dict, String name, String key){
Object object = dict.get(name);
if(object instanceof NDArrayWrapper){
NDArrayWrapper arrayWrapper = (NDArrayWrapper)object;
NDArray array = arrayWrapper.getContent();
return NDArrayUtil.getContent(array, key);
}
throw new IllegalArgumentException();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public List<?> getArray(ClassDict dict, String name, String key){
NDArrayWrapper nodes = (NDArrayWrapper)dict.get(name);
Map<String, ?> content = (Map<String, ?>)nodes.getContent();
return toArray(content.get(key));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public List<?> getArray(ClassDict dict, String name, String key){
NDArrayWrapper arrayWrapper = (NDArrayWrapper)dict.get(name);
NDArray array = arrayWrapper.getContent();
return NDArrayUtil.getData(array, key);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Expression encode(int index, FieldName name){
Expression expression = new FieldRef(name);
if(withMean()){
Number mean = Iterables.get(getMean(), index);
if(Double.compare(mean.doubleValue(), 0d) != 0){
expression = PMMLUtil.createApply("-", expression, PMMLUtil.createConstant(mean));
}
} // End if
if(withStd()){
Number std = Iterables.get(getStd(), index);
if(Double.compare(std.doubleValue(), 1d) != 0){
expression = PMMLUtil.createApply("/", expression, PMMLUtil.createConstant(std));
}
}
// "($name - mean) / std"
return expression;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public Expression encode(int index, FieldName name){
Expression expression = new FieldRef(name);
if(getWithMean()){
Number mean = Iterables.get(getMean(), index);
if(Double.compare(mean.doubleValue(), 0d) != 0){
expression = PMMLUtil.createApply("-", expression, PMMLUtil.createConstant(mean));
}
} // End if
if(gwtWithStd()){
Number std = Iterables.get(getStd(), index);
if(Double.compare(std.doubleValue(), 1d) != 0){
expression = PMMLUtil.createApply("/", expression, PMMLUtil.createConstant(std));
}
}
// "($name - mean) / std"
return expression;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected Object[] getEstimatorStep(){
List<Object[]> steps = getSteps();
if(steps.size() < 1){
throw new IllegalArgumentException("Missing estimator step");
}
return steps.get(steps.size() - 1);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
protected Object[] getEstimatorStep(){
List<Object[]> steps = getSteps();
if(steps == null || steps.size() < 1){
throw new IllegalArgumentException("Missing estimator step");
}
return steps.get(steps.size() - 1);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public List<Object[]> getTransformerSteps(){
List<Object[]> steps = getSteps();
if(steps.size() < 1){
throw new IllegalArgumentException("Missing estimator step");
}
return steps.subList(0, steps.size() - 1);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public List<Object[]> getTransformerSteps(){
List<Object[]> steps = getSteps();
if(steps == null || steps.size() < 1){
throw new IllegalArgumentException("Missing estimator step");
}
return steps.subList(0, steps.size() - 1);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object getFill(){
return asJavaObject(get("fill_"));
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Object getFill(){
return getScalar("fill_");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public PMML encodePMML(){
List<DataField> dataFields = new ArrayList<>();
DataField targetDataField = encodeTarget();
dataFields.add(targetDataField);
Integer features = getFeatures();
for(int i = 0; i < features.intValue(); i++){
DataField dataField = new DataField(FieldName.create("x" + String.valueOf(i + 1)), OpType.CONTINUOUS, DataType.DOUBLE);
dataFields.add(dataField);
}
DataDictionary dataDictionary = new DataDictionary(dataFields);
PMML pmml = new PMML("4.2", PMMLUtil.createHeader("JPMML-SkLearn"), dataDictionary);
Model model = encodeModel(dataFields);
pmml.addModels(model);
return pmml;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public PMML encodePMML(){
List<DataField> dataFields = new ArrayList<>();
dataFields.add(encodeTargetField());
int features = getNumberOfFeatures();
for(int i = 0; i < features; i++){
dataFields.add(encodeActiveField(i));
}
DataDictionary dataDictionary = new DataDictionary(dataFields);
PMML pmml = new PMML("4.2", PMMLUtil.createHeader("JPMML-SkLearn"), dataDictionary);
Model model = encodeModel(dataFields);
pmml.addModels(model);
return pmml;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getNumberOfFeatures(){
return (Integer)get("rank_");
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getNumberOfFeatures(){
int[] shape = getCoefShape();
if(shape.length != 1){
throw new IllegalArgumentException();
}
return shape[0];
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public int[] getShape(NDArray array){
Object[] shape = array.getShape();
int[] result = new int[shape.length];
for(int i = 0; i < shape.length; i++){
result[i] = ValueUtil.asInteger((Number)shape[i]);
}
return result;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public int[] getShape(NDArray array){
Object[] shape = array.getShape();
List<? extends Number> values = (List)Arrays.asList(shape);
return Ints.toArray(ValueUtil.asIntegers(values));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void encodeFeatures(SkLearnEncoder encoder){
List<Object[]> steps = getFeatures();
for(int row = 0; row < steps.size(); row++){
Object[] step = steps.get(row);
List<String> ids = new ArrayList<>();
List<Feature> features = new ArrayList<>();
List<String> names = getNameList(step);
for(String name : names){
ids.add(name);
DataField dataField = encoder.createDataField(FieldName.create(name));
Feature feature = new WildcardFeature(encoder, dataField);
features.add(feature);
}
List<Transformer> transformers = getTransformerList(step);
for(int column = 0; column < transformers.size(); column++){
Transformer transformer = transformers.get(column);
for(Feature feature : features){
encoder.updateType(feature.getName(), transformer.getOpType(), transformer.getDataType());
}
features = transformer.encodeFeatures(ids, features, encoder);
}
encoder.addRow(ids, features);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void encodeFeatures(SkLearnEncoder encoder){
Object _default = getDefault();
List<Object[]> rows = getFeatures();
if(!(Boolean.FALSE).equals(_default)){
throw new IllegalArgumentException();
}
for(Object[] row : rows){
List<String> ids = new ArrayList<>();
List<Feature> features = new ArrayList<>();
List<String> columns = getColumnList(row);
for(String column : columns){
FieldName name = FieldName.create(column);
ids.add(name.getValue());
DataField dataField = encoder.getDataField(name);
if(dataField == null){
dataField = encoder.createDataField(name);
}
Feature feature = new WildcardFeature(encoder, dataField);
features.add(feature);
}
List<Transformer> transformers = getTransformerList(row);
for(Transformer transformer : transformers){
for(Feature feature : features){
encoder.updateType(feature.getName(), transformer.getOpType(), transformer.getDataType());
}
features = transformer.encodeFeatures(ids, features, encoder);
}
encoder.addRow(ids, features);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Expression encode(int index, FieldName name){
List<?> classes = getClasses();
Object value = classes.get(index);
Number posLabel = getPosLabel();
Number negLabel = getNegLabel();
if(Double.compare(posLabel.doubleValue(), 1d) == 0 && Double.compare(negLabel.doubleValue(), 0d) == 0){
NormDiscrete normDiscrete = new NormDiscrete(name, String.valueOf(value));
return normDiscrete;
}
// "($name == value) ? pos_label : neg_label"
return PMMLUtil.createApply("if", PMMLUtil.createApply("equal", new FieldRef(name), PMMLUtil.createConstant(value)), PMMLUtil.createConstant(posLabel), PMMLUtil.createConstant(negLabel));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public Expression encode(int index, FieldName name){
List<?> classes = getClasses();
Object value = classes.get(index);
Number posLabel = getPosLabel();
Number negLabel = getNegLabel();
if(ValueUtil.isOne(posLabel) && ValueUtil.isZero(negLabel)){
NormDiscrete normDiscrete = new NormDiscrete(name, String.valueOf(value));
return normDiscrete;
}
// "($name == value) ? pos_label : neg_label"
return PMMLUtil.createApply("if", PMMLUtil.createApply("equal", new FieldRef(name), PMMLUtil.createConstant(value)), PMMLUtil.createConstant(posLabel), PMMLUtil.createConstant(negLabel));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object getMissingValues(){
return asJavaObject(get("missing_values"));
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Object getMissingValues(){
return getScalar("missing_values");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
Expression encodeUFunc(UFunc ufunc, FieldRef fieldRef){
String module = ufunc.getModule();
String name = ufunc.getName();
switch(module){
case "numpy":
case "numpy.core.numeric":
case "numpy.lib.function_base":
break;
default:
throw new IllegalArgumentException(module);
}
switch(name){
case "absolute":
return PMMLUtil.createApply("abs", fieldRef);
case "ceil":
case "exp":
case "floor":
return PMMLUtil.createApply(name, fieldRef);
case "log":
return PMMLUtil.createApply("ln", fieldRef);
case "log10":
return PMMLUtil.createApply(name, fieldRef);
case "negative":
return PMMLUtil.createApply("*", PMMLUtil.createConstant(-1), fieldRef);
case "reciprocal":
return PMMLUtil.createApply("/", PMMLUtil.createConstant(1), fieldRef);
case "rint":
return PMMLUtil.createApply("round", fieldRef);
case "sign":
return PMMLUtil.createApply("if", PMMLUtil.createApply("lessThan", fieldRef, PMMLUtil.createConstant(0)),
PMMLUtil.createConstant(-1), // x < 0
PMMLUtil.createApply("if", PMMLUtil.createApply("greaterThan", fieldRef, PMMLUtil.createConstant(0)),
PMMLUtil.createConstant(+1), // x > 0
PMMLUtil.createConstant(0) // x == 0
)
);
case "sqrt":
return PMMLUtil.createApply(name, fieldRef);
case "square":
return PMMLUtil.createApply("*", fieldRef, fieldRef);
default:
throw new IllegalArgumentException(name);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
Expression encodeUFunc(UFunc ufunc, FieldRef fieldRef){
String name = ufunc.getName();
switch(name){
case "absolute":
return PMMLUtil.createApply("abs", fieldRef);
case "ceil":
case "exp":
case "floor":
return PMMLUtil.createApply(name, fieldRef);
case "log":
return PMMLUtil.createApply("ln", fieldRef);
case "log10":
return PMMLUtil.createApply(name, fieldRef);
case "negative":
return PMMLUtil.createApply("*", PMMLUtil.createConstant(-1), fieldRef);
case "reciprocal":
return PMMLUtil.createApply("/", PMMLUtil.createConstant(1), fieldRef);
case "rint":
return PMMLUtil.createApply("round", fieldRef);
case "sign":
return PMMLUtil.createApply("if", PMMLUtil.createApply("lessThan", fieldRef, PMMLUtil.createConstant(0)),
PMMLUtil.createConstant(-1), // x < 0
PMMLUtil.createApply("if", PMMLUtil.createApply("greaterThan", fieldRef, PMMLUtil.createConstant(0)),
PMMLUtil.createConstant(+1), // x > 0
PMMLUtil.createConstant(0) // x == 0
)
);
case "sqrt":
return PMMLUtil.createApply(name, fieldRef);
case "square":
return PMMLUtil.createApply("*", fieldRef, fieldRef);
default:
throw new IllegalArgumentException(name);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
private InputStream init(PushbackInputStream is) throws IOException {
byte[] headerBytes = new byte[2 + 19];
ByteStreams.readFully(is, headerBytes);
String header = new String(headerBytes);
if(!header.startsWith("ZF0x")){
throw new IOException();
}
// Remove trailing whitespace
header = header.trim();
final
long expectedSize = Long.parseLong(header.substring(4), 16);
// Consume the first byte
int firstByte = is.read();
if(firstByte < 0){
return is;
} // End if
// If the first byte is not a space character, then make it available for reading again
if(firstByte != '\u0020'){
is.unread(firstByte);
}
InflaterInputStream zlibIs = new InflaterInputStream(is);
InputStream result = new FilterInputStream(new CountingInputStream(zlibIs)){
private boolean closed = false;
@Override
public void close() throws IOException {
if(this.closed){
return;
}
this.closed = true;
long size = ((CountingInputStream)super.in).getCount();
super.close();
if(size != expectedSize){
throw new IOException("Expected " + expectedSize + " bytes of uncompressed data, got " + size + " bytes");
}
}
};
return result;
}
#location 32
#vulnerability type RESOURCE_LEAK
|
#fixed code
static
private InputStream init(PushbackInputStream is) throws IOException {
byte[] magic = new byte[2];
ByteStreams.readFully(is, magic);
is.unread(magic);
// Joblib 0.10.0 and newer
if(magic[0] == 'x'){
return initZlib(is);
} else
// Joblib 0.9.4 and earlier
if(magic[0] == 'Z' && magic[1] == 'F'){
return initCompat(is);
} else
{
throw new IOException();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getNumberOfFeatures(){
return (Integer)get("n_features");
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getNumberOfFeatures(){
return ValueUtil.asInteger((Number)get("n_features"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private Object loadContent(){
Object[] shape = getShape();
Object descr = getDescr();
byte[] data = (byte[])getData();
try {
InputStream is = new ByteArrayInputStream(data);
try {
return NDArrayUtil.parseData(is, descr, shape);
} finally {
is.close();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private Object loadContent(){
Object[] shape = getShape();
Object descr = getDescr();
byte[] data = (byte[])getData();
if(descr instanceof DType){
DType dType = (DType)descr;
descr = dType.toDescr();
}
try {
InputStream is = new ByteArrayInputStream(data);
try {
return NDArrayUtil.parseData(is, descr, shape);
} finally {
is.close();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
List<?> data = getData();
if(ids.size() != 1 || features.size() != 1){
throw new IllegalArgumentException();
}
final
InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValueTreatment(getInvalidValueTreatment());
WildcardFeature wildcardFeature = (WildcardFeature)features.get(0);
Function<Object, String> function = new Function<Object, String>(){
@Override
public String apply(Object object){
return ValueUtil.formatValue(object);
}
};
List<String> categories = Lists.transform(data, function);
FieldDecorator decorator = new ValidValueDecorator(){
{
setInvalidValueTreatment(invalidValueTreatment);
}
};
CategoricalFeature categoricalFeature = wildcardFeature.toCategoricalFeature(categories);
encoder.addDecorator(categoricalFeature.getName(), decorator);
return Collections.<Feature>singletonList(categoricalFeature);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
List<?> data = getData();
ClassDictUtil.checkSize(1, ids, features);
final
InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValueTreatment(getInvalidValueTreatment());
WildcardFeature wildcardFeature = (WildcardFeature)features.get(0);
Function<Object, String> function = new Function<Object, String>(){
@Override
public String apply(Object object){
return ValueUtil.formatValue(object);
}
};
List<String> categories = Lists.transform(data, function);
FieldDecorator decorator = new ValidValueDecorator(){
{
setInvalidValueTreatment(invalidValueTreatment);
}
};
CategoricalFeature categoricalFeature = wildcardFeature.toCategoricalFeature(categories);
encoder.addDecorator(categoricalFeature.getName(), decorator);
return Collections.<Feature>singletonList(categoricalFeature);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Number getWeight(int index){
CSRMatrix idfDiag = (CSRMatrix)get("_idf_diag");
List<?> data = idfDiag.getData();
return (Number)data.get(index);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Number getWeight(int index){
CSRMatrix idfDiag = get("_idf_diag", CSRMatrix.class);
List<?> data = idfDiag.getData();
return (Number)data.get(index);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getNumberOfFeatures(){
List<?> coefs = getCoefs();
NDArray input = (NDArray)coefs.get(0);
int[] shape = NDArrayUtil.getShape(input);
return shape[0];
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getNumberOfFeatures(){
List<? extends HasArray> coefs = getCoefs();
return NeuralNetworkUtil.getNumberOfFeatures(coefs);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Expression encode(int index, FieldName name){
List<?> classes = getClasses();
Object value = classes.get(index);
Number posLabel = getPosLabel();
Number negLabel = getNegLabel();
if(Double.compare(posLabel.doubleValue(), 1d) == 0 && Double.compare(negLabel.doubleValue(), 0d) == 0){
NormDiscrete normDiscrete = new NormDiscrete(name, String.valueOf(value));
return normDiscrete;
}
// "($name == value) ? pos_label : neg_label"
return PMMLUtil.createApply("if", PMMLUtil.createApply("equal", new FieldRef(name), PMMLUtil.createConstant(value)), PMMLUtil.createConstant(posLabel), PMMLUtil.createConstant(negLabel));
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public Expression encode(int index, FieldName name){
List<?> classes = getClasses();
Object value = classes.get(index);
Number posLabel = getPosLabel();
Number negLabel = getNegLabel();
if(ValueUtil.isOne(posLabel) && ValueUtil.isZero(negLabel)){
NormDiscrete normDiscrete = new NormDiscrete(name, String.valueOf(value));
return normDiscrete;
}
// "($name == value) ? pos_label : neg_label"
return PMMLUtil.createApply("if", PMMLUtil.createApply("equal", new FieldRef(name), PMMLUtil.createConstant(value)), PMMLUtil.createConstant(posLabel), PMMLUtil.createConstant(negLabel));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public DefineFunction encodeDefineFunction(){
String analyzer = getAnalyzer();
Boolean binary = getBinary();
String stripAccents = getStripAccents();
String tokenPattern = getTokenPattern();
switch(analyzer){
case "word":
break;
default:
throw new IllegalArgumentException(analyzer);
}
if(stripAccents != null){
throw new IllegalArgumentException(stripAccents);
} // End if
if(tokenPattern != null && !("(?u)\\b\\w\\w+\\b").equals(tokenPattern)){
throw new IllegalArgumentException(tokenPattern);
}
ParameterField documentField = new ParameterField(FieldName.create("document"));
ParameterField termField = new ParameterField(FieldName.create("term"));
TextIndex textIndex = new TextIndex(documentField.getName())
.setTokenize(Boolean.TRUE)
.setLocalTermWeights(binary ? TextIndex.LocalTermWeights.BINARY : null)
.setExpression(new FieldRef(termField.getName()));
DefineFunction defineFunction = new DefineFunction("tf", OpType.CONTINUOUS, null)
.setDataType(DataType.DOUBLE)
.addParameterFields(documentField, termField)
.setExpression(textIndex);
return defineFunction;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public DefineFunction encodeDefineFunction(){
String analyzer = getAnalyzer();
Boolean binary = getBinary();
Object preprocessor = getPreprocessor();
String stripAccents = getStripAccents();
Splitter tokenizer = getTokenizer();
switch(analyzer){
case "word":
break;
default:
throw new IllegalArgumentException(analyzer);
}
if(preprocessor != null){
throw new IllegalArgumentException();
} // End if
if(stripAccents != null){
throw new IllegalArgumentException(stripAccents);
}
ParameterField documentField = new ParameterField(FieldName.create("text"));
ParameterField termField = new ParameterField(FieldName.create("term"));
TextIndex textIndex = new TextIndex(documentField.getName())
.setTokenize(Boolean.TRUE)
.setWordSeparatorCharacterRE(tokenizer.getSeparatorRE())
.setLocalTermWeights(binary ? TextIndex.LocalTermWeights.BINARY : null)
.setExpression(new FieldRef(termField.getName()));
DefineFunction defineFunction = new DefineFunction("tf", OpType.CONTINUOUS, null)
.setDataType(DataType.DOUBLE)
.addParameterFields(documentField, termField)
.setExpression(textIndex);
return defineFunction;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public ContinuousOutputFeature toContinuousFeature(){
PMMLEncoder encoder = ensureEncoder();
Output output = getOutput();
OutputField outputField = OutputUtil.getOutputField(output, getName());
DataType dataType = outputField.getDataType();
switch(dataType){
case INTEGER:
case FLOAT:
case DOUBLE:
break;
default:
throw new IllegalArgumentException();
}
outputField.setOpType(OpType.CONTINUOUS);
return new ContinuousOutputFeature(encoder, output, outputField);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public ContinuousOutputFeature toContinuousFeature(){
PMMLEncoder encoder = ensureEncoder();
Output output = getOutput();
OutputField outputField = getField();
DataType dataType = outputField.getDataType();
switch(dataType){
case INTEGER:
case FLOAT:
case DOUBLE:
break;
default:
throw new IllegalArgumentException();
}
outputField.setOpType(OpType.CONTINUOUS);
return new ContinuousOutputFeature(encoder, output, outputField);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getNumberOfFeatures(){
return (Integer)get("n_features");
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getNumberOfFeatures(){
return ValueUtil.asInteger((Number)get("n_features"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private List<?> loadContent(){
DType dtype = getDType();
byte[] obj = getObj();
try {
InputStream is = new ByteArrayInputStream(obj);
try {
return (List<?>)NDArrayUtil.parseData(is, dtype.toDescr(), new Object[0]);
} finally {
is.close();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private List<?> loadContent(){
DType dtype = getDType();
byte[] obj = getObj();
try {
InputStream is = new ByteArrayInputStream(obj);
try {
return (List<?>)NDArrayUtil.parseData(is, dtype, new Object[0]);
} finally {
is.close();
}
} catch(IOException ioe){
throw new RuntimeException(ioe);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
List<? extends Number> dataMin = getDataMin();
List<? extends Number> dataMax = getDataMax();
ClassDictUtil.checkSize(ids, features, dataMin, dataMax);
InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValueTreatment(getInvalidValueTreatment());
InvalidValueDecorator invalidValueDecorator = new InvalidValueDecorator()
.setInvalidValueTreatment(invalidValueTreatment);
List<Feature> result = new ArrayList<>();
for(int i = 0; i < features.size(); i++){
WildcardFeature wildcardFeature = (WildcardFeature)features.get(i);
ContinuousFeature continuousFeature = wildcardFeature.toContinuousFeature();
Interval interval = new Interval(Interval.Closure.CLOSED_CLOSED)
.setLeftMargin(ValueUtil.asDouble(dataMin.get(i)))
.setRightMargin(ValueUtil.asDouble(dataMax.get(i)));
ValidValueDecorator validValueDecorator = new ValidValueDecorator()
.addIntervals(interval);
encoder.addDecorator(continuousFeature.getName(), validValueDecorator);
encoder.addDecorator(continuousFeature.getName(), invalidValueDecorator);
result.add(continuousFeature);
}
return result;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
List<? extends Number> dataMin = getDataMin();
List<? extends Number> dataMax = getDataMax();
ClassDictUtil.checkSize(ids, features, dataMin, dataMax);
List<Feature> result = new ArrayList<>();
for(int i = 0; i < features.size(); i++){
WildcardFeature wildcardFeature = (WildcardFeature)features.get(i);
ContinuousFeature continuousFeature = wildcardFeature.toContinuousFeature();
Interval interval = new Interval(Interval.Closure.CLOSED_CLOSED)
.setLeftMargin(ValueUtil.asDouble(dataMin.get(i)))
.setRightMargin(ValueUtil.asDouble(dataMax.get(i)));
ValidValueDecorator validValueDecorator = new ValidValueDecorator()
.addIntervals(interval);
encoder.addDecorator(continuousFeature.getName(), validValueDecorator);
result.add(continuousFeature);
}
return super.encodeFeatures(ids, result, encoder);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
int[] shape = getComponentsShape();
int numberOfComponents = shape[0];
int numberOfFeatures = shape[1];
if(ids.size() != numberOfFeatures || features.size() != numberOfFeatures){
throw new IllegalArgumentException();
}
String id = String.valueOf(PCA.SEQUENCE.getAndIncrement());
List<? extends Number> components = getComponents();
List<? extends Number> mean = getMean();
Boolean whiten = getWhiten();
List<? extends Number> explainedVariance = (whiten ? getExplainedVariance() : null);
ids.clear();
List<Feature> result = new ArrayList<>();
for(int i = 0; i < numberOfComponents; i++){
List<? extends Number> component = MatrixUtil.getRow(components, numberOfComponents, numberOfFeatures, i);
Apply apply = new Apply("sum");
for(int j = 0; j < numberOfFeatures; j++){
Feature feature = features.get(j);
// "($name[i] - mean[i]) * component[i]"
Expression expression = (feature.toContinuousFeature()).ref();
Number meanValue = mean.get(j);
if(!ValueUtil.isZero(meanValue)){
expression = PMMLUtil.createApply("-", expression, PMMLUtil.createConstant(meanValue));
}
Number componentValue = component.get(j);
if(!ValueUtil.isOne(componentValue)){
expression = PMMLUtil.createApply("*", expression, PMMLUtil.createConstant(componentValue));
}
apply.addExpressions(expression);
}
if(whiten){
Number explainedVarianceValue = explainedVariance.get(i);
if(!ValueUtil.isOne(explainedVarianceValue)){
apply = PMMLUtil.createApply("/", apply, PMMLUtil.createConstant(Math.sqrt(ValueUtil.asDouble(explainedVarianceValue))));
}
}
DerivedField derivedField = encoder.createDerivedField(createName(id, i), apply);
ids.add((derivedField.getName()).getValue());
result.add(new ContinuousFeature(encoder, derivedField));
}
return result;
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){
int[] shape = getComponentsShape();
int numberOfComponents = shape[0];
int numberOfFeatures = shape[1];
List<? extends Number> components = getComponents();
List<? extends Number> mean = getMean();
ClassDictUtil.checkSize(numberOfFeatures, ids, features, mean);
Boolean whiten = getWhiten();
List<? extends Number> explainedVariance = (whiten ? getExplainedVariance() : null);
ClassDictUtil.checkSize(numberOfComponents, explainedVariance);
String id = String.valueOf(PCA.SEQUENCE.getAndIncrement());
ids.clear();
List<Feature> result = new ArrayList<>();
for(int i = 0; i < numberOfComponents; i++){
List<? extends Number> component = MatrixUtil.getRow(components, numberOfComponents, numberOfFeatures, i);
Apply apply = new Apply("sum");
for(int j = 0; j < numberOfFeatures; j++){
Feature feature = features.get(j);
// "($name[i] - mean[i]) * component[i]"
Expression expression = (feature.toContinuousFeature()).ref();
Number meanValue = mean.get(j);
if(!ValueUtil.isZero(meanValue)){
expression = PMMLUtil.createApply("-", expression, PMMLUtil.createConstant(meanValue));
}
Number componentValue = component.get(j);
if(!ValueUtil.isOne(componentValue)){
expression = PMMLUtil.createApply("*", expression, PMMLUtil.createConstant(componentValue));
}
apply.addExpressions(expression);
}
if(whiten){
Number explainedVarianceValue = explainedVariance.get(i);
if(!ValueUtil.isOne(explainedVarianceValue)){
apply = PMMLUtil.createApply("/", apply, PMMLUtil.createConstant(Math.sqrt(ValueUtil.asDouble(explainedVarianceValue))));
}
}
DerivedField derivedField = encoder.createDerivedField(createName(id, i), apply);
ids.add((derivedField.getName()).getValue());
result.add(new ContinuousFeature(encoder, derivedField));
}
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){
String function = translateFunction(getFunction());
if(features.size() <= 1){
return features;
}
FieldName name = FieldName.create(function + "(" + FeatureUtil.formatFeatureList(features) + ")");
Apply apply = new Apply(function);
for(Feature feature : features){
apply.addExpressions(feature.ref());
}
DerivedField derivedField = encoder.createDerivedField(name, OpType.CONTINUOUS, DataType.DOUBLE, apply);
return Collections.<Feature>singletonList(new ContinuousFeature(encoder, derivedField));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){
String function = getFunction();
if(features.size() <= 1){
return features;
}
Apply apply = new Apply(translateFunction(function));
for(Feature feature : features){
apply.addExpressions(feature.ref());
}
FieldName name = FieldName.create(function + "(" + FeatureUtil.formatFeatureList(features) + ")"); // XXX
DerivedField derivedField = encoder.createDerivedField(name, OpType.CONTINUOUS, DataType.DOUBLE, apply);
return Collections.<Feature>singletonList(new ContinuousFeature(encoder, derivedField));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private int[] getCoefShape(){
NDArrayWrapper arrayWrapper = (NDArrayWrapper)get("coef_");
NDArray array = arrayWrapper.getContent();
return NDArrayUtil.getShape(array);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private int[] getCoefShape(){
return ClassDictUtil.getShape(this, "coef_");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public List<?> getArray(ClassDict dict, String name, String key){
Object object = unwrap(dict.get(name));
if(object instanceof NDArray){
NDArray array = (NDArray)object;
return NDArrayUtil.getContent(array, key);
}
throw new IllegalArgumentException("The value of the " + ClassDictUtil.formatMember(dict, name) + " attribute (" + ClassDictUtil.formatClass(object) + ") is not a supported array type");
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public List<?> getArray(ClassDict dict, String name, String key){
Object object = dict.get(name);
if(object instanceof NDArrayWrapper){
NDArrayWrapper arrayWrapper = (NDArrayWrapper)object;
object = arrayWrapper.getContent();
} // End if
if(object instanceof NDArray){
NDArray array = (NDArray)object;
return NDArrayUtil.getContent(array, key);
}
throw new IllegalArgumentException("The value of the " + ClassDictUtil.formatMember(dict, name) + " attribute (" + ClassDictUtil.formatClass(object) + ") is not a supported array type");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int getNumberOfFeatures(){
return (Integer)get("n_features_");
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public int getNumberOfFeatures(){
return ValueUtil.asInteger((Number)get("n_features_"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public List<?> getContent(NDArray array, String key){
Map<String, ?> data = (Map<String, ?>)array.getContent();
return asJavaList(array, (List<?>)data.get(key));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public List<?> getContent(NDArray array, String key){
Map<String, ?> content = (Map<String, ?>)array.getContent();
return asJavaList(array, (List<?>)content.get(key));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public List<Transformer> getTransformers(){
List<Object[]> steps = getSteps();
boolean flexible = isFlexible();
if(flexible && steps.size() > 0){
Estimator estimator = getEstimator();
if(estimator != null){
steps = steps.subList(0, steps.size() - 1);
}
}
return TransformerUtil.asTransformerList(TupleUtil.extractElementList(steps, 1));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public List<Transformer> getTransformers(){
List<Object[]> steps = getSteps();
return TransformerUtil.asTransformerList(TupleUtil.extractElementList(steps, 1));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<Feature> initializeFeatures(SkLearnEncoder encoder){
List<String> featureNames = getFeatureNames();
String separator = getSeparator();
Map<String, Integer> vocabulary = getVocabulary();
Feature[] featureArray = new Feature[featureNames.size()];
for(String featureName : featureNames){
String key = featureName;
String value = null;
int index = featureName.indexOf(separator);
if(index > -1){
key = featureName.substring(0, index);
value = featureName.substring(index + separator.length());
}
FieldName name = FieldName.create(key);
DataField dataField = encoder.getDataField(name);
if(dataField == null){
if(value != null){
dataField = encoder.createDataField(name, OpType.CATEGORICAL, DataType.STRING);
} else
{
dataField = encoder.createDataField(name, OpType.CONTINUOUS, DataType.DOUBLE);
}
}
Feature feature;
if(value != null){
PMMLUtil.addValues(dataField, Collections.singletonList(value));
feature = new BinaryFeature(encoder, dataField, value);
} else
{
feature = new ContinuousFeature(encoder, dataField);
}
featureArray[vocabulary.get(featureName)] = feature;
}
List<Feature> result = new ArrayList<>();
result.addAll(Arrays.asList(featureArray));
return result;
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<Feature> initializeFeatures(SkLearnEncoder encoder){
List<? extends String> featureNames = getFeatureNames();
String separator = getSeparator();
Map<String, Integer> vocabulary = getVocabulary();
Feature[] featureArray = new Feature[featureNames.size()];
for(String featureName : featureNames){
String key = featureName;
String value = null;
int index = featureName.indexOf(separator);
if(index > -1){
key = featureName.substring(0, index);
value = featureName.substring(index + separator.length());
}
FieldName name = FieldName.create(key);
DataField dataField = encoder.getDataField(name);
if(dataField == null){
if(value != null){
dataField = encoder.createDataField(name, OpType.CATEGORICAL, DataType.STRING);
} else
{
dataField = encoder.createDataField(name, OpType.CONTINUOUS, DataType.DOUBLE);
}
}
Feature feature;
if(value != null){
PMMLUtil.addValues(dataField, Collections.singletonList(value));
feature = new BinaryFeature(encoder, dataField, value);
} else
{
feature = new ContinuousFeature(encoder, dataField);
}
featureArray[vocabulary.get(featureName)] = feature;
}
List<Feature> result = new ArrayList<>();
result.addAll(Arrays.asList(featureArray));
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public List<?> getArray(ClassDict dict, String name){
Object object = unwrap(dict.get(name));
if(object instanceof NDArray){
NDArray array = (NDArray)object;
return NDArrayUtil.getContent(array);
} else
if(object instanceof CSRMatrix){
CSRMatrix matrix = (CSRMatrix)object;
return CSRMatrixUtil.getContent(matrix);
} else
if(object instanceof Scalar){
Scalar scalar = (Scalar)object;
return scalar.getContent();
} // End if
if(object instanceof Number){
return Collections.singletonList(object);
}
throw new IllegalArgumentException("The value of the " + ClassDictUtil.formatMember(dict, name) + " attribute (" + ClassDictUtil.formatClass(object) + ") is not a supported array type");
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public List<?> getArray(ClassDict dict, String name){
Object object = dict.get(name);
if(object instanceof HasArray){
HasArray hasArray = (HasArray)object;
return hasArray.getArrayContent();
} // End if
if(object instanceof Number){
return Collections.singletonList(object);
}
throw new IllegalArgumentException("The value of the " + ClassDictUtil.formatMember(dict, name) + " attribute (" + ClassDictUtil.formatClass(object) + ") is not a supported array type");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<?> getClasses(){
List<Object> result = new ArrayList<>();
List<?> values = (List<?>)get("classes_");
for(Object value : values){
if(value instanceof HasArray){
HasArray hasArray = (HasArray)value;
result.addAll(hasArray.getArrayContent());
} else
{
result.add(value);
}
}
return result;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<?> getClasses(){
LabelEncoder labelEncoder = getLabelEncoder();
return labelEncoder.getClasses();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public double[] getValues(){
NDArrayWrapper values = (NDArrayWrapper)get("values");
return Doubles.toArray((List<? extends Number>)values.getContent());
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public double[] getValues(){
List<? extends Number> values = (List<? extends Number>)ClassDictUtil.getArray(this, "values");
return Doubles.toArray(values);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static
public MiningModel encodeBooster(HasBooster hasBooster, Schema schema){
Booster booster = hasBooster.getBooster();
Learner learner = booster.getLearner();
Schema xgbSchema = XGBoostUtil.toXGBoostSchema(schema);
MiningModel miningModel = learner.encodeMiningModel(xgbSchema);
return miningModel;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static
public MiningModel encodeBooster(HasBooster hasBooster, Schema schema){
Booster booster = hasBooster.getBooster();
Learner learner = booster.getLearner();
Schema xgbSchema = XGBoostUtil.toXGBoostSchema(schema);
// XXX
List<Feature> features = xgbSchema.getFeatures();
for(Feature feature : features){
if(feature instanceof ContinuousFeature){
SkLearnEncoder encoder = (SkLearnEncoder)feature.getEncoder();
TypeDefinitionField field = encoder.getField(feature.getName());
if(!(OpType.CONTINUOUS).equals(field.getOpType())){
field.setOpType(OpType.CONTINUOUS);
}
}
}
MiningModel miningModel = learner.encodeMiningModel(xgbSchema);
return miningModel;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){
Object func = getFunc();
UFunc ufunc;
try {
ufunc = (UFunc)func;
} catch(ClassCastException cce){
throw new IllegalArgumentException("The function object (" + ClassDictUtil.formatClass(func) + ") is not a Numpy universal function", cce);
}
List<Feature> result = new ArrayList<>();
for(int i = 0; i < features.size(); i++){
ContinuousFeature continuousFeature = (features.get(i)).toContinuousFeature();
FieldName name = FeatureUtil.createName(ufunc.getName(), continuousFeature);
DerivedField derivedField = encoder.getDerivedField(name);
if(derivedField == null){
Expression expression = encodeUFunc(ufunc, continuousFeature.ref());
derivedField = encoder.createDerivedField(name, expression);
}
result.add(new ContinuousFeature(encoder, derivedField));
}
return result;
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){
Object func = getFunc();
if(func == null){
return features;
}
UFunc ufunc;
try {
ufunc = (UFunc)func;
} catch(ClassCastException cce){
throw new IllegalArgumentException("The function object (" + ClassDictUtil.formatClass(func) + ") is not a Numpy universal function", cce);
}
List<Feature> result = new ArrayList<>();
for(int i = 0; i < features.size(); i++){
ContinuousFeature continuousFeature = (features.get(i)).toContinuousFeature();
FieldName name = FeatureUtil.createName(ufunc.getName(), continuousFeature);
DerivedField derivedField = encoder.getDerivedField(name);
if(derivedField == null){
Expression expression = encodeUFunc(ufunc, continuousFeature.ref());
derivedField = encoder.createDerivedField(name, expression);
}
result.add(new ContinuousFeature(encoder, derivedField));
}
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void test_dispatcher_local_greeting_request_completes_before_timeout() {
Microservices gateway = Microservices.builder()
.services(new GreetingServiceImpl())
.build();
Call service = gateway.call();
Publisher<ServiceMessage> result = service.requestOne(GREETING_REQUEST_REQ, GreetingResponse.class);
GreetingResponse greetings = Mono.from(result).timeout(Duration.ofSeconds(TIMEOUT)).block().data();
System.out.println("1. greeting_request_completes_before_timeout : " + greetings.getResult());
assertTrue(greetings.getResult().equals(" hello to: joe"));
gateway.shutdown().block();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void test_dispatcher_local_greeting_request_completes_before_timeout() {
Microservices gateway = Microservices.builder()
.discoveryPort(port.incrementAndGet())
.services(new GreetingServiceImpl())
.build();
Call service = gateway.call();
Publisher<ServiceMessage> result = service.requestOne(GREETING_REQUEST_REQ, GreetingResponse.class);
GreetingResponse greetings = Mono.from(result).timeout(Duration.ofSeconds(TIMEOUT)).block().data();
System.out.println("1. greeting_request_completes_before_timeout : " + greetings.getResult());
assertTrue(greetings.getResult().equals(" hello to: joe"));
gateway.shutdown().block();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public ServiceMessage decodeMessage(Payload payload) {
Builder builder = ServiceMessage.builder();
if (payload.getData().hasRemaining()) {
try {
builder.data(payload.sliceData());
} catch (Throwable ex) {
LOGGER.error("Failed to deserialize data", ex);
}
}
if (payload.hasMetadata()) {
ByteBuf headers = payload.sliceMetadata();
ByteBufInputStream inputStream = new ByteBufInputStream(headers);
try {
builder.headers((Map<String, String>) (readFrom(inputStream, mapType)));
} catch (Throwable ex) {
LOGGER.error("Failed to deserialize data", ex);
}
}
return builder.build();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public ServiceMessage decodeMessage(Payload payload) {
Builder builder = ServiceMessage.builder();
if (payload.getData().hasRemaining()) {
try {
builder.data(payload.sliceData());
} catch (Throwable ex) {
LOGGER.error("Failed to deserialize data", ex);
}
}
if (payload.hasMetadata()) {
try (ByteBufInputStream inputStream = new ByteBufInputStream(payload.sliceMetadata(), true)) {
builder.headers(readFrom(inputStream, mapType));
} catch (Throwable ex) {
LOGGER.error("Failed to deserialize data", ex);
}
}
payload.release();
return builder.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void test_local_quotes_service() throws InterruptedException {
Microservices node = Microservices.builder().services(new SimpleQuoteService()).build();
QuoteService service = node.call().api(QuoteService.class);
CountDownLatch latch = new CountDownLatch(3);
Flux<String> obs = service.quotes();
Disposable sub = obs.subscribe(onNext -> latch.countDown());
latch.await(4, TimeUnit.SECONDS);
sub.dispose();
assertTrue(latch.getCount() <= 0);
node.shutdown();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void test_local_quotes_service() throws InterruptedException {
Microservices node = Microservices.builder()
.discoveryPort(port.incrementAndGet())
.services(new SimpleQuoteService()).build();
QuoteService service = node.call().api(QuoteService.class);
CountDownLatch latch = new CountDownLatch(3);
Flux<String> obs = service.quotes();
Disposable sub = obs.subscribe(onNext -> latch.countDown());
latch.await(4, TimeUnit.SECONDS);
sub.dispose();
assertTrue(latch.getCount() <= 0);
node.shutdown();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public ServiceMessage decodeData(ServiceMessage message, Class type) {
if (message.data() != null && message.data() instanceof ByteBuf) {
ByteBufInputStream inputStream = new ByteBufInputStream(message.data());
try {
return ServiceMessage.from(message).data(readFrom(inputStream, type)).build();
} catch (Throwable ex) {
LOGGER.error("Failed to deserialize data", ex);
}
}
return message;
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public ServiceMessage decodeData(ServiceMessage message, Class type) {
if (message.data() != null && message.data() instanceof ByteBuf) {
try (ByteBufInputStream inputStream = new ByteBufInputStream(message.data(), true)) {
return ServiceMessage.from(message).data(readFrom(inputStream, type)).build();
} catch (Throwable ex) {
LOGGER.error("Failed to deserialize data", ex);
}
}
return message;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void importNodeIndexes(File file, String indexName, String indexType) throws IOException {
BatchInserterIndex index;
if (indexType.equals("fulltext")) {
index = lucene.nodeIndex( indexName, stringMap( "type", "fulltext" ) );
} else {
index = lucene.nodeIndex( indexName, EXACT_CONFIG );
}
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 1);
Object[] node = new Object[1];
String line;
report.reset();
while ((line = bf.readLine()) != null) {
final Map<String, Object> properties = map(data.update(line, node));
index.add(id(node[0]), properties);
report.dots();
}
report.finishImport("Nodes into " + indexName + " Index");
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void importNodeIndexes(File file, String indexName, String indexType) throws IOException {
BatchInserterIndex index;
if (indexType.equals("fulltext")) {
index = lucene.nodeIndex( indexName, FULLTEXT_CONFIG );
} else {
index = lucene.nodeIndex( indexName, EXACT_CONFIG );
}
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 1);
Object[] node = new Object[1];
String line;
report.reset();
while ((line = bf.readLine()) != null) {
final Map<String, Object> properties = data.update(line, node);
index.add(id(node[0]), properties);
report.dots();
}
report.finishImport("Nodes into " + indexName + " Index");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void importNodes(File file) throws IOException {
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 0);
String line;
report.reset();
while ((line = bf.readLine()) != null) {
db.createNode(map(data.update(line)));
report.dots();
}
report.finishImport("Nodes");
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void importNodes(File file) throws IOException {
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 0);
String line;
report.reset();
while ((line = bf.readLine()) != null) {
db.createNode(data.update(line));
report.dots();
}
report.finishImport("Nodes");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void importRelationshipIndexes(File file, String indexName, String indexType) throws IOException {
BatchInserterIndex index;
if (indexType.equals("fulltext")) {
index = lucene.relationshipIndex( indexName, stringMap( "type", "fulltext" ) );
} else {
index = lucene.relationshipIndex( indexName, EXACT_CONFIG );
}
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 1);
Object[] rel = new Object[1];
String line;
report.reset();
while ((line = bf.readLine()) != null) {
final Map<String, Object> properties = map(data.update(line, rel));
index.add(id(rel[0]), properties);
report.dots();
}
report.finishImport("Relationships into " + indexName + " Index");
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void importRelationshipIndexes(File file, String indexName, String indexType) throws IOException {
BatchInserterIndex index;
if (indexType.equals("fulltext")) {
index = lucene.relationshipIndex( indexName, FULLTEXT_CONFIG );
} else {
index = lucene.relationshipIndex( indexName, EXACT_CONFIG );
}
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 1);
Object[] rel = new Object[1];
String line;
report.reset();
while ((line = bf.readLine()) != null) {
final Map<String, Object> properties = data.update(line, rel);
index.add(id(rel[0]), properties);
report.dots();
}
report.finishImport("Relationships into " + indexName + " Index");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void importRelationships(File file) throws IOException {
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 3);
Object[] rel = new Object[3];
final Type type = new Type();
String line;
report.reset();
while ((line = bf.readLine()) != null) {
final Map<String, Object> properties = map(data.update(line, rel));
db.createRelationship(id(rel[0]), id(rel[1]), type.update(rel[2]), properties);
report.dots();
}
report.finishImport("Relationships");
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void importRelationships(File file) throws IOException {
BufferedReader bf = new BufferedReader(new FileReader(file));
final Data data = new Data(bf.readLine(), "\t", 3);
Object[] rel = new Object[3];
final RelType relType = new RelType();
String line;
report.reset();
while ((line = bf.readLine()) != null) {
final Map<String, Object> properties = data.update(line, rel);
db.createRelationship(id(rel[0]), id(rel[1]), relType.update(rel[2]), properties);
report.dots();
}
report.finishImport("Relationships");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testCache() {
long start1 = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
long end1 = System.currentTimeMillis();
//关闭缓存
userDetailsService.setEnableCache(false);
long start2 = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
long end2 = System.currentTimeMillis();
System.out.printf("使用缓存:" + (end1 - start1) + "毫秒\n 不使用缓存:" + (end2 - start2) + "毫秒");
}
#location 15
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Test
public void testCache() {
long start1 = System.currentTimeMillis();
int size = 10000;
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
long end1 = System.currentTimeMillis();
//关闭缓存
userDetailsService.setEnableCache(false);
long start2 = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
long end2 = System.currentTimeMillis();
System.out.print("使用缓存:" + (end1 - start1) + "毫秒\n 不使用缓存:" + (end2 - start2) + "毫秒");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static List<String> readSqlList(File sqlFile) throws Exception {
List<String> sqlList = Lists.newArrayList();
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(sqlFile), "UTF-8"));
String tmp = null;
while ((tmp = reader.readLine()) != null) {
log.info("line:{}", tmp);
if (tmp.endsWith(";")) {
sb.append(tmp);
sqlList.add(sb.toString());
sb.delete(0, sb.length());
} else {
sb.append(tmp);
}
}
if (!"".endsWith(sb.toString().trim())) {
sqlList.add(sb.toString());
}
} finally {
try {
reader.close();
} catch (IOException e1) {
}
}
return sqlList;
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private static List<String> readSqlList(File sqlFile) throws Exception {
List<String> sqlList = Lists.newArrayList();
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(sqlFile), StandardCharsets.UTF_8))) {
String tmp;
while ((tmp = reader.readLine()) != null) {
log.info("line:{}", tmp);
if (tmp.endsWith(";")) {
sb.append(tmp);
sqlList.add(sb.toString());
sb.delete(0, sb.length());
} else {
sb.append(tmp);
}
}
if (!"".endsWith(sb.toString().trim())) {
sqlList.add(sb.toString());
}
}
return sqlList;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void test1() {
long l = System.currentTimeMillis() / 1000;
LocalDateTime localDateTime = DateUtil.fromTimeStamp(l);
System.out.printf(DateUtil.localDateTimeFormatyMdHms(localDateTime));
}
#location 5
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
@Test
public void test1() {
long l = System.currentTimeMillis() / 1000;
LocalDateTime localDateTime = DateUtil.fromTimeStamp(l);
System.out.print(DateUtil.localDateTimeFormatyMdHms(localDateTime));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
File desDir = new File(folderPath);
if (!desDir.exists()) {
desDir.mkdirs();
}
ZipFile zf = new ZipFile(zipFile);
for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
InputStream in = zf.getInputStream(entry);
String str = folderPath;
File desFile = new File(str, java.net.URLEncoder.encode(entry.getName(), "UTF-8"));
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
}
OutputStream out = new FileOutputStream(desFile);
byte[] buffer = new byte[1024 * 1024];
int realLength = in.read(buffer);
while (realLength != -1) {
out.write(buffer, 0, realLength);
realLength = in.read(buffer);
}
out.close();
in.close();
}
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
File desDir = new File(folderPath);
if (!desDir.exists()) {
if (!desDir.mkdirs()) {
System.out.println("was not successful.");
}
}
ZipFile zf = new ZipFile(zipFile);
for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = ((ZipEntry) entries.nextElement());
InputStream in = zf.getInputStream(entry);
String str = folderPath;
File desFile = new File(str, java.net.URLEncoder.encode(entry.getName(), "UTF-8"));
if (!desFile.exists()) {
File fileParentDir = desFile.getParentFile();
if (!fileParentDir.exists()) {
if (!fileParentDir.mkdirs()) {
System.out.println("was not successful.");
}
}
}
OutputStream out = new FileOutputStream(desFile);
byte[] buffer = new byte[1024 * 1024];
int realLength = in.read(buffer);
while (realLength != -1) {
out.write(buffer, 0, realLength);
realLength = in.read(buffer);
}
out.close();
in.close();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test()
public void testSizeControl() throws IOException, InterruptedException, ExecutionException {
// very slow running data generator. Don't want to run this normally. To run slow tests use
// mvn test -DrunSlowTests=true
assumeTrue(Boolean.parseBoolean(System.getProperty("runSlowTests")));
final Random gen0 = RandomUtils.getRandom();
final PrintWriter out = new PrintWriter(new FileOutputStream("scaling.tsv"));
out.printf("k\tsamples\tcompression\tsize1\tsize2\n");
List<Callable<String>> tasks = Lists.newArrayList();
for (int k = 0; k < 20; k++) {
for (final int size : new int[]{10, 100, 1000, 10000}) {
final int currentK = k;
tasks.add(new Callable<String>() {
Random gen = new Random(gen0.nextLong());
@Override
public String call() throws Exception {
System.out.printf("Starting %d,%d\n", currentK, size);
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
for (double compression : new double[]{2, 5, 10, 20, 50, 100, 200, 500, 1000}) {
AVLTreeDigest dist = new AVLTreeDigest(compression);
for (int i = 0; i < size * 1000; i++) {
dist.add(gen.nextDouble());
}
out.printf("%d\t%d\t%.0f\t%d\t%d\n", currentK, size, compression, dist.smallByteSize(), dist.byteSize());
out.flush();
}
out.close();
return s.toString();
}
});
}
}
for (Future<String> result : Executors.newFixedThreadPool(20).invokeAll(tasks)) {
out.write(result.get());
}
out.close();
}
#location 27
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test()
public void testSizeControl() throws IOException, InterruptedException, ExecutionException {
runSizeControl("scaling-avl.tsv", new AvlDigestFactory());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test()
public void testSizeControl() throws IOException, InterruptedException, ExecutionException {
// very slow running data generator. Don't want to run this normally. To run slow tests use
// mvn test -DrunSlowTests=true
assumeTrue(Boolean.parseBoolean(System.getProperty("runSlowTests")));
final Random gen0 = getRandom();
final PrintWriter out = new PrintWriter(new FileOutputStream("scaling.tsv"));
out.printf("k\tsamples\tcompression\tsize1\tsize2\n");
List<Callable<String>> tasks = Lists.newArrayList();
for (int k = 0; k < 20; k++) {
for (final int size : new int[]{10, 100, 1000, 10000}) {
final int currentK = k;
tasks.add(new Callable<String>() {
final Random gen = new Random(gen0.nextLong());
@Override
public String call() throws Exception {
System.out.printf("Starting %d,%d\n", currentK, size);
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
for (double compression : new double[]{2, 5, 10, 20, 50, 100, 200, 500, 1000}) {
TDigest dist = factory(compression).create();
for (int i = 0; i < size * 1000; i++) {
dist.add(gen.nextDouble());
}
out.printf("%d\t%d\t%.0f\t%d\t%d\n", currentK, size, compression, dist.smallByteSize(), dist.byteSize());
out.flush();
}
out.close();
return s.toString();
}
});
}
}
ExecutorService executor = Executors.newFixedThreadPool(20);
for (Future<String> result : executor.invokeAll(tasks)) {
out.write(result.get());
}
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
out.close();
}
#location 27
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test()
public void testSizeControl() throws IOException, InterruptedException, ExecutionException {
// very slow running data generator. Don't want to run this normally. To run slow tests use
// mvn test -DrunSlowTests=true
// assumeTrue(Boolean.parseBoolean(System.getProperty("runSlowTests")));
final Random gen0 = getRandom();
try (final PrintWriter out = new PrintWriter(new FileOutputStream(String.format("scaling-%s.tsv", digestName)))) {
out.printf("k\tsamples\tcompression\tsize1\tsize2\n");
List<Callable<String>> tasks = Lists.newArrayList();
for (int k = 0; k < 20; k++) {
for (final int size : new int[]{10, 100, 1000, 10000}) {
final int currentK = k;
tasks.add(new Callable<String>() {
final Random gen = new Random(gen0.nextLong());
@Override
public String call() throws Exception {
System.out.printf("Starting %d,%d\n", currentK, size);
StringWriter s = new StringWriter();
PrintWriter out = new PrintWriter(s);
for (double compression : new double[]{20, 50, 100, 200, 500, 1000}) {
TDigest dist = factory(compression).create();
for (int i = 0; i < size * 1000; i++) {
dist.add(gen.nextDouble());
}
out.printf("%d\t%d\t%.0f\t%d\t%d\n", currentK, size, compression, dist.smallByteSize(), dist.byteSize());
out.flush();
}
out.close();
return s.toString();
}
});
}
}
ExecutorService executor = Executors.newFixedThreadPool(20);
for (Future<String> result : executor.invokeAll(tasks)) {
out.write(result.get());
}
executor.shutdownNow();
assertTrue("Dangling executor thread", executor.awaitTermination(5, TimeUnit.SECONDS));
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
static void whitelistVerify(
final String remoteHost,
final WhitelistItem whitelistItem,
final Map<String, List<String>> headers,
final String postContent)
throws WhitelistException {
String whitelistHost = whitelistItem.getHost();
if (HostVerifier.whitelistContains(remoteHost, whitelistHost)) {
if (whitelistItem.isHmacEnabled()) {
final Optional<StringCredentials> hmacKeyOpt =
CredentialsHelper.findCredentials(whitelistItem.getHmacCredentialId());
if (!hmacKeyOpt.isPresent()) {
throw new WhitelistException(
"Was unable to find secret text credential " + whitelistItem.getHmacCredentialId());
}
final String hmacHeader = whitelistItem.getHmacHeader();
final String hmacKey = hmacKeyOpt.get().getSecret().getPlainText();
final String hmacAlgorithm = whitelistItem.getHmacAlgorithm();
hmacVerify(headers, postContent, hmacHeader, hmacKey, hmacAlgorithm);
return;
}
return;
}
throw new WhitelistException(
"Sending host \"" + remoteHost + "\" was not matched by whitelist.");
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
static void whitelistVerify(
final String remoteHost,
final WhitelistItem whitelistItem,
final Map<String, List<String>> headers,
final String postContent)
throws WhitelistException {
WhitelistHost whitelistHost = new WhitelistHost(whitelistItem.getHost());
if (HostVerifier.whitelistVerified(new WhitelistHost(remoteHost), whitelistHost)) {
if (whitelistItem.isHmacEnabled()) {
final Optional<StringCredentials> hmacKeyOpt =
CredentialsHelper.findCredentials(whitelistItem.getHmacCredentialId());
if (!hmacKeyOpt.isPresent()) {
throw new WhitelistException(
"Was unable to find secret text credential " + whitelistItem.getHmacCredentialId());
}
final String hmacHeader = whitelistItem.getHmacHeader();
final String hmacKey = hmacKeyOpt.get().getSecret().getPlainText();
final String hmacAlgorithm = whitelistItem.getHmacAlgorithm();
hmacVerify(headers, postContent, hmacHeader, hmacKey, hmacAlgorithm);
return;
}
return;
}
throw new WhitelistException(
"Sending host \"" + remoteHost + "\" was not matched by whitelist.");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
Set<? extends Element> compiledJsons = roundEnv.getElementsAnnotatedWith(analysis.compiledJsonElement);
Set<? extends Element> jacksonCreators = withJackson && jacksonCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jacksonCreatorElement) : new HashSet<>();
Set<? extends Element> jsonbCreators = withJsonb && jsonbCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jsonbCreatorElement) : new HashSet<>();
if (!compiledJsons.isEmpty() || !jacksonCreators.isEmpty() || !jsonbCreators.isEmpty()) {
Set<? extends Element> jsonConverters = roundEnv.getElementsAnnotatedWith(analysis.converterElement);
List<String> configurations = analysis.processConverters(jsonConverters);
analysis.processAnnotation(analysis.compiledJsonType, compiledJsons);
if (!jacksonCreators.isEmpty() && jacksonCreatorType != null) {
analysis.processAnnotation(jacksonCreatorType, jacksonCreators);
}
if (!jsonbCreators.isEmpty() && jsonbCreatorType != null) {
analysis.processAnnotation(jsonbCreatorType, jsonbCreators);
}
Map<String, StructInfo> structs = analysis.analyze();
if (analysis.hasError()) {
return false;
}
try {
String className = "dsl_json_Annotation_Processor_External_Serialization";
Writer writer = processingEnv.getFiler().createSourceFile(className).openWriter();
buildCode(writer, structs, allowInline);
writer.close();
writer = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", CONFIG).openWriter();
writer.write(className);
for (String conf : configurations) {
writer.write('\n');
writer.write(conf);
}
writer.close();
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed saving compiled json serialization files");
}
}
return false;
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader());
Set<Type> knownEncoders = dslJson.getRegisteredEncoders();
Set<Type> knownDecoders = dslJson.getRegisteredDecoders();
Set<String> allTypes = new HashSet<>();
for (Type t : knownEncoders) {
if (knownDecoders.contains(t)) {
allTypes.add(t.getTypeName());
}
}
final Analysis analysis = new Analysis(
processingEnv,
annotationUsage,
logLevel,
allTypes,
rawClass -> {
try {
Class<?> raw = Class.forName(rawClass);
return dslJson.canSerialize(raw) && dslJson.canDeserialize(raw);
} catch (Exception ignore) {
return false;
}
},
JsonIgnore,
NonNullable,
PropertyAlias,
JsonRequired,
Constructors,
Indexes,
unknownTypes,
false,
true,
true,
true);
Set<? extends Element> compiledJsons = roundEnv.getElementsAnnotatedWith(analysis.compiledJsonElement);
Set<? extends Element> jacksonCreators = withJackson && jacksonCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jacksonCreatorElement) : new HashSet<>();
Set<? extends Element> jsonbCreators = withJsonb && jsonbCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jsonbCreatorElement) : new HashSet<>();
if (!compiledJsons.isEmpty() || !jacksonCreators.isEmpty() || !jsonbCreators.isEmpty()) {
Set<? extends Element> jsonConverters = roundEnv.getElementsAnnotatedWith(analysis.converterElement);
List<String> configurations = analysis.processConverters(jsonConverters);
analysis.processAnnotation(analysis.compiledJsonType, compiledJsons);
if (!jacksonCreators.isEmpty() && jacksonCreatorType != null) {
analysis.processAnnotation(jacksonCreatorType, jacksonCreators);
}
if (!jsonbCreators.isEmpty() && jsonbCreatorType != null) {
analysis.processAnnotation(jsonbCreatorType, jsonbCreators);
}
Map<String, StructInfo> structs = analysis.analyze();
if (analysis.hasError()) {
return false;
}
try {
String className = "dsl_json_Annotation_Processor_External_Serialization";
Writer writer = processingEnv.getFiler().createSourceFile(className).openWriter();
buildCode(writer, structs, allowInline, allTypes);
writer.close();
writer = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", CONFIG).openWriter();
writer.write(className);
for (String conf : configurations) {
writer.write('\n');
writer.write(conf);
}
writer.close();
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed saving compiled json serialization files");
}
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
Set<? extends Element> jsonAnnotated = roundEnv.getElementsAnnotatedWith(jsonTypeElement);
if (!jsonAnnotated.isEmpty()) {
Map<String, StructInfo> structs = new HashMap<String, StructInfo>();
StringBuilder dsl = new StringBuilder();
dsl.append("module json {\n");
for (Element el : jsonAnnotated) {
findStructs(structs, el, "CompiledJson requires public no argument constructor");
}
findRelatedReferences(structs);
buildDsl(structs, dsl);
dsl.append("}");
if (dsl.length() < 20) {
return false;
}
String fullDsl = dsl.toString();
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, fullDsl);
String fileContent;
try {
fileContent = AnnotationCompiler.buildExternalJson(fullDsl, namespace, useJodaTime);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "DSL compilation error\n" + e.getMessage());
return false;
}
try {
JavaFileObject jfo = processingEnv.getFiler().createSourceFile("ExternalSerialization");
BufferedWriter bw = new BufferedWriter(jfo.openWriter());
bw.write(fileContent);
bw.close();
FileObject rfo = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/services/com.dslplatform.json.Configuration");
bw = new BufferedWriter(rfo.openWriter());
bw.write(namespace + ".json.ExternalSerialization");
bw.close();
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed saving compiled json serialization files");
}
}
return false;
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
Set<? extends Element> jsonAnnotated = roundEnv.getElementsAnnotatedWith(jsonTypeElement);
if (!jsonAnnotated.isEmpty()) {
Map<String, StructInfo> structs = new HashMap<String, StructInfo>();
StringBuilder dsl = new StringBuilder();
dsl.append("module json {\n");
for (Element el : jsonAnnotated) {
findStructs(structs, el, "CompiledJson requires public no argument constructor");
}
findRelatedReferences(structs);
DslOptions options = new DslOptions();
options.namespace = namespace;
buildDsl(structs, dsl, options);
dsl.append("}");
if (dsl.length() < 20) {
return false;
}
String fullDsl = dsl.toString();
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, fullDsl);
String fileContent;
try {
fileContent = AnnotationCompiler.buildExternalJson(fullDsl, options.namespace, options.useJodaTime);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "DSL compilation error\n" + e.getMessage());
return false;
}
try {
JavaFileObject jfo = processingEnv.getFiler().createSourceFile("ExternalSerialization");
BufferedWriter bw = new BufferedWriter(jfo.openWriter());
bw.write(fileContent);
bw.close();
FileObject rfo = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/services/com.dslplatform.json.Configuration");
bw = new BufferedWriter(rfo.openWriter());
bw.write(options.namespace + ".json.ExternalSerialization");
bw.close();
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed saving compiled json serialization files");
}
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || annotations.isEmpty()) {
return false;
}
final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader(getClass().getClassLoader()));
Set<Type> knownEncoders = dslJson.getRegisteredEncoders();
Set<Type> knownDecoders = dslJson.getRegisteredDecoders();
Set<String> allTypes = new HashSet<>();
for (Type t : knownEncoders) {
if (knownDecoders.contains(t)) {
allTypes.add(t.getTypeName());
}
}
final Analysis analysis = new Analysis(
processingEnv,
annotationUsage,
logLevel,
allTypes,
rawClass -> {
try {
Class<?> raw = Class.forName(rawClass);
return dslJson.canSerialize(raw) && dslJson.canDeserialize(raw);
} catch (Exception ignore) {
return false;
}
},
JsonIgnore,
NonNullable,
PropertyAlias,
JsonRequired,
Constructors,
Indexes,
unknownTypes,
false,
true,
true,
true);
Set<? extends Element> compiledJsons = roundEnv.getElementsAnnotatedWith(analysis.compiledJsonElement);
Set<? extends Element> jacksonCreators = withJackson && jacksonCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jacksonCreatorElement) : new HashSet<>();
Set<? extends Element> jsonbCreators = withJsonb && jsonbCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jsonbCreatorElement) : new HashSet<>();
if (!compiledJsons.isEmpty() || !jacksonCreators.isEmpty() || !jsonbCreators.isEmpty()) {
Set<? extends Element> jsonConverters = roundEnv.getElementsAnnotatedWith(analysis.converterElement);
List<String> configurations = analysis.processConverters(jsonConverters);
analysis.processAnnotation(analysis.compiledJsonType, compiledJsons);
if (!jacksonCreators.isEmpty() && jacksonCreatorType != null) {
analysis.processAnnotation(jacksonCreatorType, jacksonCreators);
}
if (!jsonbCreators.isEmpty() && jsonbCreatorType != null) {
analysis.processAnnotation(jsonbCreatorType, jsonbCreators);
}
Map<String, StructInfo> structs = analysis.analyze();
if (analysis.hasError()) {
return false;
}
final List<String> generatedFiles = new ArrayList<>();
final List<Element> originatingElements = new ArrayList<>();
for (Map.Entry<String, StructInfo> entry : structs.entrySet()) {
StructInfo structInfo = entry.getValue();
if (structInfo.type == ObjectType.CLASS && structInfo.attributes.isEmpty()) {
continue;
}
String classNamePath = findConverterName(entry.getValue());
try {
JavaFileObject converterFile = processingEnv.getFiler().createSourceFile(classNamePath, structInfo.element);
try (Writer writer = converterFile.openWriter()) {
buildCode(writer, entry.getKey(), structInfo, structs, allowInline, allTypes);
generatedFiles.add(classNamePath);
originatingElements.add(structInfo.element);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed saving compiled json serialization file " + classNamePath);
}
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed creating compiled json serialization file " + classNamePath);
}
}
if (configurationFileName != null) {
final List<String> allConfigurations = new ArrayList<>(configurations);
try {
FileObject configFile = processingEnv.getFiler()
.createSourceFile(configurationFileName, originatingElements.toArray(new Element[0]));
try (Writer writer = configFile.openWriter()) {
buildRootConfiguration(writer, configurationFileName, generatedFiles);
allConfigurations.add(configurationFileName);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed saving configuration file " + configurationFileName);
}
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed creating configuration file " + configurationFileName);
}
saveToServiceConfigFile(allConfigurations);
}
}
return false;
}
#location 70
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver() || annotations.isEmpty()) {
return false;
}
final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader(getClass().getClassLoader()));
Set<Type> knownEncoders = dslJson.getRegisteredEncoders();
Set<Type> knownDecoders = dslJson.getRegisteredDecoders();
Set<String> allTypes = new HashSet<>();
for (Type t : knownEncoders) {
if (knownDecoders.contains(t)) {
allTypes.add(t.getTypeName());
}
}
final Analysis analysis = new Analysis(
processingEnv,
annotationUsage,
logLevel,
allTypes,
rawClass -> {
try {
Class<?> raw = Class.forName(rawClass);
return dslJson.canSerialize(raw) && dslJson.canDeserialize(raw);
} catch (Exception ignore) {
return false;
}
},
JsonIgnore,
NonNullable,
PropertyAlias,
JsonRequired,
Constructors,
Indexes,
unknownTypes,
false,
true,
true,
true);
Set<? extends Element> compiledJsons = roundEnv.getElementsAnnotatedWith(analysis.compiledJsonElement);
Set<? extends Element> jacksonCreators = withJackson && jacksonCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jacksonCreatorElement) : new HashSet<>();
Set<? extends Element> jsonbCreators = withJsonb && jsonbCreatorElement != null ? roundEnv.getElementsAnnotatedWith(jsonbCreatorElement) : new HashSet<>();
if (!compiledJsons.isEmpty() || !jacksonCreators.isEmpty() || !jsonbCreators.isEmpty()) {
Set<? extends Element> jsonConverters = roundEnv.getElementsAnnotatedWith(analysis.converterElement);
List<String> configurations = analysis.processConverters(jsonConverters);
analysis.processAnnotation(analysis.compiledJsonType, compiledJsons);
if (!jacksonCreators.isEmpty() && jacksonCreatorType != null) {
analysis.processAnnotation(jacksonCreatorType, jacksonCreators);
}
if (!jsonbCreators.isEmpty() && jsonbCreatorType != null) {
analysis.processAnnotation(jsonbCreatorType, jsonbCreators);
}
Map<String, StructInfo> structs = analysis.analyze();
if (analysis.hasError()) {
return false;
}
final List<String> generatedFiles = new ArrayList<>();
final List<Element> originatingElements = new ArrayList<>();
for (Map.Entry<String, StructInfo> entry : structs.entrySet()) {
StructInfo structInfo = entry.getValue();
if (structInfo.type == ObjectType.CLASS && structInfo.attributes.isEmpty()) {
continue;
}
String classNamePath = findConverterName(entry.getValue());
try {
JavaFileObject converterFile = processingEnv.getFiler().createSourceFile(classNamePath, structInfo.element);
try (Writer writer = converterFile.openWriter()) {
buildCode(writer, entry.getKey(), structInfo, structs, allTypes);
generatedFiles.add(classNamePath);
originatingElements.add(structInfo.element);
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed saving compiled json serialization file " + classNamePath);
}
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed creating compiled json serialization file " + classNamePath);
}
}
if (configurationFileName != null) {
final List<String> allConfigurations = new ArrayList<>(configurations);
try {
FileObject configFile = processingEnv.getFiler()
.createSourceFile(configurationFileName, originatingElements.toArray(new Element[0]));
try (Writer writer = configFile.openWriter()) {
buildRootConfiguration(writer, configurationFileName, generatedFiles);
allConfigurations.add(configurationFileName);
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed saving configuration file " + configurationFileName);
}
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
"Failed creating configuration file " + configurationFileName);
}
saveToServiceConfigFile(allConfigurations);
}
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
Set<? extends Element> jsonAnnotated = roundEnv.getElementsAnnotatedWith(jsonTypeElement);
if (!jsonAnnotated.isEmpty()) {
Map<String, StructInfo> structs = new HashMap<String, StructInfo>();
CompileOptions options = new CompileOptions();
for (Element el : jsonAnnotated) {
findStructs(structs, options, el, "CompiledJson requires public no argument constructor");
}
findRelatedReferences(structs, options);
String dsl = buildDsl(structs, options);
if (options.hasError) {
return false;
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, dsl);
String fileContent;
try {
fileContent = AnnotationCompiler.buildExternalJson(dsl, options.toOptions(namespace));
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "DSL compilation error\n" + e.getMessage());
return false;
}
try {
JavaFileObject jfo = processingEnv.getFiler().createSourceFile("ExternalSerialization");
BufferedWriter bw = new BufferedWriter(jfo.openWriter());
bw.write(fileContent);
bw.close();
FileObject rfo = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/services/com.dslplatform.json.Configuration");
bw = new BufferedWriter(rfo.openWriter());
bw.write(namespace + ".json.ExternalSerialization");
bw.close();
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed saving compiled json serialization files");
}
}
return false;
}
#location 38
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
Set<? extends Element> jsonAnnotated = roundEnv.getElementsAnnotatedWith(jsonTypeElement);
if (!jsonAnnotated.isEmpty()) {
Map<String, StructInfo> structs = new HashMap<String, StructInfo>();
CompileOptions options = new CompileOptions();
for (Element el : jsonAnnotated) {
findStructs(structs, options, el, "CompiledJson requires public no argument constructor");
}
findRelatedReferences(structs, options);
String dsl = buildDsl(structs, options);
if (options.hasError) {
return false;
}
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, dsl);
String fileContent;
try {
fileContent = AnnotationCompiler.buildExternalJson(dsl, options.toOptions(namespace));
} catch (Exception e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "DSL compilation error\n" + e.getMessage());
return false;
}
try {
String className = namespace + ".json.ExternalSerialization";
Writer writer = processingEnv.getFiler().createSourceFile(className).openWriter();
writer.write(fileContent);
writer.close();
writer = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", CONFIG).openWriter();
writer.write(className);
writer.close();
} catch (IOException e) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Failed saving compiled json serialization files");
}
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
Gson gson = new Gson();
JsonElement element = gson.fromJson(responseData, JsonElement.class);
JsonObject object = element.getAsJsonObject();
String clientDataJSON = object.get("clientDataJSON").getAsString();
String authenticatorData = object.get("authenticatorData").getAsString();
String signature = object.get("signature").getAsString();
AuthenticatorAssertionResponse assertion =
new AuthenticatorAssertionResponse(clientDataJSON, authenticatorData, signature);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
assertion.getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), assertion);
try {
U2fServer.verifyAssertion(cred, user.getEmail(), session);
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
Gson gson = new Gson();
JsonElement element = gson.fromJson(responseData, JsonElement.class);
JsonObject object = element.getAsJsonObject();
String clientDataJSON = object.get("clientDataJSON").getAsString();
String authenticatorData = object.get("authenticatorData").getAsString();
String credentialId = object.get("credentialId").getAsString();
String signature = object.get("signature").getAsString();
AuthenticatorAssertionResponse assertion =
new AuthenticatorAssertionResponse(clientDataJSON, authenticatorData, signature);
// TODO
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), assertion);
try {
U2fServer.verifyAssertion(cred, user.getEmail(), session);
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@ApiMethod(name = "processRegistrationResponse")
public List<String> processRegistrationResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
Gson gson = new Gson();
JsonElement element = gson.fromJson(responseData, JsonElement.class);
AuthenticatorAttestationResponse attestation =
new AuthenticatorAttestationResponse(element);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
attestation.getAttestationObject().getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), attestation);
try {
switch (cred.getAttestationType()) {
case FIDOU2F:
U2fServer.registerCredential(cred, user.getEmail(), session, Constants.APP_ID);
break;
case ANDROIDSAFETYNET:
AndroidSafetyNetServer.registerCredential(
cred, user.getEmail(), session, Constants.APP_ID);
break;
default:
// This should never happen.
}
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@ApiMethod(name = "processRegistrationResponse")
public List<String> processRegistrationResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
Gson gson = new Gson();
JsonElement element = gson.fromJson(responseData, JsonElement.class);
JsonObject object = element.getAsJsonObject();
String clientDataJSON = object.get("clientDataJSON").getAsString();
String attestationObject = object.get("attestationObject").getAsString();
AuthenticatorAttestationResponse attestation =
new AuthenticatorAttestationResponse(clientDataJSON, attestationObject);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
attestation.getAttestationObject().getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), attestation);
try {
switch (cred.getAttestationType()) {
case FIDOU2F:
U2fServer.registerCredential(cred, user.getEmail(), session, Constants.APP_ID);
break;
case ANDROIDSAFETYNET:
AndroidSafetyNetServer.registerCredential(
cred, user.getEmail(), session, Constants.APP_ID);
break;
default:
// This should never happen.
}
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
AuthenticatorAssertionResponse assertion =
new AuthenticatorAssertionResponse(responseData);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
assertion.getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), assertion);
try {
U2fServer.verifyAssertion(cred, user.getEmail(), session);
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@ApiMethod(name = "processSignResponse")
public List<String> processSignResponse(
@Named("responseData") String responseData, User user)
throws OAuthRequestException, ResponseException {
if (user == null) {
throw new OAuthRequestException("User is not authenticated");
}
Gson gson = new Gson();
JsonElement element = gson.fromJson(responseData, JsonElement.class);
JsonObject object = element.getAsJsonObject();
String clientDataJSON = object.get("clientDataJSON").getAsString();
String authenticatorData = object.get("authenticatorData").getAsString();
String signature = object.get("signature").getAsString();
AuthenticatorAssertionResponse assertion =
new AuthenticatorAssertionResponse(clientDataJSON, authenticatorData, signature);
// TODO
String credentialId = BaseEncoding.base64Url().encode(
assertion.getAuthenticatorData().getAttData().getCredentialId());
String type = null;
String session = null;
PublicKeyCredential cred = new PublicKeyCredential(credentialId, type,
BaseEncoding.base64Url().decode(credentialId), assertion);
try {
U2fServer.verifyAssertion(cred, user.getEmail(), session);
} catch (ServletException e) {
// TODO
}
Credential credential = new Credential(cred);
credential.save(user.getEmail());
List<String> resultList = new ArrayList<String>();
resultList.add(credential.toJson());
return resultList;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void shouldRunAllQueuedCallbacks() throws Exception {
final AtomicInteger count = new AtomicInteger();
final CountDownLatch latch = new CountDownLatch(1000);
for(int i = 0; i < 20; i++) {
new Thread(new Runnable() {
@Override
public void run() {
final Queue<Runnable> queries = new LinkedList<>();
for(int j = 0; j < 50; j++) {
queries.add(() -> pool.query("INSERT INTO CP_TEST VALUES($1)", asList(UUID.randomUUID()), result -> {
latch.countDown();
count.incrementAndGet();
if(!queries.isEmpty()) {
queries.poll().run();
}
}, err));
}
queries.poll().run();
}
}).start();
}
assertTrue(latch.await(5L, TimeUnit.SECONDS));
assertEquals(1000, count.get());
ResultHolder result = new ResultHolder();
pool.query("SELECT COUNT(*) FROM CP_TEST", result, result.errorHandler());
assertEquals(count.get(), result.result().row(0).getLong(0).longValue());
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void shouldRunAllQueuedCallbacks() throws Exception {
final int count = 1000;
IntFunction<Callable<ResultSet>> insert = value -> () -> dbr.query("INSERT INTO CP_TEST VALUES($1)", singletonList(value));
List<Callable<ResultSet>> tasks = IntStream.range(0, count).mapToObj(insert).collect(toList());
ExecutorService executor = Executors.newFixedThreadPool(20);
executor.invokeAll(tasks).stream().map(this::await);
assertEquals(count, dbr.query("SELECT COUNT(*) FROM CP_TEST").row(0).getLong(0).longValue());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRoot() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals("Root Entry", root.getName());
assertTrue(root.isRoot());
assertFalse(root.isFile());
assertFalse(root.isDirectory());
assertEquals(0, root.length());
assertNull(root.getInputStream());
}
#location 13
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testRoot() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals("Root Entry", root.getName());
assertTrue(root.isRoot());
assertFalse(root.isFile());
assertFalse(root.isDirectory());
assertEquals(0, root.length());
assertNull(root.getInputStream());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getHeight() throws IOException {
if (compression == 1) { // 1 = no compression
Entry height = ifd.getEntryById(TIFF.TAG_IMAGE_HEIGHT);
if (height == null) {
throw new IIOException("Missing dimensions for RAW EXIF thumbnail");
}
return ((Number) height.getValue()).intValue();
}
else if (compression == 6) { // 6 = JPEG compression
return readJPEGCached(false).getHeight();
}
else {
throw new IIOException("Unsupported EXIF thumbnail compression: " + compression);
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getHeight() throws IOException {
if (compression == 1) { // 1 = no compression
Entry height = ifd.getEntryById(TIFF.TAG_IMAGE_HEIGHT);
if (height == null) {
throw new IIOException("Missing dimensions for unknown EXIF thumbnail");
}
return ((Number) height.getValue()).intValue();
}
else if (compression == 6) { // 6 = JPEG compression
return readJPEGCached(false).getHeight();
}
else {
throw new IIOException("Unsupported EXIF thumbnail compression (expected 1 or 6): " + compression);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private DataOutput createCompressorStream(final RenderedImage image, final ImageWriteParam param, final Map<Integer, Entry> entries) {
/*
36 MB test data:
No compression:
Write time: 450 ms
output.length: 36000226
PackBits:
Write time: 688 ms
output.length: 30322187
Deflate, BEST_SPEED (1):
Write time: 1276 ms
output.length: 14128866
Deflate, 2:
Write time: 1297 ms
output.length: 13848735
Deflate, 3:
Write time: 1594 ms
output.length: 13103224
Deflate, 4:
Write time: 1663 ms
output.length: 13380899 (!!)
5
Write time: 1941 ms
output.length: 13171244
6
Write time: 2311 ms
output.length: 12845101
7: Write time: 2853 ms
output.length: 12759426
8:
Write time: 4429 ms
output.length: 12624517
Deflate: DEFAULT_COMPRESSION (6?):
Write time: 2357 ms
output.length: 12845101
Deflate, BEST_COMPRESSION (9):
Write time: 4998 ms
output.length: 12600399
*/
// Use predictor by default for LZW and ZLib/Deflate
// TODO: Unless explicitly disabled in TIFFImageWriteParam
int compression = (int) entries.get(TIFF.TAG_COMPRESSION).getValue();
OutputStream stream;
switch (compression) {
case TIFFBaseline.COMPRESSION_NONE:
return imageOutput;
case TIFFBaseline.COMPRESSION_PACKBITS:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new PackBitsEncoder(), true);
// NOTE: PackBits + Predictor is possible, but not generally supported, disable it by default
// (and probably not even allow it, see http://stackoverflow.com/questions/20337400/tiff-packbits-compression-with-predictor-step)
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_ZLIB:
case TIFFExtension.COMPRESSION_DEFLATE:
// NOTE: This interpretation does the opposite of the JAI TIFFImageWriter, but seems more correct.
// API Docs says:
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
// However, the JAI TIFFImageWriter uses:
// if (param & compression etc...) {
// float quality = param.getCompressionQuality();
// deflateLevel = (int)(1 + 8*quality);
// } else {
// deflateLevel = Deflater.DEFAULT_COMPRESSION;
// }
// (in other words, 0.0 means 1 == BEST_SPEED, 1.0 means 9 == BEST_COMPRESSION)
// PS: PNGImageWriter just uses hardcoded BEST_COMPRESSION... :-P
int deflateSetting = Deflater.BEST_SPEED; // This is consistent with default compression quality being 1.0 and 0 meaning max compression...
if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
deflateSetting = Deflater.BEST_COMPRESSION - Math.round((Deflater.BEST_COMPRESSION - 1) * param.getCompressionQuality());
}
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new DeflaterOutputStream(stream, new Deflater(deflateSetting), 1024);
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), image.getTile(0, 0).getNumBands(), image.getColorModel().getComponentSize(0), imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_LZW:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new LZWEncoder((image.getTileWidth() * image.getTileHeight() * image.getColorModel().getPixelSize() + 7) / 8));
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), image.getTile(0, 0).getNumBands(), image.getColorModel().getComponentSize(0), imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE:
case TIFFExtension.COMPRESSION_CCITT_T4:
case TIFFExtension.COMPRESSION_CCITT_T6:
long option = 0L;
if (compression != TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE) {
option = (long) entries.get(compression == TIFFExtension.COMPRESSION_CCITT_T4 ? TIFF.TAG_GROUP3OPTIONS : TIFF.TAG_GROUP4OPTIONS).getValue();
}
Entry fillOrderEntry = entries.get(TIFF.TAG_FILL_ORDER);
int fillOrder = (int) (fillOrderEntry != null ? fillOrderEntry.getValue() : TIFFBaseline.FILL_LEFT_TO_RIGHT);
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new CCITTFaxEncoderStream(stream, image.getTileWidth(), image.getTileHeight(), compression, fillOrder, option);
return new DataOutputStream(stream);
}
throw new IllegalArgumentException(String.format("Unsupported TIFF compression: %d", compression));
}
#location 89
#vulnerability type RESOURCE_LEAK
|
#fixed code
private DataOutput createCompressorStream(final RenderedImage image, final ImageWriteParam param, final Map<Integer, Entry> entries) {
/*
36 MB test data:
No compression:
Write time: 450 ms
output.length: 36000226
PackBits:
Write time: 688 ms
output.length: 30322187
Deflate, BEST_SPEED (1):
Write time: 1276 ms
output.length: 14128866
Deflate, 2:
Write time: 1297 ms
output.length: 13848735
Deflate, 3:
Write time: 1594 ms
output.length: 13103224
Deflate, 4:
Write time: 1663 ms
output.length: 13380899 (!!)
5
Write time: 1941 ms
output.length: 13171244
6
Write time: 2311 ms
output.length: 12845101
7: Write time: 2853 ms
output.length: 12759426
8:
Write time: 4429 ms
output.length: 12624517
Deflate: DEFAULT_COMPRESSION (6?):
Write time: 2357 ms
output.length: 12845101
Deflate, BEST_COMPRESSION (9):
Write time: 4998 ms
output.length: 12600399
*/
int samplesPerPixel = (Integer) entries.get(TIFF.TAG_SAMPLES_PER_PIXEL).getValue();
int bitPerSample = ((short[]) entries.get(TIFF.TAG_BITS_PER_SAMPLE).getValue())[0];
// Use predictor by default for LZW and ZLib/Deflate
// TODO: Unless explicitly disabled in TIFFImageWriteParam
int compression = (int) entries.get(TIFF.TAG_COMPRESSION).getValue();
OutputStream stream;
switch (compression) {
case TIFFBaseline.COMPRESSION_NONE:
return imageOutput;
case TIFFBaseline.COMPRESSION_PACKBITS:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new PackBitsEncoder(), true);
// NOTE: PackBits + Predictor is possible, but not generally supported, disable it by default
// (and probably not even allow it, see http://stackoverflow.com/questions/20337400/tiff-packbits-compression-with-predictor-step)
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_ZLIB:
case TIFFExtension.COMPRESSION_DEFLATE:
// NOTE: This interpretation does the opposite of the JAI TIFFImageWriter, but seems more correct.
// API Docs says:
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
// However, the JAI TIFFImageWriter uses:
// if (param & compression etc...) {
// float quality = param.getCompressionQuality();
// deflateLevel = (int)(1 + 8*quality);
// } else {
// deflateLevel = Deflater.DEFAULT_COMPRESSION;
// }
// (in other words, 0.0 means 1 == BEST_SPEED, 1.0 means 9 == BEST_COMPRESSION)
// PS: PNGImageWriter just uses hardcoded BEST_COMPRESSION... :-P
int deflateSetting = Deflater.BEST_SPEED; // This is consistent with default compression quality being 1.0 and 0 meaning max compression...
if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
deflateSetting = Deflater.BEST_COMPRESSION - Math.round((Deflater.BEST_COMPRESSION - 1) * param.getCompressionQuality());
}
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new DeflaterOutputStream(stream, new Deflater(deflateSetting), 1024);
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), samplesPerPixel, bitPerSample, imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_LZW:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new LZWEncoder((image.getTileWidth() * image.getTileHeight() * samplesPerPixel * bitPerSample + 7) / 8));
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), samplesPerPixel, bitPerSample, imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE:
case TIFFExtension.COMPRESSION_CCITT_T4:
case TIFFExtension.COMPRESSION_CCITT_T6:
long option = 0L;
if (compression != TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE) {
option = (long) entries.get(compression == TIFFExtension.COMPRESSION_CCITT_T4 ? TIFF.TAG_GROUP3OPTIONS : TIFF.TAG_GROUP4OPTIONS).getValue();
}
Entry fillOrderEntry = entries.get(TIFF.TAG_FILL_ORDER);
int fillOrder = (int) (fillOrderEntry != null ? fillOrderEntry.getValue() : TIFFBaseline.FILL_LEFT_TO_RIGHT);
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new CCITTFaxEncoderStream(stream, image.getTileWidth(), image.getTileHeight(), compression, fillOrder, option);
return new DataOutputStream(stream);
}
throw new IllegalArgumentException(String.format("Unsupported TIFF compression: %d", compression));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void writeBody(ByteArrayOutputStream pImageData) throws IOException {
imageOutput.writeInt(IFF.CHUNK_BODY);
imageOutput.writeInt(pImageData.size());
// NOTE: This is much faster than mOutput.write(pImageData.toByteArray())
// as the data array is not duplicated
pImageData.writeTo(IIOUtil.createStreamAdapter(imageOutput));
if (pImageData.size() % 2 == 0) {
imageOutput.writeByte(0); // PAD
}
imageOutput.flush();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void writeBody(ByteArrayOutputStream pImageData) throws IOException {
imageOutput.writeInt(IFF.CHUNK_BODY);
imageOutput.writeInt(pImageData.size());
// NOTE: This is much faster than imageOutput.write(pImageData.toByteArray())
// as the data array is not duplicated
OutputStream adapter = IIOUtil.createStreamAdapter(imageOutput);
try {
pImageData.writeTo(adapter);
}
finally {
adapter.close();
}
if (pImageData.size() % 2 == 0) {
imageOutput.writeByte(0); // PAD
}
imageOutput.flush();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRoot() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals("Root Entry", root.getName());
assertTrue(root.isRoot());
assertFalse(root.isFile());
assertFalse(root.isDirectory());
assertEquals(0, root.length());
assertNull(root.getInputStream());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testRoot() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals("Root Entry", root.getName());
assertTrue(root.isRoot());
assertFalse(root.isFile());
assertFalse(root.isDirectory());
assertEquals(0, root.length());
assertNull(root.getInputStream());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected IIOMetadataNode getStandardChromaNode() {
IIOMetadataNode chroma = new IIOMetadataNode("Chroma");
// Handle ColorSpaceType (RGB/CMYK/YCbCr etc)...
Entry photometricTag = ifd.getEntryById(TIFF.TAG_PHOTOMETRIC_INTERPRETATION);
int photometricValue = getValueAsInt(photometricTag); // No default for this tag!
Entry samplesPerPixelTag = ifd.getEntryById(TIFF.TAG_SAMPLES_PER_PIXEL);
Entry bitsPerSampleTag = ifd.getEntryById(TIFF.TAG_BITS_PER_SAMPLE);
int numChannelsValue = samplesPerPixelTag != null
? getValueAsInt(samplesPerPixelTag)
: bitsPerSampleTag.valueCount();
IIOMetadataNode colorSpaceType = new IIOMetadataNode("ColorSpaceType");
chroma.appendChild(colorSpaceType);
switch (photometricValue) {
case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO:
case TIFFBaseline.PHOTOMETRIC_MASK: // It's really a transparency mask/alpha channel, but...
colorSpaceType.setAttribute("value", "GRAY");
break;
case TIFFBaseline.PHOTOMETRIC_RGB:
case TIFFBaseline.PHOTOMETRIC_PALETTE:
colorSpaceType.setAttribute("value", "RGB");
break;
case TIFFExtension.PHOTOMETRIC_YCBCR:
colorSpaceType.setAttribute("value", "YCbCr");
break;
case TIFFExtension.PHOTOMETRIC_CIELAB:
case TIFFExtension.PHOTOMETRIC_ICCLAB:
case TIFFExtension.PHOTOMETRIC_ITULAB:
colorSpaceType.setAttribute("value", "Lab");
break;
case TIFFExtension.PHOTOMETRIC_SEPARATED:
// TODO: May be CMYK, or something else... Consult InkSet and NumberOfInks!
if (numChannelsValue == 3) {
colorSpaceType.setAttribute("value", "CMY");
}
else {
colorSpaceType.setAttribute("value", "CMYK");
}
break;
case TIFFCustom.PHOTOMETRIC_LOGL: // ..?
case TIFFCustom.PHOTOMETRIC_LOGLUV:
colorSpaceType.setAttribute("value", "Luv");
break;
case TIFFCustom.PHOTOMETRIC_CFA:
case TIFFCustom.PHOTOMETRIC_LINEAR_RAW: // ...or is this RGB?
colorSpaceType.setAttribute("value", "3CLR");
break;
default:
colorSpaceType.setAttribute("value", Integer.toHexString(numChannelsValue) + "CLR");
break;
}
// NumChannels
IIOMetadataNode numChannels = new IIOMetadataNode("NumChannels");
chroma.appendChild(numChannels);
if (photometricValue == TIFFBaseline.PHOTOMETRIC_PALETTE) {
numChannels.setAttribute("value", "3");
}
else {
numChannels.setAttribute("value", Integer.toString(numChannelsValue));
}
// BlackIsZero (defaults to TRUE)
IIOMetadataNode blackIsZero = new IIOMetadataNode("BlackIsZero");
chroma.appendChild(blackIsZero);
switch (photometricValue) {
case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
blackIsZero.setAttribute("value", "FALSE");
break;
default:
break;
}
Entry colorMapTag = ifd.getEntryById(TIFF.TAG_COLOR_MAP);
if (colorMapTag != null) {
int[] colorMapValues = (int[]) colorMapTag.getValue();
IIOMetadataNode palette = new IIOMetadataNode("Palette");
chroma.appendChild(palette);
int count = colorMapValues.length / 3;
for (int i = 0; i < count; i++) {
IIOMetadataNode paletteEntry = new IIOMetadataNode("PaletteEntry");
paletteEntry.setAttribute("index", Integer.toString(i));
// TODO: See TIFFImageReader createIndexColorModel, to detect 8 bit colorMap
paletteEntry.setAttribute("red", Integer.toString((colorMapValues[i] >> 8) & 0xff));
paletteEntry.setAttribute("green", Integer.toString((colorMapValues[i + count] >> 8) & 0xff));
paletteEntry.setAttribute("blue", Integer.toString((colorMapValues[i + count * 2] >> 8) & 0xff));
palette.appendChild(paletteEntry);
}
}
return chroma;
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected IIOMetadataNode getStandardChromaNode() {
IIOMetadataNode chroma = new IIOMetadataNode("Chroma");
// Handle ColorSpaceType (RGB/CMYK/YCbCr etc)...
Entry photometricTag = ifd.getEntryById(TIFF.TAG_PHOTOMETRIC_INTERPRETATION);
int photometricValue = getValueAsInt(photometricTag); // No default for this tag!
int numChannelsValue = getSamplesPerPixelWithFallback();
IIOMetadataNode colorSpaceType = new IIOMetadataNode("ColorSpaceType");
chroma.appendChild(colorSpaceType);
switch (photometricValue) {
case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO:
case TIFFBaseline.PHOTOMETRIC_MASK: // It's really a transparency mask/alpha channel, but...
colorSpaceType.setAttribute("value", "GRAY");
break;
case TIFFBaseline.PHOTOMETRIC_RGB:
case TIFFBaseline.PHOTOMETRIC_PALETTE:
colorSpaceType.setAttribute("value", "RGB");
break;
case TIFFExtension.PHOTOMETRIC_YCBCR:
colorSpaceType.setAttribute("value", "YCbCr");
break;
case TIFFExtension.PHOTOMETRIC_CIELAB:
case TIFFExtension.PHOTOMETRIC_ICCLAB:
case TIFFExtension.PHOTOMETRIC_ITULAB:
colorSpaceType.setAttribute("value", "Lab");
break;
case TIFFExtension.PHOTOMETRIC_SEPARATED:
// TODO: May be CMYK, or something else... Consult InkSet and NumberOfInks!
if (numChannelsValue == 3) {
colorSpaceType.setAttribute("value", "CMY");
}
else {
colorSpaceType.setAttribute("value", "CMYK");
}
break;
case TIFFCustom.PHOTOMETRIC_LOGL: // ..?
case TIFFCustom.PHOTOMETRIC_LOGLUV:
colorSpaceType.setAttribute("value", "Luv");
break;
case TIFFCustom.PHOTOMETRIC_CFA:
case TIFFCustom.PHOTOMETRIC_LINEAR_RAW: // ...or is this RGB?
colorSpaceType.setAttribute("value", "3CLR");
break;
default:
colorSpaceType.setAttribute("value", Integer.toHexString(numChannelsValue) + "CLR");
break;
}
// NumChannels
IIOMetadataNode numChannels = new IIOMetadataNode("NumChannels");
chroma.appendChild(numChannels);
if (photometricValue == TIFFBaseline.PHOTOMETRIC_PALETTE) {
numChannels.setAttribute("value", "3");
}
else {
numChannels.setAttribute("value", Integer.toString(numChannelsValue));
}
// BlackIsZero (defaults to TRUE)
IIOMetadataNode blackIsZero = new IIOMetadataNode("BlackIsZero");
chroma.appendChild(blackIsZero);
switch (photometricValue) {
case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO:
blackIsZero.setAttribute("value", "FALSE");
break;
default:
break;
}
Entry colorMapTag = ifd.getEntryById(TIFF.TAG_COLOR_MAP);
if (colorMapTag != null) {
int[] colorMapValues = (int[]) colorMapTag.getValue();
IIOMetadataNode palette = new IIOMetadataNode("Palette");
chroma.appendChild(palette);
int count = colorMapValues.length / 3;
for (int i = 0; i < count; i++) {
IIOMetadataNode paletteEntry = new IIOMetadataNode("PaletteEntry");
paletteEntry.setAttribute("index", Integer.toString(i));
// TODO: See TIFFImageReader createIndexColorModel, to detect 8 bit colorMap
paletteEntry.setAttribute("red", Integer.toString((colorMapValues[i] >> 8) & 0xff));
paletteEntry.setAttribute("green", Integer.toString((colorMapValues[i + count] >> 8) & 0xff));
paletteEntry.setAttribute("blue", Integer.toString((colorMapValues[i + count * 2] >> 8) & 0xff));
palette.appendChild(paletteEntry);
}
}
return chroma;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testEOFExceptionInSegmentParsingShouldNotCreateBadState() throws IOException {
ImageInputStream iis = new JPEGSegmentImageInputStream(ImageIO.createImageInputStream(getClassLoaderResource("/broken-jpeg/broken-no-sof-ascii-transfer-mode.jpg")));
byte[] buffer = new byte[4096];
// NOTE: This is a simulation of how the native parts of com.sun...JPEGImageReader would read the image...
assertEquals(2, iis.read(buffer, 0, buffer.length));
assertEquals(2, iis.getStreamPosition());
iis.seek(0x2012); // bad segment length, should have been 0x0012, not 0x2012
assertEquals(0x2012, iis.getStreamPosition());
// So far, so good (but stream position is now really beyond EOF)...
// This however, will blow up with an EOFException internally (but we'll return -1 to be good)
assertEquals(-1, iis.read(buffer, 0, buffer.length));
assertEquals(0x2012, iis.getStreamPosition());
// Again, should just continue returning -1 for ever
assertEquals(-1, iis.read(buffer, 0, buffer.length));
assertEquals(0x2012, iis.getStreamPosition());
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testEOFExceptionInSegmentParsingShouldNotCreateBadState() throws IOException {
ImageInputStream iis = new JPEGSegmentImageInputStream(ImageIO.createImageInputStream(getClassLoaderResource("/broken-jpeg/broken-no-sof-ascii-transfer-mode.jpg")));
byte[] buffer = new byte[4096];
// NOTE: This is a simulation of how the native parts of com.sun...JPEGImageReader would read the image...
assertEquals(2, iis.read(buffer, 0, buffer.length));
assertEquals(2, iis.getStreamPosition());
iis.seek(0x2012); // bad segment length, should have been 0x0012, not 0x2012
assertEquals(0x2012, iis.getStreamPosition());
// So far, so good (but stream position is now really beyond EOF)...
// This however, will blow up with an EOFException internally (but we'll return -1 to be good)
assertEquals(-1, iis.read(buffer, 0, buffer.length));
assertEquals(-1, iis.read());
assertEquals(0x2012, iis.getStreamPosition());
// Again, should just continue returning -1 for ever
assertEquals(-1, iis.read(buffer, 0, buffer.length));
assertEquals(-1, iis.read());
assertEquals(0x2012, iis.getStreamPosition());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadThumbsCatalogFile() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals(25, root.getChildEntries().size());
Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream());
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testReadThumbsCatalogFile() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals(25, root.getChildEntries().size());
Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testContents() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = new TreeSet<Entry>(root.getChildEntries());
assertEquals(25, children.size());
// Weirdness in the file format, name is *written backwards* 1-24 + Catalog
for (String name : "1,2,3,4,5,6,7,8,9,01,02,11,12,21,22,31,32,41,42,51,61,71,81,91,Catalog".split(",")) {
assertEquals(name, children.first().getName());
children.remove(children.first());
}
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testContents() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = new TreeSet<Entry>(root.getChildEntries());
assertEquals(25, children.size());
// Weirdness in the file format, name is *written backwards* 1-24 + Catalog
for (String name : "1,2,3,4,5,6,7,8,9,01,02,11,12,21,22,31,32,41,42,51,61,71,81,91,Catalog".split(",")) {
assertEquals(name, children.first().getName());
children.remove(children.first());
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.