output
stringlengths 79
30.1k
| instruction
stringclasses 1
value | input
stringlengths 216
28.9k
|
---|---|---|
#fixed code
private void incrementalCompile( Set<Object> drivers )
{
for( Object driver: drivers )
{
//noinspection unchecked
Set<IFile> files = ((Collection<File>)ReflectUtil.method( driver, "getResourceFiles" ).invoke() ).stream().map( (File f) -> ManifoldHost.getFileSystem().getIFile( f ) )
.collect( Collectors.toSet() );
for( ITypeManifold tm : ManifoldHost.instance().getCurrentModule().getTypeManifolds() )
{
for( IFile file: files )
{
Set<String> types = Arrays.stream( tm.getTypesForFile( file ) ).collect( Collectors.toSet() );
if( types.size() > 0 )
{
ReflectUtil.method( driver, "mapTypesToFile", Set.class, File.class ).invoke( types, file.toJavaFile() );
for( String fqn : types )
{
// This call surfaces the type in the compiler. If compiling in "static" mode, this means
// the type will be compiled to disk.
IDynamicJdk.instance().getTypeElement( _tp.getContext(), (JCTree.JCCompilationUnit)_tp.getCompilationUnit(), fqn );
}
}
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void incrementalCompile( Set<Object> drivers )
{
JavacElements elementUtils = JavacElements.instance( _tp.getContext() );
for( Object driver: drivers )
{
//noinspection unchecked
Set<IFile> files = ((Collection<File>)ReflectUtil.method( driver, "getResourceFiles" ).invoke() ).stream().map( (File f) -> ManifoldHost.getFileSystem().getIFile( f ) )
.collect( Collectors.toSet() );
for( ITypeManifold tm : ManifoldHost.instance().getCurrentModule().getTypeManifolds() )
{
for( IFile file: files )
{
Set<String> types = Arrays.stream( tm.getTypesForFile( file ) ).collect( Collectors.toSet() );
if( types.size() > 0 )
{
ReflectUtil.method( driver, "mapTypesToFile", Set.class, File.class ).invoke( types, file.toJavaFile() );
for( String fqn : types )
{
// This call surfaces the type in the compiler. If compiling in "static" mode, this means
// the type will be compiled to disk.
elementUtils.getTypeElement( fqn );
}
}
}
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public Collection<String> getAllTypeNames()
{
FqnCache<LocklessLazyVar<M>> fqnCache = _fqnToModel.get();
if( fqnCache.isEmpty() )
{
return Collections.emptySet();
}
return fqnCache.getFqns();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public Collection<String> getAllTypeNames()
{
return _fqnToModel.get().getFqns();
}
#location 4
#vulnerability type NULL_DEREFERENCE |
#fixed code
public Tree getParent( Tree node )
{
return _parents.getParent( node );
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public Tree getParent( Tree node )
{
TreePath2 path = TreePath2.getPath( getCompilationUnit(), node );
if( path == null )
{
// null is indiciative of Generation phase where trees are no longer attached to symobls so the comp unit is detached
// use the root tree instead, which is mostly ok, mostly
path = TreePath2.getPath( _tree, node );
}
TreePath2 parentPath = path.getParentPath();
return parentPath == null ? null : parentPath.getLeaf();
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
public ItemList getDataItemList() throws RiotApiException {
return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, (ItemListData) null);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public ItemList getDataItemList() throws RiotApiException {
return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
#fixed code
public RiotApiException getException() {
return exception;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public RiotApiException getException() {
if (!isFailed()) {
return null;
}
return exception;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected static CharSequence encodeUriQuery(CharSequence in) {
//Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
StringBuilder outBuf = null;
Formatter formatter = null;
for(int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
boolean escape = true;
if (c < 128) {
if (asciiQueryChars.get((int)c)) {
escape = false;
}
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
escape = false;
}
if (!escape) {
if (outBuf != null)
outBuf.append(c);
} else {
//escape
if (outBuf == null) {
outBuf = new StringBuilder(in.length() + 5*3);
outBuf.append(in,0,i);
try {
formatter = new Formatter(outBuf);
} finally {
if (formatter != null) {
formatter.flush();
formatter.close();
}
}
}
//leading %, 0 padded, width 2, capital hex
formatter.format("%%%02X",(int)c);//TODO
}
}
return outBuf != null ? outBuf : in;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected static CharSequence encodeUriQuery(CharSequence in) {
//Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
StringBuilder outBuf = null;
Formatter formatter = null;
for(int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
boolean escape = true;
if (c < 128) {
if (asciiQueryChars.get((int)c)) {
escape = false;
}
} else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
escape = false;
}
if (!escape) {
if (outBuf != null)
outBuf.append(c);
} else {
//escape
if (outBuf == null) {
outBuf = new StringBuilder(in.length() + 5*3);
outBuf.append(in,0,i);
formatter = new Formatter(outBuf);
}
//leading %, 0 padded, width 2, capital hex
formatter.format("%%%02X",(int)c);//TODO
}
}
return outBuf != null ? outBuf : in;
}
#location 29
#vulnerability type RESOURCE_LEAK |
#fixed code
public static UrlBuilder fromString(final String url, final Charset inputEncoding) {
if (url.isEmpty()) {
return new UrlBuilder();
}
final Matcher m = URI_PATTERN.matcher(url);
String protocol = null, hostName = null, path = null, anchor = null;
Integer port = null;
final Map<String, List<String>> queryParameters;
if (m.find()) {
protocol = m.group(2);
if (m.group(4) != null) {
final Matcher n = AUTHORITY_PATTERN.matcher(m.group(4));
if (n.find()) {
hostName = IDN.toUnicode(n.group(1));
if (n.group(3) != null) {
port = Integer.parseInt(n.group(3));
}
}
}
path = decodePath(m.group(5), inputEncoding);
queryParameters = decodeQueryParameters(m.group(7), inputEncoding);
anchor = m.group(9);
} else {
queryParameters = emptyMap();
}
return of(inputEncoding, DEFAULT_ENCODING, protocol, hostName, port, path, queryParameters, anchor);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static UrlBuilder fromString(final String url, final Charset inputEncoding) {
if (url.isEmpty()) {
return new UrlBuilder();
}
final Matcher m = URI_PATTERN.matcher(url);
String protocol = null, hostName = null, path = null, anchor = null;
Integer port = null;
Map<String, List<String>> queryParameters = null;
if (m.find()) {
protocol = m.group(2);
if (m.group(4) != null) {
final Matcher n = AUTHORITY_PATTERN.matcher(m.group(4));
if (n.find()) {
hostName = IDN.toUnicode(n.group(1));
if (n.group(3) != null) {
port = Integer.parseInt(n.group(3));
}
}
}
path = decodePath(m.group(5), inputEncoding);
queryParameters = decodeQueryParameters(m.group(7), inputEncoding);
anchor = m.group(9);
}
return of(inputEncoding, DEFAULT_ENCODING, protocol, hostName, port, path, queryParameters, anchor);
}
#location 24
#vulnerability type NULL_DEREFERENCE |
#fixed code
public static ClassName get(Class<?> clazz) {
checkNotNull(clazz, "clazz == null");
checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName");
checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName");
checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName");
String anonymousSuffix = "";
while (clazz.isAnonymousClass()) {
int lastDollar = clazz.getName().lastIndexOf('$');
anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix;
clazz = clazz.getEnclosingClass();
}
String name = clazz.getSimpleName() + anonymousSuffix;
if (clazz.getEnclosingClass() == null) {
// Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295
int lastDot = clazz.getName().lastIndexOf('.');
String packageName = (lastDot != -1) ? clazz.getName().substring(0, lastDot) : NO_PACKAGE;
return new ClassName(packageName, null, name);
}
return ClassName.get(clazz.getEnclosingClass()).nestedClass(name);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static ClassName get(Class<?> clazz) {
checkNotNull(clazz, "clazz == null");
checkArgument(!clazz.isPrimitive(), "primitive types cannot be represented as a ClassName");
checkArgument(!void.class.equals(clazz), "'void' type cannot be represented as a ClassName");
checkArgument(!clazz.isArray(), "array types cannot be represented as a ClassName");
String anonymousSuffix = "";
while (clazz.isAnonymousClass()) {
int lastDollar = clazz.getName().lastIndexOf('$');
anonymousSuffix = clazz.getName().substring(lastDollar) + anonymousSuffix;
clazz = clazz.getEnclosingClass();
}
String name = clazz.getSimpleName() + anonymousSuffix;
if (clazz.getEnclosingClass() == null) {
// Avoid unreliable Class.getPackage(). https://github.com/square/javapoet/issues/295
int lastDot = clazz.getName().lastIndexOf('.');
String packageName = (lastDot != -1) ? clazz.getName().substring(0, lastDot) : null;
return new ClassName(packageName, null, name);
}
return ClassName.get(clazz.getEnclosingClass()).nestedClass(name);
}
#location 19
#vulnerability type NULL_DEREFERENCE |
#fixed code
@SuppressWarnings("unchecked")
private static Deserializer deserializer(File file, PoijiOptions options) {
final PoijiStream poiParser = new PoijiStream(file);
final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser);
return Deserializer.instance(workbook, options);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
private static Deserializer deserializer(File file, PoijiOptions options) throws FileNotFoundException {
final PoijiStream poiParser = new PoijiStream(fileInputStream(file));
final PoiWorkbook workbook = PoiWorkbook.workbook(Files.getExtension(file.getName()), poiParser);
return Deserializer.instance(workbook, options);
}
#location 4
#vulnerability type RESOURCE_LEAK |
#fixed code
private ZipInputStream prepareZipInputStream() throws ZipException {
try {
splitInputStream = new SplitInputStream(getZipModel().getZipFile(),
getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk());
FileHeader fileHeader = getFirstFileHeader(getZipModel());
if (fileHeader != null) {
splitInputStream.prepareExtractionForFileHeader(fileHeader);
}
return new ZipInputStream(splitInputStream, password);
} catch (IOException e) {
throw new ZipException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private ZipInputStream prepareZipInputStream() throws ZipException {
try {
SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(),
getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk());
FileHeader fileHeader = getFirstFileHeader(getZipModel());
if (fileHeader != null) {
splitInputStream.prepareExtractionForFileHeader(fileHeader);
}
return new ZipInputStream(splitInputStream, password);
} catch (IOException e) {
throw new ZipException(e);
}
}
#location 12
#vulnerability type RESOURCE_LEAK |
#fixed code
private ZipInputStream prepareZipInputStream() throws ZipException {
try {
splitInputStream = new SplitInputStream(getZipModel().getZipFile(),
getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk());
FileHeader fileHeader = getFirstFileHeader(getZipModel());
if (fileHeader != null) {
splitInputStream.prepareExtractionForFileHeader(fileHeader);
}
return new ZipInputStream(splitInputStream, password);
} catch (IOException e) {
throw new ZipException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private ZipInputStream prepareZipInputStream() throws ZipException {
try {
SplitInputStream splitInputStream = new SplitInputStream(getZipModel().getZipFile(),
getZipModel().isSplitArchive(), getZipModel().getEndOfCentralDirectoryRecord().getNumberOfThisDisk());
FileHeader fileHeader = getFirstFileHeader(getZipModel());
if (fileHeader != null) {
splitInputStream.prepareExtractionForFileHeader(fileHeader);
}
return new ZipInputStream(splitInputStream, password);
} catch (IOException e) {
throw new ZipException(e);
}
}
#location 12
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void bidiBackpressure() throws InterruptedException {
RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel);
Flowable<NumberProto.Number> rxRequest = Flowable
.fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator)
.doOnNext(i -> System.out.println(i + " --> "))
.doOnNext(i -> updateNumberOfWaits(clientLastValueTime, clientNbOfWaits))
.map(BackpressureIntegrationTest::protoNum);
TestSubscriber<NumberProto.Number> rxResponse = stub.twoWayPressure(rxRequest)
.doOnNext(n -> System.out.println(n.getNumber(0) + " <--"))
.doOnNext(n -> waitIfValuesAreEqual(n.getNumber(0), 3))
.test();
rxResponse.awaitTerminalEvent(5, TimeUnit.SECONDS);
rxResponse.assertComplete().assertValueCount(NUMBER_OF_STREAM_ELEMENTS);
assertThat(clientNbOfWaits.get()).isEqualTo(1);
assertThat(serverNumberOfWaits.get()).isEqualTo(1);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void bidiBackpressure() throws InterruptedException {
Object lock = new Object();
BackpressureDetector clientReqBPDetector = new BackpressureDetector(madMultipleCutoff);
BackpressureDetector clientRespBPDetector = new BackpressureDetector(madMultipleCutoff);
RxNumbersGrpc.RxNumbersStub stub = RxNumbersGrpc.newRxStub(channel);
Flowable<NumberProto.Number> rxRequest = Flowable
.fromIterable(new Sequence(180, clientReqBPDetector))
.doOnNext(i -> System.out.println(i + " -->"))
.map(BackpressureIntegrationTest::protoNum);
Flowable<NumberProto.Number> rxResponse = stub.twoWayPressure(rxRequest);
rxResponse.subscribe(
n -> {
clientRespBPDetector.tick();
System.out.println(" " + n.getNumber(0) + " <--");
try { Thread.sleep(50); } catch (InterruptedException e) {}
},
t -> {
t.printStackTrace();
synchronized (lock) {
lock.notify();
}
},
() -> {
System.out.println("Client done.");
synchronized (lock) {
lock.notify();
}
});
synchronized (lock) {
lock.wait(TimeUnit.SECONDS.toMillis(20));
}
assertThat(clientReqBPDetector.backpressureDelayOcurred()).isTrue();
assertThat(serverRespBPDetector.backpressureDelayOcurred()).isTrue();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public void run() {
final Set<String> artifacts = new HashSet<>();
installNodeModules(artifacts);
final File base = new File(cwd, "node_modules");
final File libs = new File(base, ".lib");
if (force || libs.exists()) {
final double version = Double.parseDouble(System.getProperty("java.specification.version"));
final boolean isGraalVM =
System.getProperty("java.vm.name", "").toLowerCase().contains("graalvm") ||
// from graal 20.0.0 the vm name doesn't contain graalvm in the name
// but it is now part of the vendor version
System.getProperty("java.vendor.version", "").toLowerCase().contains("graalvm");
if (!isGraalVM) {
// not on graal, install graaljs and dependencies
warn("Installing GraalJS...");
// graaljs + dependencies
installGraalJS(artifacts);
if (version >= 11) {
// verify if the current JDK contains the jdk.internal.vm.ci module
try {
String modules = exec(javaHomePrefix() + "java", "--list-modules");
if (modules.contains("jdk.internal.vm.ci")) {
warn("Installing JVMCI Compiler...");
// jvmci compiler + dependencies
installGraalJMVCICompiler();
}
} catch (IOException | InterruptedException e) {
err(e.getMessage());
}
} else {
warn("Current JDK only supports GraalJS in Interpreted mode!");
}
}
}
// always create a launcher even if no dependencies are needed
createLauncher(artifacts);
// always install the es4x type definitions
installTypeDefinitions();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void run() {
final Set<String> artifacts = new HashSet<>();
installNodeModules(artifacts);
final File base = new File(cwd, "node_modules");
final File libs = new File(base, ".lib");
if (force || libs.exists()) {
final double version = Double.parseDouble(System.getProperty("java.specification.version"));
final String vm = System.getProperty("java.vm.name");
// from graal 20.0.0 the vm name doesn't contain graalvm in the name
// but it is now part of the vendor version
final String vendor = System.getProperty("java.vendor.version");
if (!vm.toLowerCase().contains("graalvm") && vendor != null && !vendor.toLowerCase().contains("graalvm")) {
// not on graal, install graaljs and dependencies
warn("Installing GraalJS...");
// graaljs + dependencies
installGraalJS(artifacts);
if (version >= 11) {
// verify if the current JDK contains the jdk.internal.vm.ci module
try {
String modules = exec(javaHomePrefix() + "java", "--list-modules");
if (modules.contains("jdk.internal.vm.ci")) {
warn("Installing JVMCI Compiler...");
// jvmci compiler + dependencies
installGraalJMVCICompiler();
}
} catch (IOException | InterruptedException e) {
err(e.getMessage());
}
} else {
warn("Current JDK only supports GraalJS in Interpreted mode!");
}
}
}
// always create a launcher even if no dependencies are needed
createLauncher(artifacts);
// always install the es4x type definitions
installTypeDefinitions();
}
#location 15
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void agentLoads() throws IOException, InterruptedException {
// If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually.
final String buildDirectory = (String) System.getProperties().get("buildDirectory");
final String finalName = (String) System.getProperties().get("finalName");
final int port = Integer.parseInt((String) System.getProperties().get("it.port"));
final String config = resolveRelativePathToResource("test.yml");
final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config;
final String java = buildJavaPath(System.getenv("JAVA_HOME"));
final Process app = new ProcessBuilder()
.command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication")
.start();
try {
// Wait for application to start
app.getInputStream().read();
InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream();
BufferedReader contents = new BufferedReader(new InputStreamReader(stream));
boolean found = false;
while (!found) {
String line = contents.readLine();
if (line == null) {
break;
}
if (line.contains("jmx_scrape_duration_seconds")) {
found = true;
}
}
assertThat("Expected metric not found", found);
// Tell application to stop
app.getOutputStream().write('\n');
try {
app.getOutputStream().flush();
} catch (IOException ignored) {
}
} finally {
final int exitcode = app.waitFor();
// Log any errors printed
int len;
byte[] buffer = new byte[100];
while ((len = app.getErrorStream().read(buffer)) != -1) {
System.out.write(buffer, 0, len);
}
assertThat("Application did not exit cleanly", exitcode == 0);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void agentLoads() throws IOException, InterruptedException {
// If not starting the testcase via Maven, set the buildDirectory and finalName system properties manually.
final String buildDirectory = (String) System.getProperties().get("buildDirectory");
final String finalName = (String) System.getProperties().get("finalName");
final int port = Integer.parseInt((String) System.getProperties().get("it.port"));
final String config = resolveRelativePathToResource("test.yml");
final String javaagent = "-javaagent:" + buildDirectory + "/" + finalName + ".jar=" + port + ":" + config;
final String javaHome = System.getenv("JAVA_HOME");
final String java;
if (javaHome != null && javaHome.equals("")) {
java = javaHome + "/bin/java";
} else {
java = "java";
}
final Process app = new ProcessBuilder()
.command(java, javaagent, "-cp", buildClasspath(), "io.prometheus.jmx.TestApplication")
.start();
try {
// Wait for application to start
app.getInputStream().read();
InputStream stream = new URL("http://localhost:" + port + "/metrics").openStream();
BufferedReader contents = new BufferedReader(new InputStreamReader(stream));
boolean found = false;
while (!found) {
String line = contents.readLine();
if (line == null) {
break;
}
if (line.contains("jmx_scrape_duration_seconds")) {
found = true;
}
}
assertThat("Expected metric not found", found);
// Tell application to stop
app.getOutputStream().write('\n');
try {
app.getOutputStream().flush();
} catch (IOException ignored) {
}
} finally {
final int exitcode = app.waitFor();
// Log any errors printed
int len;
byte[] buffer = new byte[100];
while ((len = app.getErrorStream().read(buffer)) != -1) {
System.out.write(buffer, 0, len);
}
assertThat("Application did not exit cleanly", exitcode == 0);
}
}
#location 28
#vulnerability type RESOURCE_LEAK |
#fixed code
public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception {
String[] args = agentArgument.split(":");
if (args.length < 2 || args.length > 3) {
System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>");
System.exit(1);
}
int port;
InetSocketAddress socket;
String file;
if (args.length == 3) {
port = Integer.parseInt(args[1]);
socket = new InetSocketAddress(args[0], port);
file = args[2];
} else {
port = Integer.parseInt(args[0]);
socket = new InetSocketAddress(port);
file = args[1];
}
new JmxCollector(new File(file)).register();
DefaultExports.initialize();
server = new Server();
QueuedThreadPool pool = new QueuedThreadPool();
pool.setDaemon(true);
pool.setMaxThreads(10);
pool.setMaxQueued(10);
pool.setName("jmx_exporter");
server.setThreadPool(pool);
SelectChannelConnector connector = new SelectChannelConnector();
connector.setHost(socket.getHostName());
connector.setPort(socket.getPort());
connector.setAcceptors(1);
server.addConnector(connector);
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
server.setHandler(context);
context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
server.start();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static void premain(String agentArgument, Instrumentation instrumentation) throws Exception {
String[] args = agentArgument.split(":");
if (args.length < 2 || args.length > 3) {
System.err.println("Usage: -javaagent:/path/to/JavaAgent.jar=[host:]<port>:<yaml configuration file>");
System.exit(1);
}
String host;
int port;
String file;
if (args.length == 3) {
port = Integer.parseInt(args[1]);
host = args[0];
file = args[2];
} else {
port = Integer.parseInt(args[0]);
host = "0.0.0.0";
file = args[1];
}
new JmxCollector(new File(file)).register();
DefaultExports.initialize();
QueuedThreadPool pool = new QueuedThreadPool();
pool.setDaemon(true);
pool.setMaxThreads(10);
pool.setName("jmx_exporter");
server = new Server(pool);
ServerConnector connector = new ServerConnector(server);
connector.setReuseAddress(true);
connector.setHost(host);
connector.setPort(port);
server.setConnectors(new Connector[]{connector});
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addFilter(GzipFilter.class, "/*", null);
server.setHandler(context);
context.addServlet(new ServletHolder(new MetricsServlet()), "/metrics");
server.start();
}
#location 35
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test
public void benchmark() throws InterruptedException {
Benchmark bench = new Benchmark();
// Hipster-Dijkstra
bench.add("Hipster-Dijkstra", new Algorithm() {
AStar<Point> it; Maze2D maze;
public void initialize(Maze2D maze) {
it= AlgorithmIteratorFromMazeCreator.astar(maze, false);
this.maze = maze;
}
public Result evaluate() {
return MazeSearch.executeIteratorSearch(it, maze);
}
});
// JUNG-Dijkstra
bench.add("JUNG-Dijkstra", new Algorithm() {
Maze2D maze;DirectedGraph<Point, JungEdge<Point>> graph;
public void initialize(Maze2D maze) {
this.maze = maze;
this.graph = JungDirectedGraphFromMazeCreator.create(maze);
}
public Result evaluate() {
return MazeSearch.executeJungSearch(graph, maze);
}
});
int index = 0;
for(String algName : bench.algorithms.keySet()){
System.out.println((++index) + " = " + algName);
}
for (int i = 10; i < 300; i += 10) {
Maze2D maze = Maze2D.empty(i);
// Test over an empty maze
Map<String, Benchmark.Score> results = bench.run(maze);
// Check results and print scores. We take JUNG as baseline
Benchmark.Score jungScore = results.get("JUNG-Dijkstra");
String scores = "";
for(String algName : bench.algorithms.keySet()){
Benchmark.Score score = results.get(algName);
assertEquals(jungScore.result.getCost(),score.result.getCost(), 0.0001);
scores += score.time + " ms\t";
}
System.out.println(scores);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void benchmark() throws InterruptedException {
System.out.println("Maze | Hipster-Dijkstra (ms) | JUNG-Dijkstra (ms)");
System.out.println("-------------------------------------------------");
final int times = 5;
for (int i = 10; i < 300; i += 10) {
Maze2D maze = Maze2D.random(i, 0.9);
// Repeat 5 times
//Double mean1 = 0d, mean2 = 0d;
double min2 = Double.MAX_VALUE, min1 = Double.MAX_VALUE;
DirectedGraph<Point, JungEdge<Point>> graph = JungDirectedGraphFromMazeCreator.create(maze);
for (int j = 0; j < times; j++) {
//AStar<Point> it = AStarIteratorFromMazeCreator.create(maze, false);
AStar<Point> it = AlgorithmIteratorFromMazeCreator.astar(maze, false);
Stopwatch w1 = new Stopwatch().start();
MazeSearch.Result resultJung = MazeSearch.executeJungSearch(graph, maze);
//In case there is no possible result in the random maze
if(resultJung.equals(MazeSearch.Result.NO_RESULT)){
maze = Maze2D.random(i, 0.9);
graph = JungDirectedGraphFromMazeCreator.create(maze);
j--;
continue;
}
long result1 = w1.stop().elapsed(TimeUnit.MILLISECONDS);
if (result1 < min1) {
min1 = result1;
}
Stopwatch w2 = new Stopwatch().start();
MazeSearch.Result resultIterator = MazeSearch.executeIteratorSearch(it, maze);
long result2 = w2.stop().elapsed(TimeUnit.MILLISECONDS);
if (result2 < min2) {
min2 = result2;
}
assertEquals(resultIterator.getCost(), resultJung.getCost(), 0.001);
}
System.out.println(String.format("%d \t\t %.5g \t\t %.5g", i, min2, min1));
}
}
#location 34
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testSimpleBookieLedgerMapping() throws Exception {
for (int i = 0; i < numberOfLedgers; i++) {
createAndAddEntriesToLedger().close();
}
BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer(
ledgerManager);
Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex
.getBookieToLedgerIndex();
assertEquals("Missed few bookies in the bookie-ledger mapping!", 3,
bookieToLedgerIndex.size());
Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values();
for (Set<Long> ledgers : bk2ledgerEntry) {
assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3,
ledgers.size());
for (Long ledgerId : ledgers) {
assertTrue("Unknown ledger-bookie mapping", ledgerList
.contains(ledgerId));
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testSimpleBookieLedgerMapping() throws Exception {
LedgerManagerFactory newLedgerManagerFactory = LedgerManagerFactory
.newLedgerManagerFactory(baseConf, zkc);
LedgerManager ledgerManager = newLedgerManagerFactory
.newLedgerManager();
List<Long> ledgerList = new ArrayList<Long>(3);
LedgerHandle lh = createAndAddEntriesToLedger();
lh.close();
ledgerList.add(lh.getId());
lh = createAndAddEntriesToLedger();
lh.close();
ledgerList.add(lh.getId());
lh = createAndAddEntriesToLedger();
lh.close();
ledgerList.add(lh.getId());
BookieLedgerIndexer bookieLedgerIndex = new BookieLedgerIndexer(
ledgerManager);
Map<String, Set<Long>> bookieToLedgerIndex = bookieLedgerIndex
.getBookieToLedgerIndex();
assertEquals("Missed few bookies in the bookie-ledger mapping!", 3,
bookieToLedgerIndex.size());
Collection<Set<Long>> bk2ledgerEntry = bookieToLedgerIndex.values();
for (Set<Long> ledgers : bk2ledgerEntry) {
assertEquals("Missed few ledgers in the bookie-ledger mapping!", 3,
ledgers.size());
for (Long ledgerId : ledgers) {
assertTrue("Unknown ledger-bookie mapping", ledgerList
.contains(ledgerId));
}
}
}
#location 25
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) {
SyncObj x = (SyncObj) ctx;
if (rc != 0) {
LOG.error("Failure during add {}", rc);
x.failureOccurred = true;
}
synchronized (x) {
x.value = true;
x.ls = seq;
x.notify();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) {
if (rc != 0)
fail("Failed to write entry");
ls = seq;
synchronized (sync) {
sync.value = true;
sync.notify();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected void callOnError(final ExecutionError error) {
if (onError != null) {
onError.call(error);
}
callOnTerminate((C) error.getContext());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void callOnError(final ExecutionError error) {
if (onError != null) {
onError.call(error);
}
synchronized (error.getContext()) {
callOnTerminate((C) error.getContext());
error.getContext().notifyAll();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
protected void callOnFinalState(final State<C> state, final C context) {
try {
if (onFinalStateHandler != null) {
if (isTrace())
log.debug("when final state {} for {} <<<", state, context);
onFinalStateHandler.call(state, context);
if (isTrace())
log.debug("when final state {} for {} >>>", state, context);
}
callOnTerminate(context);
} catch (Exception e) {
callOnError(new ExecutionError(state, null, e,
"Execution Error in [EasyFlow.whenFinalState] handler", context));
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void callOnFinalState(final State<C> state, final C context) {
try {
if (onFinalStateHandler != null) {
if (isTrace())
log.debug("when final state {} for {} <<<", state, context);
onFinalStateHandler.call(state, context);
if (isTrace())
log.debug("when final state {} for {} >>>", state, context);
}
synchronized (context) {
callOnTerminate(context);
context.notifyAll();
}
} catch (Exception e) {
callOnError(new ExecutionError(state, null, e,
"Execution Error in [EasyFlow.whenFinalState] handler", context));
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void startDb() {
postgres = new MyPostgreSQLContainer()
.withDatabaseName(TEST_SCHEMA_NAME)
.withUsername("SA")
.withPassword("pass")
.withLogConsumer(new Consumer<OutputFrame>() {
@Override
public void accept(OutputFrame outputFrame) {
logger.debug(outputFrame.getUtf8String());
}
});
postgres.start();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void startDb() {
postgres = (PostgreSQLContainer) new PostgreSQLContainer()
.withDatabaseName(TEST_SCHEMA_NAME)
.withUsername("SA")
.withPassword("pass")
.withLogConsumer(new Consumer<OutputFrame>() {
@Override
public void accept(OutputFrame outputFrame) {
logger.debug(outputFrame.getUtf8String());
}
});
postgres.start();
}
#location 3
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public void run()
{
while (this.running)
{
//input
while (!this.inputs.isEmpty())
{
DatagramPacket dp = this.inputs.remove();
KcpOnUdp ku = this.kcps.get(dp.sender());
if (ku == null)
{
ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化
ku.noDelay(nodelay, interval, resend, nc);
ku.wndSize(sndwnd, rcvwnd);
ku.setMtu(mtu);
ku.setTimeout(timeout);
this.kcps.put(dp.sender(), ku);
}
ku.input(dp.content());
}
//update
KcpOnUdp temp = null;
for (KcpOnUdp ku : this.kcps.values())
{
ku.update();
if (ku.isClosed())
{
temp = ku;
}
}
if (temp != null)//删掉过时的kcp
{
this.kcps.remove((InetSocketAddress) temp.getKcp().getUser());
}
try
{
Thread.sleep(this.interval);
} catch (InterruptedException ex)
{
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public void run()
{
while (this.running)
{
//input
while (!this.inputs.isEmpty())
{
DatagramPacket dp = this.inputs.remove();
KcpOnUdp ku = this.kcps.get(dp.sender());
if (ku == null)
{
ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化
ku.noDelay(nodelay, interval, resend, nc);
ku.wndSize(sndwnd, rcvwnd);
ku.setMtu(mtu);
ku.setTimeout(timeout);
this.kcps.put(dp.sender(), ku);
pqueue.add(ku);
}
ku.input(dp.content());
}
//选出第一个kcp更新状态
KcpOnUdp first = pqueue.poll();
if(first != null && first.getTimeout() < System.currentTimeMillis()) {
first.update();
if(!first.isClosed()) {
pqueue.add(first);
} else {
this.kcps.remove((InetSocketAddress) first.getKcp().getUser());
}
}
//每30s,更新一遍所有的kcp状态
if(System.currentTimeMillis()%(1000*30) == 0) {
//update
KcpOnUdp temp = null;
for (KcpOnUdp ku : this.kcps.values())
{
ku.update();
if (ku.isClosed()) {//删掉过时的kcp
this.kcps.remove((InetSocketAddress) temp.getKcp().getUser());
pqueue.remove(ku);
}
}
}
//等待
try {
synchronized(wakeup){
wakeup.wait(5*60*1000);
}
} catch (InterruptedException ex) {
Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public static Instances createBootstrapSample(Instances instances) {
Random rand = Random.getInstance();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < instances.size(); i++) {
int idx = rand.nextInt(instances.size());
map.put(idx, map.getOrDefault(idx, 0) + 1);
}
Instances bag = new Instances(instances.getAttributes(), instances.getTargetAttribute(), map.size());
for (Integer idx : map.keySet()) {
int weight = map.get(idx);
Instance instance = instances.get(idx).clone();
instance.setWeight(weight);
bag.add(instance);
}
return bag;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static Instances createBootstrapSample(Instances instances) {
Random rand = Random.getInstance();
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < instances.size(); i++) {
int idx = rand.nextInt(instances.size());
if (!map.containsKey(idx)) {
map.put(idx, 0);
}
map.put(idx, map.get(idx) + 1);
}
Instances bag = new Instances(instances.getAttributes(), instances.getTargetAttribute(), map.size());
for (Integer idx : map.keySet()) {
int weight = map.get(idx);
Instance instance = instances.get(idx).clone();
instance.setWeight(weight);
bag.add(instance);
}
return bag;
}
#location 9
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void commit(Transaction transaction) throws RollbackException, TransactionException {
if (LOG.isTraceEnabled()) {
LOG.trace("commit " + transaction);
}
if (transaction.getStatus() != Status.RUNNING) {
throw new IllegalArgumentException("Transaction has already been " + transaction.getStatus());
}
// Check rollbackOnly status
if (transaction.isRollbackOnly()) {
rollback(transaction);
throw new RollbackException();
}
// Flush all pending writes
if (!flushTables(transaction)) {
cleanup(transaction);
throw new RollbackException();
}
SyncCommitCallback cb = new SyncCommitCallback();
TimerContext commitTimer = tsoclient.getMetrics().startTimer(Timers.COMMIT);
try {
tsoclient.commit(transaction.getStartTimestamp(), transaction.getRows(), cb);
cb.await();
} catch (Exception e) {
throw new TransactionException("Could not commit", e);
} finally {
commitTimer.stop();
}
if (cb.getException() != null) {
throw new TransactionException("Error committing", cb.getException());
}
if (LOG.isTraceEnabled()) {
LOG.trace("doneCommit " + transaction.getStartTimestamp() + " TS_c: " + cb.getCommitTimestamp()
+ " Success: " + (cb.getResult() == TSOClient.Result.OK));
}
if (cb.getResult() == TSOClient.Result.ABORTED) {
cleanup(transaction);
throw new RollbackException();
}
transaction.setStatus(Status.COMMITTED);
transaction.setCommitTimestamp(cb.getCommitTimestamp());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void commit(Transaction transaction) throws RollbackException, TransactionException {
if (LOG.isTraceEnabled()) {
LOG.trace("commit " + transaction);
}
// Check rollbackOnly status
if (transaction.isRollbackOnly()) {
rollback(transaction);
throw new RollbackException();
}
// Flush all pending writes
if (!flushTables(transaction)) {
cleanup(transaction);
throw new RollbackException();
}
SyncCommitCallback cb = new SyncCommitCallback();
TimerContext commitTimer = tsoclient.getMetrics().startTimer(Timers.COMMIT);
try {
tsoclient.commit(transaction.getStartTimestamp(), transaction.getRows(), cb);
cb.await();
} catch (Exception e) {
throw new TransactionException("Could not commit", e);
} finally {
commitTimer.stop();
}
if (cb.getException() != null) {
throw new TransactionException("Error committing", cb.getException());
}
if (LOG.isTraceEnabled()) {
LOG.trace("doneCommit " + transaction.getStartTimestamp() + " TS_c: " + cb.getCommitTimestamp()
+ " Success: " + (cb.getResult() == TSOClient.Result.OK));
}
if (cb.getResult() == TSOClient.Result.ABORTED) {
cleanup(transaction);
throw new RollbackException();
}
transaction.setCommitTimestamp(cb.getCommitTimestamp());
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void runTestWriteWriteConflict() throws Exception {
TransactionManager tm = new TransactionManager(hbaseConf);
TTable tt = new TTable(hbaseConf, TEST_TABLE);
TransactionState t1 = tm.beginTransaction();
LOG.info("Transaction created " + t1);
TransactionState t2 = tm.beginTransaction();
LOG.info("Transaction created" + t2);
byte[] row = Bytes.toBytes("test-simple");
byte[] fam = Bytes.toBytes(TEST_FAMILY);
byte[] col = Bytes.toBytes("testdata");
byte[] data1 = Bytes.toBytes("testWrite-1");
byte[] data2 = Bytes.toBytes("testWrite-2");
Put p = new Put(row);
p.add(fam, col, data1);
tt.put(t1, p);
Put p2 = new Put(row);
p2.add(fam, col, data2);
tt.put(t2, p2);
tm.tryCommit(t2);
boolean aborted = false;
try {
tm.tryCommit(t1);
assertTrue("Transaction commited successfully", false);
} catch (CommitUnsuccessfulException e) {
aborted = true;
}
assertTrue("Transaction didn't raise exception", aborted);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void runTestWriteWriteConflict() throws Exception {
TransactionManager tm = new TransactionManager(hbaseConf);
TransactionalTable tt = new TransactionalTable(hbaseConf, TEST_TABLE);
TransactionState t1 = tm.beginTransaction();
LOG.info("Transaction created " + t1);
TransactionState t2 = tm.beginTransaction();
LOG.info("Transaction created" + t2);
byte[] row = Bytes.toBytes("test-simple");
byte[] fam = Bytes.toBytes(TEST_FAMILY);
byte[] col = Bytes.toBytes("testdata");
byte[] data1 = Bytes.toBytes("testWrite-1");
byte[] data2 = Bytes.toBytes("testWrite-2");
Put p = new Put(row);
p.add(fam, col, data1);
tt.put(t1, p);
Put p2 = new Put(row);
p2.add(fam, col, data2);
tt.put(t2, p2);
tm.tryCommit(t2);
boolean aborted = false;
try {
tm.tryCommit(t1);
assertTrue("Transaction commited successfully", false);
} catch (CommitUnsuccessfulException e) {
aborted = true;
}
assertTrue("Transaction didn't raise exception", aborted);
}
#location 24
#vulnerability type RESOURCE_LEAK |
#fixed code
@Test(timeOut = 30_000)
public void runTestInterleaveScanWhenATransactionAborts() throws Exception {
TransactionManager tm = newTransactionManager();
TTable tt = new TTable(hbaseConf, TEST_TABLE);
Transaction t1 = tm.begin();
LOG.info("Transaction created " + t1);
byte[] fam = Bytes.toBytes(TEST_FAMILY);
byte[] col = Bytes.toBytes("testdata");
byte[] data1 = Bytes.toBytes("testWrite-1");
byte[] data2 = Bytes.toBytes("testWrite-2");
byte[] startrow = Bytes.toBytes("test-scan" + 0);
byte[] stoprow = Bytes.toBytes("test-scan" + 9);
byte[] modrow = Bytes.toBytes("test-scan" + 3);
for (int i = 0; i < 10; i++) {
byte[] row = Bytes.toBytes("test-scan" + i);
Put p = new Put(row);
p.add(fam, col, data1);
tt.put(t1, p);
}
tm.commit(t1);
Transaction t2 = tm.begin();
Put p = new Put(modrow);
p.add(fam, col, data2);
tt.put(t2, p);
int modifiedrows = 0;
ResultScanner rs = tt.getScanner(t2, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col));
Result r = rs.next();
while (r != null) {
if (Bytes.equals(data2, r.getValue(fam, col))) {
if (LOG.isTraceEnabled()) {
LOG.trace("Modified :" + Bytes.toString(r.getRow()));
}
modifiedrows++;
}
r = rs.next();
}
assertTrue(modifiedrows == 1, "Expected 1 row modified, but " + modifiedrows + " are.");
tm.rollback(t2);
Transaction tscan = tm.begin();
rs = tt.getScanner(tscan, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col));
r = rs.next();
while (r != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Scan1 :" + Bytes.toString(r.getRow()) + " => " + Bytes.toString(r.getValue(fam, col)));
}
assertTrue(Bytes.equals(data1, r.getValue(fam, col)),
"Unexpected value for SI scan " + tscan + ": " + Bytes.toString(r.getValue(fam, col)));
r = rs.next();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test(timeOut = 30_000)
public void runTestInterleaveScanWhenATransactionAborts() throws Exception {
TransactionManager tm = newTransactionManager();
TTable tt = new TTable(hbaseConf, TEST_TABLE);
Transaction t1 = tm.begin();
LOG.info("Transaction created " + t1);
byte[] fam = Bytes.toBytes(TEST_FAMILY);
byte[] col = Bytes.toBytes("testdata");
byte[] data1 = Bytes.toBytes("testWrite-1");
byte[] data2 = Bytes.toBytes("testWrite-2");
byte[] startrow = Bytes.toBytes("test-scan" + 0);
byte[] stoprow = Bytes.toBytes("test-scan" + 9);
byte[] modrow = Bytes.toBytes("test-scan" + 3);
for (int i = 0; i < 10; i++) {
byte[] row = Bytes.toBytes("test-scan" + i);
Put p = new Put(row);
p.add(fam, col, data1);
tt.put(t1, p);
}
tm.commit(t1);
Transaction t2 = tm.begin();
Put p = new Put(modrow);
p.add(fam, col, data2);
tt.put(t2, p);
int modifiedrows = 0;
ResultScanner rs = tt.getScanner(t2, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col));
Result r = rs.next();
while (r != null) {
if (Bytes.equals(data2, r.getValue(fam, col))) {
if (LOG.isTraceEnabled()) {
LOG.trace("Modified :" + Bytes.toString(r.getRow()));
}
modifiedrows++;
}
r = rs.next();
}
assertTrue(modifiedrows == 1, "Expected 1 row modified, but " + modifiedrows + " are.");
tm.rollback(t2);
Transaction tscan = tm.begin();
rs = tt.getScanner(tscan, new Scan().setStartRow(startrow).setStopRow(stoprow).addColumn(fam, col));
r = rs.next();
while (r != null) {
if (LOG.isTraceEnabled()) {
LOG.trace("Scan1 :" + Bytes.toString(r.getRow()) + " => " + Bytes.toString(r.getValue(fam, col)));
}
assertTrue(Bytes.equals(data1, r.getValue(fam, col)),
"Unexpected value for SI scan " + tscan + ": " + Bytes.toString(r.getValue(fam, col)));
r = rs.next();
}
}
#location 46
#vulnerability type RESOURCE_LEAK |
#fixed code
public byte[] getChannelConfigurationBytes() throws TransactionException {
try {
final Block configBlock = getConfigBlock(getRandomPeer());
Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0));
Payload payload = Payload.parseFrom(envelopeRet.getPayload());
ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData());
return configEnvelope.getConfig().toByteArray();
} catch (Exception e) {
throw new TransactionException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public byte[] getChannelConfigurationBytes() throws TransactionException {
try {
final Block configBlock = getConfigurationBlock();
Envelope envelopeRet = Envelope.parseFrom(configBlock.getData().getData(0));
Payload payload = Payload.parseFrom(envelopeRet.getPayload());
ConfigEnvelope configEnvelope = ConfigEnvelope.parseFrom(payload.getData());
return configEnvelope.getConfig().toByteArray();
} catch (Exception e) {
throw new TransactionException(e);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
Orderer(String name, String url, Properties properties) throws InvalidArgumentException {
if (StringUtil.isNullOrEmpty(name)) {
throw new InvalidArgumentException("Invalid name for orderer");
}
Exception e = checkGrpcUrl(url);
if (e != null) {
throw new InvalidArgumentException(e);
}
this.name = name;
this.url = url;
this.properties = properties == null ? null : (Properties) properties.clone(); //keep our own copy.
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
DeliverResponse[] sendDeliver(Common.Envelope transaction) throws TransactionException {
if (shutdown) {
throw new TransactionException(format("Orderer %s was shutdown.", name));
}
OrdererClient localOrdererClient = ordererClient;
logger.debug(format("Order.sendDeliver name: %s, url: %s", name, url));
if (localOrdererClient == null || !localOrdererClient.isChannelActive()) {
localOrdererClient = new OrdererClient(this, new Endpoint(url, properties).getChannelBuilder());
ordererClient = localOrdererClient;
}
try {
return localOrdererClient.sendDeliver(transaction);
} catch (Throwable t) {
ordererClient = null;
throw t;
}
}
#location 17
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testGetInfo() throws Exception {
if (testConfig.isRunningAgainstFabric10()) {
HFCAInfo info = client.info();
assertNull(info.getVersion());
}
if (!testConfig.isRunningAgainstFabric10()) {
HFCAInfo info = client.info();
assertNotNull("client.info returned null.", info);
String version = info.getVersion();
assertNotNull("client.info.getVersion returned null.", version);
assertTrue(format("Version '%s' didn't match expected pattern", version), version.matches("^\\d+\\.\\d+\\.\\d+($|-.*)"));
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testGetInfo() throws Exception {
if (testConfig.isRunningAgainstFabric10()) {
HFCAInfo info = client.info();
assertNull(info.getVersion());
}
if (!testConfig.isRunningAgainstFabric10()) {
HFCAInfo info = client.info();
assertTrue(info.getVersion().contains("1.1.0"));
}
}
#location 11
#vulnerability type NULL_DEREFERENCE |
#fixed code
boolean hasConnected() {
return connected;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
void setProperties(Properties properties) {
this.properties = properties;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
private static final Collection<MapArea> createAreasForSimpleMultipolygon(OsmRelation relation,
TLongObjectMap<MapNode> nodeIdMap, OsmEntityProvider db) throws EntityNotFoundException {
assert isSimpleMultipolygon(relation, db);
OsmEntity tagSource = null;
List<MapNode> outerNodes = null;
List<List<MapNode>> holes = new ArrayList<List<MapNode>>();
for (OsmRelationMember member : membersAsList(relation)) {
if (member.getType() == EntityType.Way) {
OsmWay way = db.getWay(member.getId());
if ("inner".equals(member.getRole())) {
List<MapNode> hole = new ArrayList<MapNode>(way.getNumberOfNodes());
for (long nodeId : nodesAsList(way).toArray()) {
hole.add(nodeIdMap.get(nodeId));
}
holes.add(hole);
} else if ("outer".equals(member.getRole())) {
tagSource = relation.getNumberOfTags() > 1 ? relation : way;
outerNodes = new ArrayList<MapNode>(way.getNumberOfNodes());
for (long nodeId : nodesAsList(way).toArray()) {
outerNodes.add(nodeIdMap.get(nodeId));
}
}
}
}
return singleton(new MapArea(tagSource.getId(), tagSource instanceof OsmRelation,
OSMToMapDataConverter.tagsOfEntity(tagSource), outerNodes, holes));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private static final Collection<MapArea> createAreasForSimpleMultipolygon(OsmRelation relation,
TLongObjectMap<MapNode> nodeIdMap, OsmEntityProvider db) throws EntityNotFoundException {
assert isSimpleMultipolygon(relation, db);
OsmEntity tagSource = null;
List<MapNode> outerNodes = null;
List<List<MapNode>> holes = new ArrayList<List<MapNode>>();
for (OsmRelationMember member : membersAsList(relation)) {
if (member.getType() == EntityType.Way) {
OsmWay way = db.getWay(member.getId());
if ("inner".equals(member.getRole())) {
List<MapNode> hole = new ArrayList<MapNode>(way.getNumberOfNodes());
for (long nodeId : nodesAsList(way).toArray()) {
hole.add(nodeIdMap.get(nodeId));
}
holes.add(hole);
} else if ("outer".equals(member.getRole())) {
tagSource = relation.getNumberOfTags() > 1 ? relation : way;
outerNodes = new ArrayList<MapNode>(way.getNumberOfNodes());
for (long nodeId : nodesAsList(way).toArray()) {
outerNodes.add(nodeIdMap.get(nodeId));
}
}
}
}
return singleton(new MapArea(tagSource, outerNodes, holes));
}
#location 39
#vulnerability type NULL_DEREFERENCE |
#fixed code
public static final boolean isJOSMGenerated(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
for (int i=0; i<100; i++) {
String line = reader.readLine();
if (line != null) {
if (line.contains("generator='JOSM'")) {
reader.close();
return true;
}
}
}
reader.close();
} catch (IOException e) { }
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public static final boolean isJOSMGenerated(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
for (int i=0; i<100; i++) {
String line = reader.readLine();
if (line != null) {
if (line.contains("generator='JOSM'")) {
return true;
}
}
}
reader.close();
} catch (IOException e) { }
return false;
}
#location 11
#vulnerability type RESOURCE_LEAK |
#fixed code
public void write(RtpPacket packet, RTPFormat format) {
try {
LOCK.lock();
// checking format
if (format == null) {
logger.warn("No format specified. Packet dropped!");
return;
}
if (this.format == null || this.format.getID() != format.getID()) {
this.format = format;
logger.info("Format has been changed: " + this.format.toString());
}
// if this is first packet then synchronize clock
if (isn == -1) {
rtpClock.synchronize(packet.getTimestamp());
isn = packet.getSeqNumber();
initJitter(packet);
} else {
estimateJitter(packet);
}
// update clock rate
rtpClock.setClockRate(this.format.getClockRate());
// drop outstanding packets
// packet is outstanding if its timestamp of arrived packet is less
// then consumer media time
if (packet.getTimestamp() < this.arrivalDeadLine) {
logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString());
dropCount++;
// checking if not dropping too much
droppedInRaw++;
if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) {
arrivalDeadLine = 0;
} else {
return;
}
}
Frame f = Memory.allocate(packet.getPayloadLength());
// put packet into buffer irrespective of its sequence number
f.setHeader(null);
f.setSequenceNumber(packet.getSeqNumber());
// here time is in milliseconds
f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp()));
f.setOffset(0);
f.setLength(packet.getPayloadLength());
packet.getPayload(f.getData(), 0);
// set format
f.setFormat(this.format.getFormat());
// make checks only if have packet
if (f != null) {
droppedInRaw = 0;
// find correct position to insert a packet
// use timestamp since its always positive
int currIndex = queue.size() - 1;
while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) {
currIndex--;
}
// check for duplicate packet
if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) {
LOCK.unlock();
return;
}
queue.add(currIndex + 1, f);
// recalculate duration of each frame in queue and overall duration
// since we could insert the frame in the middle of the queue
duration = 0;
if (queue.size() > 1) {
duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp();
}
for (int i = 0; i < queue.size() - 1; i++) {
// duration measured by wall clock
long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp();
// in case of RFC2833 event timestamp remains same
queue.get(i).setDuration(d > 0 ? d : 0);
}
// if overall duration is negative we have some mess here,try to
// reset
if (duration < 0 && queue.size() > 1) {
logger.warn("Something messy happened. Reseting jitter buffer!");
reset();
return;
}
// overflow?
// only now remove packet if overflow , possibly the same packet we just received
if (queue.size() > QUEUE_SIZE) {
logger.warn("Buffer overflow!");
dropCount++;
queue.remove(0).recycle();
}
// check if this buffer already full
if (!ready) {
ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1);
if (ready && listener != null) {
listener.onFill();
}
}
}
} finally {
LOCK.unlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void write(RtpPacket packet, RTPFormat format) {
// checking format
if (format == null) {
logger.warn("No format specified. Packet dropped!");
return;
}
if (this.format == null || this.format.getID() != format.getID()) {
this.format = format;
logger.info("Format has been changed: " + this.format.toString());
}
// if this is first packet then synchronize clock
if (isn == -1) {
rtpClock.synchronize(packet.getTimestamp());
isn = packet.getSeqNumber();
initJitter(packet);
} else {
estimateJitter(packet);
}
// update clock rate
rtpClock.setClockRate(this.format.getClockRate());
// drop outstanding packets
// packet is outstanding if its timestamp of arrived packet is less
// then consumer media time
if (packet.getTimestamp() < this.arrivalDeadLine) {
logger.warn("drop packet: dead line=" + arrivalDeadLine + ", packet time=" + packet.getTimestamp() + ", seq=" + packet.getSeqNumber() + ", payload length=" + packet.getPayloadLength() + ", format=" + this.format.toString());
dropCount++;
// checking if not dropping too much
droppedInRaw++;
if (droppedInRaw == QUEUE_SIZE / 2 || queue.size() == 0) {
arrivalDeadLine = 0;
} else {
return;
}
}
Frame f = Memory.allocate(packet.getPayloadLength());
// put packet into buffer irrespective of its sequence number
f.setHeader(null);
f.setSequenceNumber(packet.getSeqNumber());
// here time is in milliseconds
f.setTimestamp(rtpClock.convertToAbsoluteTime(packet.getTimestamp()));
f.setOffset(0);
f.setLength(packet.getPayloadLength());
packet.getPayload(f.getData(), 0);
// set format
f.setFormat(this.format.getFormat());
// make checks only if have packet
if (f != null) {
LOCK.lock();
droppedInRaw = 0;
// find correct position to insert a packet
// use timestamp since its always positive
int currIndex = queue.size() - 1;
while (currIndex >= 0 && queue.get(currIndex).getTimestamp() > f.getTimestamp()) {
currIndex--;
}
// check for duplicate packet
if (currIndex >= 0 && queue.get(currIndex).getSequenceNumber() == f.getSequenceNumber()) {
LOCK.unlock();
return;
}
queue.add(currIndex + 1, f);
// recalculate duration of each frame in queue and overall duration
// since we could insert the frame in the middle of the queue
duration = 0;
if (queue.size() > 1) {
duration = queue.get(queue.size() - 1).getTimestamp() - queue.get(0).getTimestamp();
}
for (int i = 0; i < queue.size() - 1; i++) {
// duration measured by wall clock
long d = queue.get(i + 1).getTimestamp() - queue.get(i).getTimestamp();
// in case of RFC2833 event timestamp remains same
queue.get(i).setDuration(d > 0 ? d : 0);
}
// if overall duration is negative we have some mess here,try to
// reset
if (duration < 0 && queue.size() > 1) {
logger.warn("Something messy happened. Reseting jitter buffer!");
reset();
LOCK.unlock();
return;
}
// overflow?
// only now remove packet if overflow , possibly the same packet we just received
if (queue.size() > QUEUE_SIZE) {
logger.warn("Buffer overflow!");
dropCount++;
queue.remove(0).recycle();
}
LOCK.unlock();
// check if this buffer already full
if (!ready) {
ready = !useBuffer || (duration >= jitterBufferSize && queue.size() > 1);
if (ready && listener != null) {
listener.onFill();
}
}
}
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void finishSpan() {
Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span
finished.startTick = 500000L; // set in start span
state.setCurrentLocalSpan(finished);
PowerMockito.when(System.nanoTime()).thenReturn(1000000L);
localTracer.finishSpan();
verify(mockReporter).report(finished.toZipkin());
verifyNoMoreInteractions(mockReporter);
assertEquals(500L, finished.getDuration().longValue());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void finishSpan() {
Span finished = new Span().setTimestamp(1000L); // set in start span
finished.startTick = 500000L; // set in start span
state.setCurrentLocalSpan(finished);
PowerMockito.when(System.nanoTime()).thenReturn(1000000L);
localTracer.finishSpan();
verify(mockCollector).collect(finished);
verifyNoMoreInteractions(mockCollector);
assertEquals(500L, finished.getDuration().longValue());
}
#location 14
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
protected void reloadPage() {
synchronized (this) {
selectedSort = null;
sortFieldLeft = null;
super.reloadPage();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
protected void reloadPage() {
selectedSort = null;
sortFieldLeft = null;
super.reloadPage();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void getStartingWith(String queryString, Field field, String start,
int limit, List<NamedItem> list) throws ParseException,
IOException, SyntaxError, URISyntaxException,
ClassNotFoundException, InterruptedException, SearchLibException,
InstantiationException, IllegalAccessException {
SearchRequest searchRequest = urlDbClient.getNewSearchRequest(field
+ "Facet");
searchRequest.setQueryString(queryString);
searchRequest.getFilterList().add(field + ":" + start + "*",
Source.REQUEST);
getFacetLimit(field, searchRequest, limit, list);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void getStartingWith(String queryString, Field field, String start,
int limit, List<NamedItem> list) throws ParseException,
IOException, SyntaxError, URISyntaxException,
ClassNotFoundException, InterruptedException, SearchLibException,
InstantiationException, IllegalAccessException {
SearchRequest searchRequest = client.getNewSearchRequest(field
+ "Facet");
searchRequest.setQueryString(queryString);
searchRequest.getFilterList().add(field + ":" + start + "*",
Source.REQUEST);
getFacetLimit(field, searchRequest, limit, list);
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Override
public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) {
StringBuilder sql = new StringBuilder(2000);
// this statement computes the mean value
AnalyticSelectStatementRewriter meanRewriter = new AnalyticSelectStatementRewriter(vc, queryString);
meanRewriter.setDepth(depth+1);
meanRewriter.setIndentLevel(defaultIndent + 6);
String mainSql = meanRewriter.visit(ctx);
cumulativeReplacedTableSources.putAll(meanRewriter.getCumulativeSampleTables());
// this statement computes the standard deviation
BootstrapSelectStatementRewriter varianceRewriter = new BootstrapSelectStatementRewriter(vc, queryString);
varianceRewriter.setDepth(depth+1);
varianceRewriter.setIndentLevel(defaultIndent + 6);
String subSql = varianceRewriter.varianceComputationStatement(ctx);
String leftAlias = genAlias();
String rightAlias = genAlias();
// we combine those two statements using join.
List<Pair<String, String>> thisColumnName2Aliases = new ArrayList<Pair<String, String>>();
List<Pair<String, String>> leftColName2Aliases = meanRewriter.getColName2Aliases();
// List<Boolean> leftAggColIndicator = meanRewriter.getAggregateColumnIndicator();
List<Pair<String, String>> rightColName2Aliases = varianceRewriter.getColName2Aliases();
// List<Boolean> rightAggColIndicator = varianceRewriter.getAggregateColumnIndicator();
sql.append(String.format("%sSELECT", indentString));
int leftSelectElemIndex = 0;
int totalSelectElemIndex = 0;
for (Pair<String, String> colName2Alias : leftColName2Aliases) {
leftSelectElemIndex++;
if (leftSelectElemIndex == 1) sql.append(" ");
else sql.append(", ");
if (meanRewriter.isAggregateColumn(leftSelectElemIndex)) {
// mean
totalSelectElemIndex++;
String alias = genAlias();
sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), alias));
thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias));
// error (standard deviation * 1.96 (for 95% confidence interval))
totalSelectElemIndex++;
alias = genAlias();
String matchingAliasName = null;
for (Pair<String, String> r : rightColName2Aliases) {
if (colName2Alias.getLeft().equals(r.getLeft())) {
matchingAliasName = r.getRight();
}
}
sql.append(String.format(", %s.%s AS %s", rightAlias, matchingAliasName, alias));
thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias));
meanColIndex2ErrColIndex.put(totalSelectElemIndex-1, totalSelectElemIndex);
} else {
totalSelectElemIndex++;
sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), colName2Alias.getRight()));
thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), colName2Alias.getRight()));
}
}
colName2Aliases = thisColumnName2Aliases;
sql.append(String.format("\n%sFROM (\n", indentString));
sql.append(mainSql);
sql.append(String.format("\n%s ) AS %s", indentString, leftAlias));
sql.append(" LEFT JOIN (\n");
sql.append(subSql);
sql.append(String.format("%s) AS %s", indentString, rightAlias));
sql.append(String.format(" ON %s.l_shipmode = %s.l_shipmode", leftAlias, rightAlias));
return sql.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) {
List<Pair<String, String>> subqueryColName2Aliases = null;
BootstrapSelectStatementRewriter singleRewriter = null;
StringBuilder unionedFrom = new StringBuilder(2000);
int trialNum = vc.getConf().getInt("bootstrap_trial_num");
for (int i = 0; i < trialNum; i++) {
singleRewriter = new BootstrapSelectStatementRewriter(vc, queryString);
singleRewriter.setIndentLevel(2);
singleRewriter.setDepth(1);
String singleTrialQuery = singleRewriter.visitQuery_specificationForSingleTrial(ctx);
if (i == 0) {
subqueryColName2Aliases = singleRewriter.getColName2Aliases();
}
if (i > 0) unionedFrom.append("\n UNION\n");
unionedFrom.append(singleTrialQuery);
}
StringBuilder sql = new StringBuilder(2000);
sql.append("SELECT");
int selectElemIndex = 0;
for (Pair<String, String> e : subqueryColName2Aliases) {
selectElemIndex++;
sql.append((selectElemIndex > 1)? ", " : " ");
if (singleRewriter.isAggregateColumn(selectElemIndex)) {
String alias = genAlias();
sql.append(String.format("AVG(%s) AS %s",
e.getRight(), alias));
colName2Aliases.add(Pair.of(e.getLeft(), alias));
} else {
if (e.getLeft().equals(e.getRight())) sql.append(e.getLeft());
else sql.append(String.format("%s AS %s", e.getLeft(), e.getRight()));
colName2Aliases.add(Pair.of(e.getLeft(), e.getRight()));
}
}
sql.append("\nFROM (\n");
sql.append(unionedFrom.toString());
sql.append("\n) AS t");
sql.append("\nGROUP BY");
for (int colIndex = 1; colIndex <= subqueryColName2Aliases.size(); colIndex++) {
if (!singleRewriter.isAggregateColumn(colIndex)) {
if (colIndex > 1) {
sql.append(String.format(", %s", subqueryColName2Aliases.get(colIndex-1).getRight()));
} else {
sql.append(String.format(" %s", subqueryColName2Aliases.get(colIndex-1).getRight()));
}
}
}
return sql.toString();
}
#location 23
#vulnerability type NULL_DEREFERENCE |
#fixed code
private boolean stopUsingMysqldadmin() {
boolean retValue = false;
Reader stdOut = null;
Reader stdErr = null;
LogFileProcessor processor = null;
Set<String> successPatterns = Sets.newHashSet(
"'Can't connect to MySQL server on 'localhost'",
Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete");
try {
String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString();
Process p = Runtime.getRuntime().exec(new String[] {
cmd, "--no-defaults", "--protocol=tcp",
String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME),
"shutdown"});
retValue = p.waitFor() == 0;
OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor(
successPatterns,
Sets.newHashSet("[ERROR]"),
StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput()));
processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch);
stdOut = new InputStreamReader(p.getInputStream());
stdErr = new InputStreamReader(p.getErrorStream());
if (retValue) {
outputWatch.waitForResult(getConfig().getTimeout());
if (!outputWatch.isInitWithSuccess()) {
logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound());
retValue = false;
}
} else {
logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr));
}
} catch (InterruptedException e) {
logger.warn("Encountered error why shutting down process.", e);
} catch (IOException e) {
logger.warn("Encountered error why shutting down process.", e);
} finally {
closeCloseables(stdOut, stdErr);
if (processor != null) processor.shutdown();
}
return retValue;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private boolean stopUsingMysqldadmin() {
boolean retValue = false;
Reader stdOut = null;
Reader stdErr = null;
LogFileProcessor processor = null;
Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'");
try {
Process p;
if (Platform.detect() == Platform.Windows) {
String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString();
successPatterns.add("mysqld.exe: Shutdown complete");
p = Runtime.getRuntime().exec(new String[] {
cmd, "--no-defaults", "--protocol=tcp",
String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME),
"shutdown"});
} else {
String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString();
successPatterns.add("mysqld: Shutdown complete");
p = Runtime.getRuntime().exec(new String[] {
cmd, "--no-defaults", "--protocol=tcp",
String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME),
//String.format("--socket=%s", sockFile(getExecutable().executable)),
"shutdown"});
}
retValue = p.waitFor() == 0;
OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor(
successPatterns,
Sets.newHashSet("[ERROR]"),
StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput()));
processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch);
stdOut = new InputStreamReader(p.getInputStream());
stdErr = new InputStreamReader(p.getErrorStream());
if (retValue) {
outputWatch.waitForResult(getConfig().getTimeout());
if (!outputWatch.isInitWithSuccess()) {
logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound());
retValue = false;
}
} else {
logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr));
}
} catch (InterruptedException e) {
logger.warn("Encountered error why shutting down process.", e);
} catch (IOException e) {
logger.warn("Encountered error why shutting down process.", e);
} finally {
closeCloseable(stdOut);
closeCloseable(stdErr);
if (processor != null) processor.shutdown();
}
return retValue;
}
#location 59
#vulnerability type RESOURCE_LEAK |
#fixed code
public <T> MappingIterator<T> readValues(File src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(
_dataFormatReaders.findFormat(_inputStream(src)), false);
}
return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src)));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public <T> MappingIterator<T> readValues(File src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(
_dataFormatReaders.findFormat(_inputStream(src)), false);
}
return _bindAndReadValues(considerFilter(_parserFactory.createParser(src)));
}
#location 8
#vulnerability type RESOURCE_LEAK |
#fixed code
@Override
public String idFromValue(Object value)
{
return idFromClass(value.getClass());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public String idFromValue(Object value)
{
Class<?> cls = _typeFactory.constructType(value.getClass()).getRawClass();
final String key = cls.getName();
String name;
synchronized (_typeToId) {
name = _typeToId.get(key);
if (name == null) {
// 24-Feb-2011, tatu: As per [JACKSON-498], may need to dynamically look up name
// can either throw an exception, or use default name...
if (_config.isAnnotationProcessingEnabled()) {
BeanDescription beanDesc = _config.introspectClassAnnotations(cls);
name = _config.getAnnotationIntrospector().findTypeName(beanDesc.getClassInfo());
}
if (name == null) {
// And if still not found, let's choose default?
name = _defaultTypeId(cls);
}
_typeToId.put(key, name);
}
}
return name;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
public void testAtomicInt() throws Exception
{
AtomicInteger value = MAPPER.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testAtomicInt() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicInteger value = mapper.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
}
#location 5
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testVideosSitemap() throws UnknownFormatException, IOException {
SiteMapParser parser = new SiteMapParser();
parser.enableExtension(Extension.VIDEO);
String contentType = "text/xml";
byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml");
URL url = new URL("http://www.example.com/sitemap-video.xml");
AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url);
assertEquals(false, asm.isIndex());
assertEquals(true, asm instanceof SiteMap);
SiteMap sm = (SiteMap) asm;
assertEquals(2, sm.getSiteMapUrls().size());
Iterator<SiteMapURL> siter = sm.getSiteMapUrls().iterator();
// first <loc> element: nearly all video attributes
VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer",
"Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123"));
expectedVideoAttributes.setDuration(600);
ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00");
expectedVideoAttributes.setExpirationDate(dt);
dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00");
expectedVideoAttributes.setPublicationDate(dt);
expectedVideoAttributes.setRating(4.2f);
expectedVideoAttributes.setViewCount(12345);
expectedVideoAttributes.setFamilyFriendly(true);
expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" });
expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" });
expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com"));
expectedVideoAttributes.setGalleryTitle("Cooking Videos");
expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) });
expectedVideoAttributes.setRequiresSubscription(true);
expectedVideoAttributes.setUploader("GrillyMcGrillerson");
expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson"));
expectedVideoAttributes.setLive(false);
VideoAttributes attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0];
assertNotNull(attr);
assertEquals(expectedVideoAttributes, attr);
// locale-specific number format in <video:price>, test #220
expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123-2.jpg"), "Grilling steaks for summer, episode 2",
"Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123-2.flv"), null);
expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", null, VideoAttributes.VideoPriceType.own) });
attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0];
assertNotNull(attr);
assertEquals(expectedVideoAttributes, attr);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testVideosSitemap() throws UnknownFormatException, IOException {
SiteMapParser parser = new SiteMapParser();
parser.enableExtension(Extension.VIDEO);
String contentType = "text/xml";
byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml");
URL url = new URL("http://www.example.com/sitemap-video.xml");
AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url);
assertEquals(false, asm.isIndex());
assertEquals(true, asm instanceof SiteMap);
SiteMap sm = (SiteMap) asm;
assertEquals(1, sm.getSiteMapUrls().size());
VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer",
"Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123"));
expectedVideoAttributes.setDuration(600);
ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00");
expectedVideoAttributes.setExpirationDate(dt);
dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00");
expectedVideoAttributes.setPublicationDate(dt);
expectedVideoAttributes.setRating(4.2f);
expectedVideoAttributes.setViewCount(12345);
expectedVideoAttributes.setFamilyFriendly(true);
expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" });
expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" });
expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com"));
expectedVideoAttributes.setGalleryTitle("Cooking Videos");
expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) });
expectedVideoAttributes.setRequiresSubscription(true);
expectedVideoAttributes.setUploader("GrillyMcGrillerson");
expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson"));
expectedVideoAttributes.setLive(false);
for (SiteMapURL su : sm.getSiteMapUrls()) {
assertNotNull(su.getAttributesForExtension(Extension.VIDEO));
VideoAttributes attr = (VideoAttributes) su.getAttributesForExtension(Extension.VIDEO)[0];
assertEquals(expectedVideoAttributes, attr);
}
}
#location 37
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void moderator_should_approve_question_information() throws Exception {
Information approvedInfo = new QuestionInformation("edited title", "edited desc",
new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment");
moderator.approve(myQuestion, approvedInfo);
assertEquals(approvedInfo, myQuestion.getInformation());
assertTrue(myQuestion.getInformation().isModerated());
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void moderator_should_approve_question_information() throws Exception {
Question question = question("question title", "question description", author);
Information approvedInfo = new QuestionInformation("edited title", "edited desc",
new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment");
moderator.approve(question, approvedInfo);
assertEquals(approvedInfo, question.getInformation());
assertTrue(question.getInformation().isModerated());
}
#location 10
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Override
public SyndFeedInfo remove(final URL url) {
SyndFeedInfo info = null;
final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(fileName);
ois = new ObjectInputStream(fis);
info = (SyndFeedInfo) ois.readObject();
final File file = new File(fileName);
if (file.exists()) {
file.delete();
}
} catch (final FileNotFoundException fnfe) {
// That's OK, we'l return null
} catch (final ClassNotFoundException cnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", cnfe);
} catch (final IOException fnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", fnfe);
} finally {
if (fis != null) {
try {
fis.close();
} catch (final IOException e) {
}
}
if (ois != null) {
try {
ois.close();
} catch (final IOException e) {
}
}
}
return info;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Override
public SyndFeedInfo remove(final URL url) {
SyndFeedInfo info = null;
final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim();
FileInputStream fis;
try {
fis = new FileInputStream(fileName);
final ObjectInputStream ois = new ObjectInputStream(fis);
info = (SyndFeedInfo) ois.readObject();
fis.close();
final File file = new File(fileName);
if (file.exists()) {
file.delete();
}
} catch (final FileNotFoundException fnfe) {
// That's OK, we'l return null
} catch (final ClassNotFoundException cnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", cnfe);
} catch (final IOException fnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", fnfe);
}
return info;
}
#location 16
#vulnerability type RESOURCE_LEAK |
#fixed code
public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
xmlReader.close();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
}
#location 9
#vulnerability type RESOURCE_LEAK |
#fixed code
protected void testRawBomValid(final String encoding) throws Exception {
final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding);
final XmlReader xmlReader = new XmlReader(is, false);
if (!encoding.equals("UTF-16")) {
assertEquals(xmlReader.getEncoding(), encoding);
} else {
assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding);
}
xmlReader.close();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void testRawBomValid(final String encoding) throws Exception {
final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding);
final XmlReader xmlReader = new XmlReader(is, false);
if (!encoding.equals("UTF-16")) {
assertEquals(xmlReader.getEncoding(), encoding);
} else {
assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding);
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
#fixed code
static String load(File in, String charsetName) throws IOException {
InputStream inStream = new FileInputStream(in);
String data = readInputStream(inStream, charsetName);
inStream.close();
return data;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
static String load(File in, String charsetName) throws IOException {
char[] buffer = new char[0x20000]; // ~ 130K
StringBuilder data = new StringBuilder(0x20000);
InputStream inStream = new FileInputStream(in);
Reader inReader = new InputStreamReader(inStream, charsetName);
int read;
do {
read = inReader.read(buffer, 0, buffer.length);
if (read > 0) {
data.append(buffer, 0, read);
}
} while (read >= 0);
return data.toString();
}
#location 5
#vulnerability type RESOURCE_LEAK |
#fixed code
protected void addChildren(int index, Node... children) {
Validate.notNull(children);
if (children.length == 0) {
return;
}
final List<Node> nodes = ensureChildNodes();
// fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace
final Node firstParent = children[0].parent();
if (firstParent != null && firstParent.childNodeSize() == children.length) {
boolean sameList = true;
final List<Node> firstParentNodes = firstParent.childNodes();
// identity check contents to see if same
int i = children.length;
while (i-- > 0) {
if (children[i] != firstParentNodes.get(i)) {
sameList = false;
break;
}
}
firstParent.empty();
nodes.addAll(index, Arrays.asList(children));
i = children.length;
while (i-- > 0) {
children[i].parentNode = this;
}
reindexChildren(index);
return;
}
Validate.noNullElements(children);
for (Node child : children) {
reparentChild(child);
}
nodes.addAll(index, Arrays.asList(children));
reindexChildren(index);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
protected void addChildren(int index, Node... children) {
Validate.noNullElements(children);
final List<Node> nodes = ensureChildNodes();
for (Node child : children) {
reparentChild(child);
}
nodes.addAll(index, Arrays.asList(children));
reindexChildren(index);
}
#location 6
#vulnerability type NULL_DEREFERENCE |
#fixed code
private static String ihVal(String key, Document doc) {
final Element first = doc.select("th:contains(" + key + ") + td").first();
return first != null ? first.text() : null;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private static String ihVal(String key, Document doc) {
return doc.select("th:contains(" + key + ") + td").first().text();
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void transactionObject(final String trytes) {
if (StringUtils.isEmpty(trytes)) {
log.warn("Warning: empty trytes in input for transactionObject");
return;
}
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes.charAt(i) != '9') {
log.warn("Trytes {} does not seem a valid tryte", trytes);
return;
}
}
int[] transactionTrits = Converter.trits(trytes);
int[] hash = new int[243];
ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81);
// generate the correct transaction hash
curl.reset();
curl.absorb(transactionTrits, 0, transactionTrits.length);
curl.squeeze(hash, 0, hash.length);
this.setHash(Converter.trytes(hash));
this.setSignatureFragments(trytes.substring(0, 2187));
this.setAddress(trytes.substring(2187, 2268));
this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837)));
this.setObsoleteTag(trytes.substring(2295, 2322));
this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993)));
this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020)));
this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047)));
this.setBundle(trytes.substring(2349, 2430));
this.setTrunkTransaction(trytes.substring(2430, 2511));
this.setBranchTransaction(trytes.substring(2511, 2592));
this.setTag(trytes.substring(2592, 2619));
this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000);
this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911)));
this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938)));
this.setNonce(trytes.substring(2646, 2673));
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void transactionObject(final String trytes) {
if (StringUtils.isEmpty(trytes)) {
log.warn("Warning: empty trytes in input for transactionObject");
return;
}
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes.charAt(i) != '9') {
log.warn("Trytes {} does not seem a valid tryte", trytes);
return;
}
}
int[] transactionTrits = Converter.trits(trytes);
int[] hash = new int[243];
ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL);
// generate the correct transaction hash
curl.reset();
curl.absorb(transactionTrits, 0, transactionTrits.length);
curl.squeeze(hash, 0, hash.length);
this.setHash(Converter.trytes(hash));
this.setSignatureFragments(trytes.substring(0, 2187));
this.setAddress(trytes.substring(2187, 2268));
this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837)));
this.setTag(trytes.substring(2295, 2322));
this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993)));
this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020)));
this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047)));
this.setBundle(trytes.substring(2349, 2430));
this.setTrunkTransaction(trytes.substring(2430, 2511));
this.setBranchTransaction(trytes.substring(2511, 2592));
this.setNonce(trytes.substring(2592, 2673));
}
#location 21
#vulnerability type NULL_DEREFERENCE |
#fixed code
@SuppressWarnings({"unchecked", "rawtypes"})
public void onReceive(ServiceContext serviceContext) throws Throwable {
FlowMessage fm = serviceContext.getFlowMessage();
if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) {
syncActors.putIfAbsent(serviceContext.getId(), getSender());
}
// TODO 没有必要设置默认值,下面执行异常就会抛出异常
Object result = null;// DefaultMessage.getMessage();// set default
try {
this.service = ServiceFactory.getService(serviceName);
result = ((Service) service).process(fm.getMessage(), serviceContext);
} catch (Throwable e) {
Web web = serviceContext.getWeb();
if (web != null) {
web.complete();
}
throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e);
}
logger.info("同步处理 : {}, hasChild : {}", serviceContext.isSync(), hasChildActor());
if (serviceContext.isSync() && !hasChildActor()) {
logger.info("返回响应 {}", result);
ActorRef actor = syncActors.get(serviceContext.getId());
if(actor !=null) {
actor.tell(result, getSelf());
syncActors.remove(serviceContext.getId());
}
return;
}
Web web = serviceContext.getWeb();
if (service instanceof Complete) {
// FlowContext.removeServiceContext(fm.getTransactionId());
}
if (web != null) {
if (service instanceof Flush) {
web.flush();
}
if (service instanceof HttpComplete || service instanceof Complete) {
web.complete();
}
}
if (result == null)// for joint service
return;
if (hasChildActor()) {
for (RefType refType : nextServiceActors) {
ServiceContext context = serviceContext.newInstance();
context.getFlowMessage().setMessage(result);
// if (refType.isJoint()) {
// FlowMessage flowMessage1 = CloneUtil.clone(fm);
// flowMessage1.setMessage(result);
// context.setFlowMessage(flowMessage1);
// }
// condition fork for one-service to multi-service
if (refType.getMessageType().isInstance(result)) {
if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String)
|| stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) {
refType.getActorRef().tell(context, getSelf());
}
}
}
} else {
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings({"unchecked", "rawtypes"})
public void onReceive(ServiceContext serviceContext) throws Throwable {
FlowMessage fm = serviceContext.getFlowMessage();
if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) {
syncActors.putIfAbsent(serviceContext.getId(), getSender());
}
// TODO 没有必要设置默认值,下面执行异常就会抛出异常
Object result = null;// DefaultMessage.getMessage();// set default
try {
this.service = ServiceFactory.getService(serviceName);
result = ((Service) service).process(fm.getMessage(), serviceContext);
} catch (Throwable e) {
Web web = serviceContext.getWeb();
if (web != null) {
web.complete();
}
throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e);
}
if (serviceContext.isSync() && !hasChildActor()) {
syncActors.get(serviceContext.getId()).tell(result, getSelf());
syncActors.remove(serviceContext.getId());
return;
}
Web web = serviceContext.getWeb();
if (service instanceof Complete) {
// FlowContext.removeServiceContext(fm.getTransactionId());
}
if (web != null) {
if (service instanceof Flush) {
web.flush();
}
if (service instanceof HttpComplete || service instanceof Complete) {
web.complete();
}
}
if (result == null)// for joint service
return;
if (hasChildActor()) {
for (RefType refType : nextServiceActors) {
ServiceContext context = serviceContext.newInstance();
context.getFlowMessage().setMessage(result);
// if (refType.isJoint()) {
// FlowMessage flowMessage1 = CloneUtil.clone(fm);
// flowMessage1.setMessage(result);
// context.setFlowMessage(flowMessage1);
// }
// condition fork for one-service to multi-service
if (refType.getMessageType().isInstance(result)) {
if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String)
|| stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) {
refType.getActorRef().tell(context, getSelf());
}
}
}
} else {
}
}
#location 45
#vulnerability type NULL_DEREFERENCE |
#fixed code
FunctionTypeBuilder(String fnName, AbstractCompiler compiler,
Node errorRoot, String sourceName, Scope scope) {
Preconditions.checkNotNull(errorRoot);
this.fnName = fnName == null ? "" : fnName;
this.codingConvention = compiler.getCodingConvention();
this.typeRegistry = compiler.getTypeRegistry();
this.errorRoot = errorRoot;
this.sourceName = sourceName;
this.compiler = compiler;
this.scope = scope;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
FunctionTypeBuilder inferThisType(JSDocInfo info,
@Nullable Node owner) {
ObjectType maybeThisType = null;
if (info != null && info.hasThisType()) {
maybeThisType = ObjectType.cast(
info.getThisType().evaluate(scope, typeRegistry));
}
if (maybeThisType != null) {
thisType = maybeThisType;
thisType.setValidator(new ThisTypeValidator());
} else if (owner != null &&
(info == null || !info.hasType())) {
// If the function is of the form:
// x.prototype.y = function() {}
// then we can assume "x" is the @this type. On the other hand,
// if it's of the form:
// /** @type {Function} */ x.prototype.y;
// then we should not give it a @this type.
String ownerTypeName = owner.getQualifiedName();
ObjectType ownerType = ObjectType.cast(
typeRegistry.getForgivingType(
scope, ownerTypeName, sourceName,
owner.getLineno(), owner.getCharno()));
if (ownerType != null) {
thisType = ownerType;
}
}
return this;
}
#location 21
#vulnerability type NULL_DEREFERENCE |
#fixed code
private void createPropertyScopeFor(Symbol s) {
// In order to build a property scope for s, we will need to build
// a property scope for all its implicit prototypes first. This means
// that sometimes we will already have built its property scope
// for a previous symbol.
if (s.propertyScope != null) {
return;
}
SymbolScope parentPropertyScope = null;
ObjectType type = s.getType() == null ? null : s.getType().toObjectType();
if (type == null) {
return;
}
ObjectType proto = type.getParentScope();
if (proto != null && proto != type && proto.getConstructor() != null) {
Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor());
if (parentSymbol != null) {
createPropertyScopeFor(parentSymbol);
parentPropertyScope = parentSymbol.getPropertyScope();
}
}
ObjectType instanceType = type;
Iterable<String> propNames = type.getOwnPropertyNames();
if (instanceType.isFunctionPrototypeType()) {
// Merge the properties of "Foo.prototype" and "new Foo()" together.
instanceType = instanceType.getOwnerFunction().getInstanceType();
Set<String> set = Sets.newHashSet(propNames);
Iterables.addAll(set, instanceType.getOwnPropertyNames());
propNames = set;
}
s.setPropertyScope(new SymbolScope(null, parentPropertyScope, type, s));
for (String propName : propNames) {
StaticSlot<JSType> newProp = instanceType.getSlot(propName);
if (newProp.getDeclaration() == null) {
// Skip properties without declarations. We won't know how to index
// them, because we index things by node.
continue;
}
// We have symbol tables that do not do type analysis. They just try
// to build a complete index of all objects in the program. So we might
// already have symbols for things like "Foo.bar". If this happens,
// throw out the old symbol and use the type-based symbol.
Symbol oldProp = getScope(s).getSlot(s.getName() + "." + propName);
if (oldProp != null) {
removeSymbol(oldProp);
}
Symbol newSym = copySymbolTo(newProp, s.propertyScope);
if (oldProp != null) {
if (newSym.getJSDocInfo() == null) {
newSym.setJSDocInfo(oldProp.getJSDocInfo());
}
newSym.setPropertyScope(oldProp.propertyScope);
for (Reference ref : oldProp.references.values()) {
newSym.defineReferenceAt(ref.getNode());
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private void createPropertyScopeFor(Symbol s) {
// In order to build a property scope for s, we will need to build
// a property scope for all its implicit prototypes first. This means
// that sometimes we will already have built its property scope
// for a previous symbol.
if (s.propertyScope != null) {
return;
}
SymbolScope parentPropertyScope = null;
ObjectType type = s.getType().toObjectType();
ObjectType proto = type.getParentScope();
if (proto != null && proto != type && proto.getConstructor() != null) {
Symbol parentSymbol = getSymbolForInstancesOf(proto.getConstructor());
if (parentSymbol != null) {
createPropertyScopeFor(parentSymbol);
parentPropertyScope = parentSymbol.getPropertyScope();
}
}
ObjectType instanceType = type;
Iterable<String> propNames = type.getOwnPropertyNames();
if (instanceType.isFunctionPrototypeType()) {
// Merge the properties of "Foo.prototype" and "new Foo()" together.
instanceType = instanceType.getOwnerFunction().getInstanceType();
Set<String> set = Sets.newHashSet(propNames);
Iterables.addAll(set, instanceType.getOwnPropertyNames());
propNames = set;
}
s.propertyScope = new SymbolScope(null, parentPropertyScope, type);
for (String propName : propNames) {
StaticSlot<JSType> newProp = instanceType.getSlot(propName);
if (newProp.getDeclaration() == null) {
// Skip properties without declarations. We won't know how to index
// them, because we index things by node.
continue;
}
// We have symbol tables that do not do type analysis. They just try
// to build a complete index of all objects in the program. So we might
// already have symbols for things like "Foo.bar". If this happens,
// throw out the old symbol and use the type-based symbol.
Symbol oldProp = getScope(s).getSlot(s.getName() + "." + propName);
if (oldProp != null) {
removeSymbol(oldProp);
}
Symbol newSym = copySymbolTo(newProp, s.propertyScope);
if (oldProp != null) {
if (newSym.getJSDocInfo() == null) {
newSym.setJSDocInfo(oldProp.getJSDocInfo());
}
newSym.propertyScope = oldProp.propertyScope;
for (Reference ref : oldProp.references.values()) {
newSym.defineReferenceAt(ref.getNode());
}
}
}
}
#location 12
#vulnerability type NULL_DEREFERENCE |
#fixed code
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getType()) {
case Token.ASSIGN:
scope = traverseAssign(n, scope);
break;
case Token.NAME:
scope = traverseName(n, scope);
break;
case Token.GETPROP:
scope = traverseGetProp(n, scope);
break;
case Token.AND:
scope = traverseAnd(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.OR:
scope = traverseOr(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.HOOK:
scope = traverseHook(n, scope);
break;
case Token.OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case Token.CALL:
scope = traverseCall(n, scope);
break;
case Token.NEW:
scope = traverseNew(n, scope);
break;
case Token.ASSIGN_ADD:
case Token.ADD:
scope = traverseAdd(n, scope);
break;
case Token.POS:
case Token.NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case Token.THIS:
n.setJSType(scope.getTypeOfThis());
break;
case Token.ASSIGN_LSH:
case Token.ASSIGN_RSH:
case Token.LSH:
case Token.RSH:
case Token.ASSIGN_URSH:
case Token.URSH:
case Token.ASSIGN_DIV:
case Token.ASSIGN_MOD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_MUL:
case Token.ASSIGN_SUB:
case Token.DIV:
case Token.MOD:
case Token.BITAND:
case Token.BITXOR:
case Token.BITOR:
case Token.MUL:
case Token.SUB:
case Token.DEC:
case Token.INC:
case Token.BITNOT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.PARAM_LIST:
scope = traverse(n.getFirstChild(), scope);
n.setJSType(getJSType(n.getFirstChild()));
break;
case Token.COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case Token.TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case Token.DELPROP:
case Token.LT:
case Token.LE:
case Token.GT:
case Token.GE:
case Token.NOT:
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.INSTANCEOF:
case Token.IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case Token.GETELEM:
scope = traverseGetElem(n, scope);
break;
case Token.EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
ensurePropertyDeclared(n.getFirstChild());
}
break;
case Token.SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case Token.RETURN:
scope = traverseReturn(n, scope);
break;
case Token.VAR:
case Token.THROW:
scope = traverseChildren(n, scope);
break;
case Token.CATCH:
scope = traverseCatch(n, scope);
break;
case Token.CAST:
scope = traverseChildren(n, scope);
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasType()) {
n.setJSType(info.getType().evaluate(syntacticScope, registry));
}
break;
}
return scope;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private FlowScope traverse(Node n, FlowScope scope) {
switch (n.getType()) {
case Token.ASSIGN:
scope = traverseAssign(n, scope);
break;
case Token.NAME:
scope = traverseName(n, scope);
break;
case Token.GETPROP:
scope = traverseGetProp(n, scope);
break;
case Token.AND:
scope = traverseAnd(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.OR:
scope = traverseOr(n, scope).getJoinedFlowScope()
.createChildFlowScope();
break;
case Token.HOOK:
scope = traverseHook(n, scope);
break;
case Token.OBJECTLIT:
scope = traverseObjectLiteral(n, scope);
break;
case Token.CALL:
scope = traverseCall(n, scope);
break;
case Token.NEW:
scope = traverseNew(n, scope);
break;
case Token.ASSIGN_ADD:
case Token.ADD:
scope = traverseAdd(n, scope);
break;
case Token.POS:
case Token.NEG:
scope = traverse(n.getFirstChild(), scope); // Find types.
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.ARRAYLIT:
scope = traverseArrayLiteral(n, scope);
break;
case Token.THIS:
n.setJSType(scope.getTypeOfThis());
break;
case Token.ASSIGN_LSH:
case Token.ASSIGN_RSH:
case Token.LSH:
case Token.RSH:
case Token.ASSIGN_URSH:
case Token.URSH:
case Token.ASSIGN_DIV:
case Token.ASSIGN_MOD:
case Token.ASSIGN_BITAND:
case Token.ASSIGN_BITXOR:
case Token.ASSIGN_BITOR:
case Token.ASSIGN_MUL:
case Token.ASSIGN_SUB:
case Token.DIV:
case Token.MOD:
case Token.BITAND:
case Token.BITXOR:
case Token.BITOR:
case Token.MUL:
case Token.SUB:
case Token.DEC:
case Token.INC:
case Token.BITNOT:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(NUMBER_TYPE));
break;
case Token.PARAM_LIST:
scope = traverse(n.getFirstChild(), scope);
n.setJSType(getJSType(n.getFirstChild()));
break;
case Token.COMMA:
scope = traverseChildren(n, scope);
n.setJSType(getJSType(n.getLastChild()));
break;
case Token.TYPEOF:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(STRING_TYPE));
break;
case Token.DELPROP:
case Token.LT:
case Token.LE:
case Token.GT:
case Token.GE:
case Token.NOT:
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.INSTANCEOF:
case Token.IN:
scope = traverseChildren(n, scope);
n.setJSType(getNativeType(BOOLEAN_TYPE));
break;
case Token.GETELEM:
scope = traverseGetElem(n, scope);
break;
case Token.EXPR_RESULT:
scope = traverseChildren(n, scope);
if (n.getFirstChild().isGetProp()) {
ensurePropertyDeclared(n.getFirstChild());
}
break;
case Token.SWITCH:
scope = traverse(n.getFirstChild(), scope);
break;
case Token.RETURN:
scope = traverseReturn(n, scope);
break;
case Token.VAR:
case Token.THROW:
scope = traverseChildren(n, scope);
break;
case Token.CATCH:
scope = traverseCatch(n, scope);
break;
case Token.CAST:
scope = traverseChildren(n, scope);
break;
}
// TODO(johnlenz): remove this after the CAST node change has shaken out.
if (!n.isFunction()) {
JSDocInfo info = n.getJSDocInfo();
if (info != null && info.hasType()) {
JSType castType = info.getType().evaluate(syntacticScope, registry);
// A stubbed type declaration on a qualified name should take
// effect for all subsequent accesses of that name,
// so treat it the same as an assign to that name.
if (n.isQualifiedName() &&
n.getParent().isExprResult()) {
updateScopeForTypeChange(scope, n, n.getJSType(), castType);
}
n.setJSType(castType);
}
}
return scope;
}
#location 155
#vulnerability type NULL_DEREFERENCE |
#fixed code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
null, safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private Node inlineReturnValue(Node callNode, Node fnNode) {
Node block = fnNode.getLastChild();
Node callParentNode = callNode.getParent();
// NOTE: As the normalize pass guarantees globals aren't being
// shadowed and an expression can't introduce new names, there is
// no need to check for conflicts.
// Create an argName -> expression map, checking for side effects.
Map<String, Node> argMap =
FunctionArgumentInjector.getFunctionCallParameterMap(
fnNode, callNode, this.safeNameIdSupplier);
Node newExpression;
if (!block.hasChildren()) {
Node srcLocation = block;
newExpression = NodeUtil.newUndefinedNode(srcLocation);
} else {
Node returnNode = block.getFirstChild();
Preconditions.checkArgument(returnNode.getType() == Token.RETURN);
// Clone the return node first.
Node safeReturnNode = returnNode.cloneTree();
Node inlineResult = FunctionArgumentInjector.inject(
safeReturnNode, null, argMap);
Preconditions.checkArgument(safeReturnNode == inlineResult);
newExpression = safeReturnNode.removeFirstChild();
}
callParentNode.replaceChild(callNode, newExpression);
return newExpression;
}
#location 30
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void setSqlSource(MappedStatement ms) {
MapperTemplate mapperTemplate = getMapperTemplate(ms.getId());
try {
if (mapperTemplate != null) {
mapperTemplate.setSqlSource(ms);
}
} catch (Exception e) {
throw new RuntimeException("调用方法异常:" + e.getMessage());
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void setSqlSource(MappedStatement ms) {
MapperTemplate mapperTemplate = getMapperTemplate(ms.getId());
try {
mapperTemplate.setSqlSource(ms);
} catch (Exception e) {
throw new RuntimeException("调用方法异常:" + e.getMessage());
}
}
#location 4
#vulnerability type NULL_DEREFERENCE |
#fixed code
public boolean isIterableMapping() {
return getSingleSourceParameter().getType().isIterableType() && getResultType().isIterableType();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean isIterableMapping() {
return getSingleSourceType().isIterableType() && resultType.isIterableType();
}
#location 2
#vulnerability type NULL_DEREFERENCE |
#fixed code
private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) {
List<Method> methods = new ArrayList<Method>();
MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null;
for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) {
Method method = getMethod( element, executable, implementationRequired );
if ( method != null ) {
methods.add( method );
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( implementationRequired ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
(TypeElement) ( (DeclaredType) usedMapper ).asElement(),
false
)
);
}
}
return methods;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) {
List<Method> methods = new ArrayList<Method>();
MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null;
//TODO Extract to separate method
for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) {
Parameter parameter = executables.retrieveParameter( method );
Type returnType = executables.retrieveReturnType( method );
boolean mappingErroneous = false;
if ( implementationRequired ) {
if ( parameter.getType().isIterableType() && !returnType.isIterableType() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method from iterable type to non-iterable type.",
method
);
mappingErroneous = true;
}
if ( !parameter.getType().isIterableType() && returnType.isIterableType() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method from non-iterable type to iterable type.",
method
);
mappingErroneous = true;
}
if ( parameter.getType().isPrimitive() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method with primitive parameter type.",
method
);
mappingErroneous = true;
}
if ( returnType.isPrimitive() ) {
printMessage(
ReportingPolicy.ERROR,
"Can't generate mapping method with primitive return type.",
method
);
mappingErroneous = true;
}
if ( mappingErroneous ) {
continue;
}
}
//add method with property mappings if an implementation needs to be generated
if ( implementationRequired ) {
methods.add(
Method.forMethodRequiringImplementation(
method,
parameter.getName(),
parameter.getType(),
returnType,
getMappings( method )
)
);
}
//otherwise add reference to existing mapper method
else {
methods.add(
Method.forReferencedMethod(
typeUtil.getType( typeUtils.getDeclaredType( element ) ),
method,
parameter.getName(),
parameter.getType(),
returnType
)
);
}
}
//Add all methods of used mappers in order to reference them in the aggregated model
if ( implementationRequired ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
(TypeElement) ( (DeclaredType) usedMapper ).asElement(),
false
)
);
}
}
return methods;
}
#location 57
#vulnerability type NULL_DEREFERENCE |
#fixed code
public boolean matches() {
// check & collect generic types.
List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters();
if ( candidateParameters.size() != 1 ) {
typesMatch = false;
}
else {
TypeMatcher parameterMatcher = new TypeMatcher();
typesMatch = parameterMatcher.visit(
candidateParameters.iterator().next().asType(),
parameter.getTypeMirror()
);
}
// check return type
if ( typesMatch ) {
TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType();
TypeMatcher returnTypeMatcher = new TypeMatcher();
typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() );
}
// check if all type parameters are indeed mapped
if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) {
typesMatch = false;
}
else {
// check if all entries are in the bounds
for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) {
if (!isWithinBounds( entry.getValue(), getTypeParamFromCandidate( entry.getKey() ) ) ) {
// checks if the found Type is in bounds of the TypeParameters bounds.
typesMatch = false;
}
}
}
return typesMatch;
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public boolean matches() {
// check & collect generic types.
List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters();
if ( candidateParameters.size() == parameters.length ) {
for ( int i = 0; i < parameters.length; i++ ) {
TypeMatcher parameterMatcher = new TypeMatcher();
typesMatch = parameterMatcher.visit( candidateParameters.get( i ).asType(),
parameters[i].getTypeMirror() );
if ( !typesMatch ) {
break;
}
}
}
else {
typesMatch = false;
}
// check return type
if ( typesMatch ) {
TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType();
TypeMatcher returnTypeMatcher = new TypeMatcher();
typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() );
}
// check if all type parameters are indeed mapped
if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) {
typesMatch = false;
}
else {
// check if all entries are in the bounds
for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) {
if (!isWithinBounds( entry.getValue(), getTypeParamFromCandite( entry.getKey() ) ) ) {
// checks if the found Type is in bounds of the TypeParameters bounds.
typesMatch = false;
}
}
}
return typesMatch;
}
#location 33
#vulnerability type NULL_DEREFERENCE |
#fixed code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index);
try {
return new ArrayBuffer(buffer.getBackingStore());
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toTypedArray(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) {
int valueType = array.getType(index);
switch (valueType) {
case V8Value.INTEGER:
return array.getInteger(index);
case V8Value.DOUBLE:
return array.getDouble(index);
case V8Value.BOOLEAN:
return array.getBoolean(index);
case V8Value.STRING:
return array.getString(index);
case V8Value.V8_FUNCTION:
return IGNORE;
case V8Value.V8_ARRAY_BUFFER:
V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index);
try {
return buffer.getBackingStore();
} finally {
buffer.release();
}
case V8Value.V8_TYPED_ARRAY:
V8Array typedArray = array.getArray(index);
try {
return toTypedArray(typedArray);
} finally {
if (typedArray instanceof V8Array) {
typedArray.release();
}
}
case V8Value.V8_ARRAY:
V8Array arrayValue = array.getArray(index);
try {
return toList(arrayValue, cache);
} finally {
if (arrayValue instanceof V8Array) {
arrayValue.release();
}
}
case V8Value.V8_OBJECT:
V8Object objectValue = array.getObject(index);
try {
return toMap(objectValue, cache);
} finally {
if (objectValue instanceof V8Object) {
objectValue.release();
}
}
case V8Value.NULL:
return null;
case V8Value.UNDEFINED:
return V8.getUndefined();
default:
throw new IllegalStateException("Cannot find type for index: " + index);
}
}
#location 33
#vulnerability type NULL_DEREFERENCE |
#fixed code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void release(final boolean reportMemoryLeaks) {
if (isReleased()) {
return;
}
checkThread();
if (debugEnabled) {
disableDebugSupport();
}
releaseResources();
shutdownExecutors(forceTerminateExecutors);
if (executors != null) {
executors.clear();
}
synchronized (lock) {
runtimeCounter--;
}
_releaseRuntime(v8RuntimePtr);
v8RuntimePtr = 0L;
released = true;
if (reportMemoryLeaks && (objectReferences > 0)) {
throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime");
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@Test
public void testTypedArrayGetValue_Float64Array() {
V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n"
+ "var floatsArray = new Float64Array(buf);\n"
+ "floatsArray[0] = 16.2;\n"
+ "floatsArray;\n");
V8TypedArray result = ((TypedArray) V8ObjectUtils.getValue(floatsArray)).getV8TypedArray();
assertEquals(10, result.length());
assertEquals(16.2, (Double) result.get(0), 0.0001);
floatsArray.close();
result.close();
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testTypedArrayGetValue_Float64Array() {
V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n"
+ "var floatsArray = new Float64Array(buf);\n"
+ "floatsArray[0] = 16.2;\n"
+ "floatsArray;\n");
V8TypedArray result = (V8TypedArray) V8ObjectUtils.getValue(floatsArray);
assertEquals(10, result.length());
assertEquals(16.2, (Double) result.get(0), 0.0001);
floatsArray.close();
}
#location 11
#vulnerability type NULL_DEREFERENCE |
#fixed code
@Test
public void testPartialResults() throws Exception {
byte[] key1 = randomBytes(8);
byte[] key2 = randomBytes(8);
FlatRow response1 =
FlatRow.newBuilder()
.withRowKey(ByteString.copyFrom(key1))
.addCell(
new Cell(
"cf",
ByteString.EMPTY,
10,
ByteString.copyFromUtf8("hi!"),
new ArrayList<String>()))
.build();
RuntimeException exception = new RuntimeException("Something bad happened");
when(mockBulkRead.add(any(Query.class)))
.thenReturn(ApiFutures.immediateFuture(response1))
.thenReturn(ApiFutures.<FlatRow>immediateFailedFuture(exception));
List<Get> gets = Arrays.asList(new Get(key1), new Get(key2));
Object[] results = new Object[2];
try {
createExecutor().batch(gets, results);
} catch (RetriesExhaustedWithDetailsException ignored) {
}
Assert.assertTrue("first result is a result", results[0] instanceof Result);
Assert.assertTrue(Bytes.equals(((Result) results[0]).getRow(), key1));
Assert.assertEquals(exception, results[1]);
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@Test
public void testPartialResults() throws Exception {
byte[] key1 = randomBytes(8);
byte[] key2 = randomBytes(8);
FlatRow response1 =
FlatRow.newBuilder()
.withRowKey(ByteString.copyFrom(key1))
.addCell(
new Cell(
"cf",
ByteString.EMPTY,
10,
ByteString.copyFromUtf8("hi!"),
new ArrayList<String>()))
.build();
RuntimeException exception = new RuntimeException("Something bad happened");
when(mockBulkRead.add(any(Query.class)))
.thenReturn(ApiFutures.immediateFuture(response1))
.thenReturn(ApiFutures.<FlatRow>immediateFailedFuture(exception));
List<Get> gets = Arrays.asList(new Get(key1), new Get(key2));
Object[] results = new Object[2];
try {
createExecutor(options).batch(gets, results);
} catch (RetriesExhaustedWithDetailsException ignored) {
}
Assert.assertTrue("first result is a result", results[0] instanceof Result);
Assert.assertTrue(Bytes.equals(((Result) results[0]).getRow(), key1));
Assert.assertEquals(exception, results[1]);
}
#location 26
#vulnerability type RESOURCE_LEAK |
#fixed code
public void awaitCompletion() throws InterruptedException {
boolean performedWarning = false;
lock.lock();
try {
while (!isFlushed()) {
flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS);
long now = clock.nanoTime();
if (now >= noSuccessCheckDeadlineNanos) {
// There are unusual cases where an RPC could be completed, but we don't clean up
// the state and the locks. Try to clean up if there is a timeout.
for (RetryHandler retryHandler : outstandingRetries.values()) {
retryHandler.performRetryIfStale();
}
logNoSuccessWarning(now);
resetNoSuccessWarningDeadline();
performedWarning = true;
}
}
if (performedWarning) {
LOG.info("awaitCompletion() completed");
}
} finally {
lock.unlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
public void awaitCompletion() throws InterruptedException {
boolean performedWarning = false;
lock.lock();
try {
while (!isFlushed()) {
flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS);
long now = clock.nanoTime();
if (now >= noSuccessWarningDeadlineNanos) {
logNoSuccessWarning(now);
resetNoSuccessWarningDeadline();
performedWarning = true;
}
}
if (performedWarning) {
LOG.info("awaitCompletion() completed");
}
} finally {
lock.unlock();
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION |
#fixed code
@SuppressWarnings("unchecked")
@Override
public void run() {
try {
// restart the clock.
synchronized (callLock) {
super.run();
// pre-fetch one more result, for performance reasons.
adapter.request(1);
if (rowObserver instanceof ClientResponseObserver) {
((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter);
}
lastResponseMs = clock.currentTimeMillis();
}
} catch (Exception e) {
setException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. | #vulnerable code
@SuppressWarnings("unchecked")
@Override
public void run() {
try {
// restart the clock.
this.rowMerger = new RowMerger(rowObserver);
adapter = new CallToStreamObserverAdapter();
synchronized (callLock) {
super.run();
// pre-fetch one more result, for performance reasons.
adapter.request(1);
if (rowObserver instanceof ClientResponseObserver) {
((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter);
}
lastResponseMs = clock.currentTimeMillis();
}
} catch (Exception e) {
setException(e);
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 7