instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private RelationshipBuilder getRelationshipBuilder(Compiler cypherBuilder, Object entity, DirectedRelationship directedRelationship, boolean mapBothDirections) { RelationshipBuilder relationshipBuilder; if (isRelationshipEntity(entity)) { Long relId = (Long) EntityUtils.identity(entity, metaData); boolean relationshipEndsChanged = haveRelationEndsChanged(entity, relId); if (relId < 0 || relationshipEndsChanged) { //if the RE itself is new, or it exists but has one of it's end nodes changed relationshipBuilder = cypherBuilder.newRelationship(directedRelationship.type()); if (relationshipEndsChanged) { Field identityField = metaData.classInfo(entity).getField(metaData.classInfo(entity).identityField()); FieldInfo.write(identityField, entity, null); //reset the ID to null } } else { relationshipBuilder = cypherBuilder.existingRelationship(relId, directedRelationship.type()); } } else { relationshipBuilder = cypherBuilder.newRelationship(directedRelationship.type(), mapBothDirections); } relationshipBuilder.direction(directedRelationship.direction()); if (isRelationshipEntity(entity)) { relationshipBuilder.setSingleton(false); // indicates that this relationship type can be mapped multiple times between 2 nodes relationshipBuilder.setReference(EntityUtils.identity(entity, metaData)); relationshipBuilder.setRelationshipEntity(true); } return relationshipBuilder; }
#vulnerable code private RelationshipBuilder getRelationshipBuilder(Compiler cypherBuilder, Object entity, DirectedRelationship directedRelationship, boolean mapBothDirections) { RelationshipBuilder relationshipBuilder; if (isRelationshipEntity(entity)) { Long relId = (Long) metaData.classInfo(entity).identityField().readProperty(entity); boolean relationshipEndsChanged = haveRelationEndsChanged(entity, relId); if (relId == null || relationshipEndsChanged) { //if the RE itself is new, or it exists but has one of it's end nodes changed relationshipBuilder = cypherBuilder.newRelationship(directedRelationship.type()); if (relationshipEndsChanged) { Field identityField = metaData.classInfo(entity).getField(metaData.classInfo(entity).identityField()); FieldInfo.write(identityField, entity, null); //reset the ID to null } } else { relationshipBuilder = cypherBuilder.existingRelationship(relId, directedRelationship.type()); } } else { relationshipBuilder = cypherBuilder.newRelationship(directedRelationship.type(), mapBothDirections); } relationshipBuilder.direction(directedRelationship.direction()); if (isRelationshipEntity(entity)) { relationshipBuilder.setSingleton(false); // indicates that this relationship type can be mapped multiple times between 2 nodes relationshipBuilder.setReference(EntityUtils.identity(entity, metaData)); relationshipBuilder.setRelationshipEntity(true); } return relationshipBuilder; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public QueryStatistics execute(String statement) { if (StringUtils.isEmpty(statement)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } assertNothingReturned(statement); RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(statement, Utils.map()); Transaction tx = session.ensureTransaction(); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, tx)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } }
#vulnerable code @Override public QueryStatistics execute(String statement) { if (StringUtils.isEmpty(statement)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } assertNothingReturned(statement); RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(statement, Utils.map()); String url = session.ensureTransaction().url(); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, url)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private <T> Iterable<T> executeAndMap(Class<T> type, String cypher, Map<String, ?> parameters, RowModelMapper<T> rowModelMapper) { if (StringUtils.isEmpty(cypher)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } if (parameters == null) { throw new RuntimeException("Supplied Parameters cannot be null."); } Transaction tx = session.ensureTransaction(); if (type != null && session.metaData().classInfo(type.getSimpleName()) != null) { Query qry = new GraphModelQuery(cypher, parameters); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, tx)) { return session.responseHandler().loadAll(type, response); } } else { RowModelQuery qry = new RowModelQuery(cypher, parameters); try (Neo4jResponse<RowModel> response = session.requestHandler().execute(qry, tx)) { String[] variables = response.columns(); Collection<T> result = new ArrayList<>(); RowModel rowModel; while ((rowModel = response.next()) != null) { rowModelMapper.mapIntoResult(result, rowModel.getValues(), variables); } return result; } } }
#vulnerable code private <T> Iterable<T> executeAndMap(Class<T> type, String cypher, Map<String, ?> parameters, RowModelMapper<T> rowModelMapper) { if (StringUtils.isEmpty(cypher)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } if (parameters == null) { throw new RuntimeException("Supplied Parameters cannot be null."); } String url = session.ensureTransaction().url(); if (type != null && session.metaData().classInfo(type.getSimpleName()) != null) { Query qry = new GraphModelQuery(cypher, parameters); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, url)) { return session.responseHandler().loadAll(type, response); } } else { RowModelQuery qry = new RowModelQuery(cypher, parameters); try (Neo4jResponse<RowModel> response = session.requestHandler().execute(qry, url)) { String[] variables = response.columns(); Collection<T> result = new ArrayList<>(); RowModel rowModel; while ((rowModel = response.next()) != null) { rowModelMapper.mapIntoResult(result, rowModel.getValues(), variables); } return result; } } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public QueryStatistics execute(String statement) { if (StringUtils.isEmpty(statement)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } assertNothingReturned(statement); RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(statement, Utils.map()); Transaction tx = session.ensureTransaction(); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, tx)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } }
#vulnerable code @Override public QueryStatistics execute(String statement) { if (StringUtils.isEmpty(statement)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } assertNothingReturned(statement); RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(statement, Utils.map()); String url = session.ensureTransaction().url(); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, url)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public QueryStatistics execute(String cypher, Map<String, Object> parameters) { if (StringUtils.isEmpty(cypher)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } if (parameters == null) { throw new RuntimeException("Supplied Parameters cannot be null."); } assertNothingReturned(cypher); Transaction tx = session.ensureTransaction(); // NOTE: No need to check if domain objects are parameters and flatten them to json as this is done // for us using the existing execute() method. RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, tx)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } }
#vulnerable code @Override public QueryStatistics execute(String cypher, Map<String, Object> parameters) { if (StringUtils.isEmpty(cypher)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } if (parameters == null) { throw new RuntimeException("Supplied Parameters cannot be null."); } assertNothingReturned(cypher); String url = session.ensureTransaction().url(); // NOTE: No need to check if domain objects are parameters and flatten them to json as this is done // for us using the existing execute() method. RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, url)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void configure(String configurationFileName) { try (InputStream is = toInputStream(configurationFileName)) { configure(is); } catch (Exception e) { logger.warn("Could not configure OGM from {}", configurationFileName); } }
#vulnerable code public static void configure(String configurationFileName) { try (InputStream is = classPathResource(configurationFileName)) { configure(is); } catch (Exception e) { logger.warn("Could not configure OGM from {}", configurationFileName); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public FieldInfo propertyField(String propertyName) { if (propertyFields == null) { initPropertyFields(); } return propertyFields.get(propertyName.toLowerCase()); }
#vulnerable code public FieldInfo propertyField(String propertyName) { if (propertyFields == null) { if (propertyFields == null) { Collection<FieldInfo> fieldInfos = propertyFields(); propertyFields = new HashMap<>(fieldInfos.size()); for (FieldInfo fieldInfo : fieldInfos) { propertyFields.put(fieldInfo.property().toLowerCase(), fieldInfo); } } } return propertyFields.get(propertyName.toLowerCase()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testIndexesAreSuccessfullyValidated() { createLoginConstraint(); baseConfiguration.setAutoIndex("validate"); AutoIndexManager indexManager = new AutoIndexManager(metaData, Components.driver(), baseConfiguration); assertEquals(AutoIndexMode.VALIDATE.getName(), baseConfiguration.getAutoIndex()); assertEquals(1, indexManager.getIndexes().size()); indexManager.build(); dropLoginConstraint(); }
#vulnerable code @Test public void testIndexesAreSuccessfullyValidated() { createLoginConstraint(); Components.getConfiguration().setAutoIndex("validate"); AutoIndexManager indexManager = new AutoIndexManager(metaData, Components.driver()); assertEquals(AutoIndexMode.VALIDATE.getName(), Components.getConfiguration().getAutoIndex()); assertEquals(1, indexManager.getIndexes().size()); indexManager.build(); dropLoginConstraint(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public QueryStatistics execute(String cypher, Map<String, Object> parameters) { if (StringUtils.isEmpty(cypher)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } if (parameters == null) { throw new RuntimeException("Supplied Parameters cannot be null."); } assertNothingReturned(cypher); Transaction tx = session.ensureTransaction(); // NOTE: No need to check if domain objects are parameters and flatten them to json as this is done // for us using the existing execute() method. RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, tx)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } }
#vulnerable code @Override public QueryStatistics execute(String cypher, Map<String, Object> parameters) { if (StringUtils.isEmpty(cypher)) { throw new RuntimeException("Supplied cypher statement must not be null or empty."); } if (parameters == null) { throw new RuntimeException("Supplied Parameters cannot be null."); } assertNothingReturned(cypher); String url = session.ensureTransaction().url(); // NOTE: No need to check if domain objects are parameters and flatten them to json as this is done // for us using the existing execute() method. RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, url)) { RowQueryStatisticsResult result = response.next(); return result == null ? null : result.getStats(); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String createTemporaryEphemeralFileStore() { try { Path path = Files.createTempDirectory("neo4j.db"); File f = path.toFile(); f.deleteOnExit(); URI uri = f.toURI(); String fileStoreUri = uri.toString(); return fileStoreUri; } catch (Exception e) { throw new RuntimeException(e); } }
#vulnerable code private String createTemporaryEphemeralFileStore() { try { System.out.format("java tmpdir root: %s\n", System.getProperty("java.io.tmpdir")); Path path = Files.createTempDirectory("neo4j.db"); System.out.format("Check temporary directory %s\n", path.toString()); File f = path.toFile(); System.out.format("Checking directory actually exists as a file %s\n", f.exists()); f.deleteOnExit(); URI uri = f.toURI(); System.out.format("Checking URI object is not null: %s\n", uri != null); System.out.format("Checking URI as String %s\n", uri.toString()); String fileStoreUri = uri.toString(); return fileStoreUri; } catch (Exception e) { System.out.println("Caught an exception:"); e.printStackTrace(); throw new RuntimeException(e); } } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public SuperstepState coordinateSuperstep() throws KeeperException, InterruptedException { // 1. Get chosen workers and set up watches on them. // 2. Assign partitions to the workers // or possibly reload from a superstep // 3. Wait for all workers to complete // 4. Collect and process aggregators // 5. Create superstep finished node // 6. If the checkpoint frequency is met, finalize the checkpoint Map<String, JSONArray> chosenWorkerHostnamePortMap = checkWorkers(); if (chosenWorkerHostnamePortMap == null) { LOG.fatal("coordinateSuperstep: Not enough healthy workers for " + "superstep " + getSuperstep()); setJobState(ApplicationState.FAILED, -1, -1); } else { for (Entry<String, JSONArray> entry : chosenWorkerHostnamePortMap.entrySet()) { String workerHealthyPath = getWorkerHealthyPath(getApplicationAttempt(), getSuperstep()) + "/" + entry.getKey(); if (getZkExt().exists(workerHealthyPath, true) == null) { LOG.warn("coordinateSuperstep: Chosen worker " + workerHealthyPath + " is no longer valid, failing superstep"); } } } currentWorkersCounter.increment(chosenWorkerHostnamePortMap.size() - currentWorkersCounter.getValue()); if (getRestartedSuperstep() == getSuperstep()) { try { if (LOG.isInfoEnabled()) { LOG.info("coordinateSuperstep: Reloading from superstep " + getSuperstep()); } mapFilesToWorkers( getRestartedSuperstep(), new ArrayList<String>( chosenWorkerHostnamePortMap.keySet())); inputSplitsToVertexRanges(chosenWorkerHostnamePortMap); } catch (IOException e) { throw new IllegalStateException( "coordinateSuperstep: Failed to reload", e); } } else { if (getSuperstep() > INPUT_SUPERSTEP) { VertexRangeBalancer<I, V, E, M> vertexRangeBalancer = BspUtils.<I, V, E, M>createVertexRangeBalancer( getConfiguration()); synchronized (vertexRangeSynchronization) { balanceVertexRanges(vertexRangeBalancer, chosenWorkerHostnamePortMap); } } } String finishedWorkerPath = getWorkerFinishedPath(getApplicationAttempt(), getSuperstep()); try { getZkExt().createExt(finishedWorkerPath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true); } catch (KeeperException.NodeExistsException e) { if (LOG.isDebugEnabled()) { LOG.debug("coordinateSuperstep: finishedWorkers " + finishedWorkerPath + " already exists, no need to create"); } } String workerHealthyPath = getWorkerHealthyPath(getApplicationAttempt(), getSuperstep()); List<String> finishedWorkerList = null; long nextInfoMillis = System.currentTimeMillis(); while (true) { try { finishedWorkerList = getZkExt().getChildrenExt(finishedWorkerPath, true, false, false); } catch (KeeperException e) { throw new IllegalStateException( "coordinateSuperstep: Couldn't get children of " + finishedWorkerPath, e); } if (LOG.isDebugEnabled()) { LOG.debug("coordinateSuperstep: Got finished worker list = " + finishedWorkerList + ", size = " + finishedWorkerList.size() + ", chosen worker list = " + chosenWorkerHostnamePortMap.keySet() + ", size = " + chosenWorkerHostnamePortMap.size() + " from " + finishedWorkerPath); } if (LOG.isInfoEnabled() && (System.currentTimeMillis() > nextInfoMillis)) { nextInfoMillis = System.currentTimeMillis() + 30000; LOG.info("coordinateSuperstep: " + finishedWorkerList.size() + " out of " + chosenWorkerHostnamePortMap.size() + " chosen workers finished on superstep " + getSuperstep()); } getContext().setStatus(getGraphMapper().getMapFunctions() + " - " + finishedWorkerList.size() + " finished out of " + chosenWorkerHostnamePortMap.size() + " on superstep " + getSuperstep()); if (finishedWorkerList.containsAll( chosenWorkerHostnamePortMap.keySet())) { break; } getSuperstepStateChangedEvent().waitForever(); getSuperstepStateChangedEvent().reset(); // Did a worker die? if ((getSuperstep() > 0) && !superstepChosenWorkerAlive( workerHealthyPath, chosenWorkerHostnamePortMap.keySet())) { return SuperstepState.WORKER_FAILURE; } } collectAndProcessAggregatorValues(getSuperstep()); JSONObject globalInfoObject = aggregateWorkerStats(getSuperstep()); // Convert the input split stats to vertex ranges in INPUT_SUPERSTEP if (getSuperstep() == INPUT_SUPERSTEP) { inputSplitsToVertexRanges(chosenWorkerHostnamePortMap); } // Let everyone know the aggregated application state through the // superstep String superstepFinishedNode = getSuperstepFinishedPath(getApplicationAttempt(), getSuperstep()); try { getZkExt().createExt(superstepFinishedNode, globalInfoObject.toString().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true); vertexCounter.increment( globalInfoObject.getLong(JSONOBJ_NUM_VERTICES_KEY) - vertexCounter.getValue()); finishedVertexCounter.increment( globalInfoObject.getLong(JSONOBJ_FINISHED_VERTICES_KEY) - finishedVertexCounter.getValue()); edgeCounter.increment( globalInfoObject.getLong(JSONOBJ_NUM_EDGES_KEY) - edgeCounter.getValue()); sentMessagesCounter.increment( globalInfoObject.getLong(JSONOBJ_NUM_MESSAGES_KEY) - sentMessagesCounter.getValue()); } catch (JSONException e) { throw new IllegalStateException("coordinateSuperstep: " + "JSONException", e); } // Finalize the valid checkpoint file prefixes and possibly // the aggregators. if (checkpointFrequencyMet(getSuperstep())) { try { finalizeCheckpoint( getSuperstep(), new ArrayList<String>(chosenWorkerHostnamePortMap.keySet())); } catch (IOException e) { throw new IllegalStateException( "coordinateSuperstep: IOException on finalizing checkpoint", e); } } // Clean up the old supersteps (always keep this one) long removeableSuperstep = getSuperstep() - 1; if ((getConfiguration().getBoolean( GiraphJob.KEEP_ZOOKEEPER_DATA, GiraphJob.KEEP_ZOOKEEPER_DATA_DEFAULT) == false) && (removeableSuperstep >= 0)) { String oldSuperstepPath = getSuperstepPath(getApplicationAttempt()) + "/" + (removeableSuperstep); try { if (LOG.isInfoEnabled()) { LOG.info("coordinateSuperstep: Cleaning up old Superstep " + oldSuperstepPath); } getZkExt().deleteExt(oldSuperstepPath, -1, true); } catch (KeeperException.NoNodeException e) { LOG.warn("coordinateBarrier: Already cleaned up " + oldSuperstepPath); } catch (KeeperException e) { throw new IllegalStateException( "coordinateSuperstep: KeeperException on " + "finalizing checkpoint", e); } } incrCachedSuperstep(); superstepCounter.increment(1); try { if ((globalInfoObject.getLong(JSONOBJ_FINISHED_VERTICES_KEY) == globalInfoObject.getLong(JSONOBJ_NUM_VERTICES_KEY)) && (globalInfoObject.getLong(JSONOBJ_NUM_MESSAGES_KEY)) == 0) { return SuperstepState.ALL_SUPERSTEPS_DONE; } else { return SuperstepState.THIS_SUPERSTEP_DONE; } } catch (JSONException e) { throw new IllegalStateException( "coordinateSuperstep: JSONException on checking if " + "the application is done", e); } }
#vulnerable code @Override public SuperstepState coordinateSuperstep() throws KeeperException, InterruptedException { // 1. Get chosen workers and set up watches on them. // 2. Assign partitions to the workers // or possibly reload from a superstep // 3. Wait for all workers to complete // 4. Collect and process aggregators // 5. Create superstep finished node // 6. If the checkpoint frequency is met, finalize the checkpoint Map<String, JSONArray> chosenWorkerHostnamePortMap = checkWorkers(); if (chosenWorkerHostnamePortMap == null) { LOG.fatal("coordinateSuperstep: Not enough healthy workers for " + "superstep " + getSuperstep()); setJobState(State.FAILED, -1, -1); } else { for (Entry<String, JSONArray> entry : chosenWorkerHostnamePortMap.entrySet()) { String workerHealthyPath = getWorkerHealthyPath(getApplicationAttempt(), getSuperstep()) + "/" + entry.getKey(); if (getZkExt().exists(workerHealthyPath, true) == null) { LOG.warn("coordinateSuperstep: Chosen worker " + workerHealthyPath + " is no longer valid, failing superstep"); } } } currentWorkersCounter.increment(chosenWorkerHostnamePortMap.size() - currentWorkersCounter.getValue()); if (getRestartedSuperstep() == getSuperstep()) { try { if (LOG.isInfoEnabled()) { LOG.info("coordinateSuperstep: Reloading from superstep " + getSuperstep()); } mapFilesToWorkers( getRestartedSuperstep(), new ArrayList<String>( chosenWorkerHostnamePortMap.keySet())); inputSplitsToVertexRanges(chosenWorkerHostnamePortMap); } catch (IOException e) { throw new IllegalStateException( "coordinateSuperstep: Failed to reload", e); } } else { if (getSuperstep() > 0) { VertexRangeBalancer<I, V, E, M> vertexRangeBalancer = BspUtils.<I, V, E, M>createVertexRangeBalancer( getConfiguration()); synchronized (vertexRangeSynchronization) { balanceVertexRanges(vertexRangeBalancer, chosenWorkerHostnamePortMap); } } } String finishedWorkerPath = getWorkerFinishedPath(getApplicationAttempt(), getSuperstep()); try { getZkExt().createExt(finishedWorkerPath, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true); } catch (KeeperException.NodeExistsException e) { if (LOG.isDebugEnabled()) { LOG.debug("coordinateSuperstep: finishedWorkers " + finishedWorkerPath + " already exists, no need to create"); } } String workerHealthyPath = getWorkerHealthyPath(getApplicationAttempt(), getSuperstep()); List<String> finishedWorkerList = null; long nextInfoMillis = System.currentTimeMillis(); while (true) { try { finishedWorkerList = getZkExt().getChildrenExt(finishedWorkerPath, true, false, false); } catch (KeeperException e) { throw new IllegalStateException( "coordinateSuperstep: Couldn't get children of " + finishedWorkerPath, e); } if (LOG.isDebugEnabled()) { LOG.debug("coordinateSuperstep: Got finished worker list = " + finishedWorkerList + ", size = " + finishedWorkerList.size() + ", chosen worker list = " + chosenWorkerHostnamePortMap.keySet() + ", size = " + chosenWorkerHostnamePortMap.size() + " from " + finishedWorkerPath); } if (LOG.isInfoEnabled() && (System.currentTimeMillis() > nextInfoMillis)) { nextInfoMillis = System.currentTimeMillis() + 30000; LOG.info("coordinateSuperstep: " + finishedWorkerList.size() + " out of " + chosenWorkerHostnamePortMap.size() + " chosen workers finished on superstep " + getSuperstep()); } getContext().setStatus(getGraphMapper().getMapFunctions() + " " + finishedWorkerList.size() + " finished out of " + chosenWorkerHostnamePortMap.size() + " on superstep " + getSuperstep()); if (finishedWorkerList.containsAll( chosenWorkerHostnamePortMap.keySet())) { break; } getSuperstepStateChangedEvent().waitForever(); getSuperstepStateChangedEvent().reset(); // Did a worker die? if ((getSuperstep() > 0) && !superstepChosenWorkerAlive( workerHealthyPath, chosenWorkerHostnamePortMap.keySet())) { return SuperstepState.WORKER_FAILURE; } } collectAndProcessAggregatorValues(getSuperstep()); JSONObject globalInfoObject = aggregateWorkerStats(getSuperstep()); // Convert the input split stats to vertex ranges in superstep 0 if (getSuperstep() == 0) { inputSplitsToVertexRanges(chosenWorkerHostnamePortMap); } // Let everyone know the aggregated application state through the // superstep String superstepFinishedNode = getSuperstepFinishedPath(getApplicationAttempt(), getSuperstep()); try { getZkExt().createExt(superstepFinishedNode, globalInfoObject.toString().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, true); vertexCounter.increment( globalInfoObject.getLong(JSONOBJ_NUM_VERTICES_KEY) - vertexCounter.getValue()); finishedVertexCounter.increment( globalInfoObject.getLong(JSONOBJ_FINISHED_VERTICES_KEY) - finishedVertexCounter.getValue()); edgeCounter.increment( globalInfoObject.getLong(JSONOBJ_NUM_EDGES_KEY) - edgeCounter.getValue()); sentMessagesCounter.increment( globalInfoObject.getLong(JSONOBJ_NUM_MESSAGES_KEY) - sentMessagesCounter.getValue()); } catch (JSONException e) { throw new IllegalStateException("coordinateSuperstep: " + "JSONException", e); } // Finalize the valid checkpoint file prefixes and possibly // the aggregators. if (checkpointFrequencyMet(getSuperstep())) { try { finalizeCheckpoint( getSuperstep(), new ArrayList<String>(chosenWorkerHostnamePortMap.keySet())); } catch (IOException e) { throw new IllegalStateException( "coordinateSuperstep: IOException on finalizing checkpoint", e); } } // Clean up the old supersteps (always keep this one) long removeableSuperstep = getSuperstep() - 1; if ((getConfiguration().getBoolean( GiraphJob.KEEP_ZOOKEEPER_DATA, GiraphJob.KEEP_ZOOKEEPER_DATA_DEFAULT) == false) && (removeableSuperstep >= 0)) { String oldSuperstepPath = getSuperstepPath(getApplicationAttempt()) + "/" + (removeableSuperstep); try { if (LOG.isInfoEnabled()) { LOG.info("coordinateSuperstep: Cleaning up old Superstep " + oldSuperstepPath); } getZkExt().deleteExt(oldSuperstepPath, -1, true); } catch (KeeperException.NoNodeException e) { LOG.warn("coordinateBarrier: Already cleaned up " + oldSuperstepPath); } catch (KeeperException e) { throw new IllegalStateException( "coordinateSuperstep: KeeperException on " + "finalizing checkpoint", e); } } incrCachedSuperstep(); superstepCounter.increment(1); try { if ((globalInfoObject.getLong(JSONOBJ_FINISHED_VERTICES_KEY) == globalInfoObject.getLong(JSONOBJ_NUM_VERTICES_KEY)) && (globalInfoObject.getLong(JSONOBJ_NUM_MESSAGES_KEY)) == 0) { return SuperstepState.ALL_SUPERSTEPS_DONE; } else { return SuperstepState.THIS_SUPERSTEP_DONE; } } catch (JSONException e) { throw new IllegalStateException( "coordinateSuperstep: JSONException on checking if " + "the application is done", e); } } #location 42 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void load(String name, List<String> col) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(name),"US-ASCII")); try { String line; while ((line=r.readLine())!=null) col.add(line); } finally { r.close(); } }
#vulnerable code private void load(String name, List<String> col) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(name),"US-ASCII")); String line; while ((line=r.readLine())!=null) col.add(line); r.close(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addSendJob(Frame f, int sec, int usec) { StringBuilder sb = new StringBuilder(40); sb.append("< add "); sb.append(Integer.toString(sec)); sb.append(' '); sb.append(Integer.toString(usec)); sb.append(' '); sb.append(Integer.toHexString(f.getIdentifier())); sb.append(' '); sb.append(Integer.toString(f.getLength())); sb.append(' '); sb.append(Util.byteArrayToHexString(f.getData())); sb.append(" >"); send(sb.toString()); }
#vulnerable code public void addSendJob(Frame f, int sec, int usec) { synchronized(output) { output.print("< add " + Integer.toString(sec) + " " + Integer.toString(usec) + " " + Integer.toHexString(f.getIdentifier()) + " " + Integer.toString(f.getLength()) + " " + Util.byteArrayToHexString(f.getData()) + " >"); output.flush(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); }
#vulnerable code Object readProperties(java.util.Properties p) { if (instance == null) { instance = this; } instance.readPropertiesImpl(p); return instance; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void writeProperties(java.util.Properties p) { p.setProperty("version", "1.0"); p.setProperty("busName", bus.getName()); ProjectManager manager = ProjectManager.getGlobalProjectManager(); p.setProperty("projectName", manager.getOpenedProject().getName()); }
#vulnerable code Object readProperties(java.util.Properties p) { if (instance == null) { instance = this; } instance.readPropertiesImpl(p); return instance; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected Node[] createNodesForKey(BusDescription key) { Bus bus = null; for(Bus b : project.getBusses()) { if(b.getDescription() == key) bus = b; } return new Node[] { new BusNode(key, bus) }; }
#vulnerable code @Override protected Node[] createNodesForKey(BusDescription key) { Bus bus = null; for(Bus b : project.getBusses()) { if(b.getDescription() == key) bus = b; } AbstractNode node = new AbstractNode(Children.create(new MessageNodeFactory(key, bus), true), Lookups.fixed(key, bus)); node.setIconBaseWithExtension("org/freedesktop/tango/16x16/places/network-workgroup.png"); node.setDisplayName(bus.getName() + " (" + key.getName() + ")"); return new Node[] { node }; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setDescription(String description) throws FileNotFoundException, IOException { if(!descriptionPattern.matcher(description).matches()) throw new IllegalArgumentException("Description must match " + descriptionPattern.pattern()); this.description = description; rewriteHeader(); }
#vulnerable code public void setDescription(String description) throws FileNotFoundException, IOException { if(!descriptionPattern.matcher(description).matches()) throw new IllegalArgumentException("Description must match " + descriptionPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("DESCRIPTION"))) { pw.println("DESCRIPTION \"" + description + "\""); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("DESCRIPTION \"" + description + "\""); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.description = description; } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void subscribeTo(int id, int sec, int usec) { StringBuilder sb = new StringBuilder(30); sb.append("< subscribe "); sb.append(String.valueOf(sec)); sb.append(' '); sb.append(String.valueOf(usec)); sb.append(' '); sb.append(Integer.toHexString(id)); sb.append(" >"); send(sb.toString()); }
#vulnerable code public void subscribeTo(int id, int sec, int usec) { synchronized(output) { output.print("< subscribe " + Integer.toString(sec) + " " + Integer.toString(usec) + " " + Integer.toHexString(id) + " >"); output.flush(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Boolean checkConnection() { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(host, port); InputStreamReader input = null; OutputStreamWriter output = null; try { socket.setSoTimeout(10); socket.connect(address, 50); input = new InputStreamReader( socket.getInputStream()); output = new OutputStreamWriter(socket.getOutputStream()); String ret = "< hi >"; for(int i=0;i<6;i++) { if(input.read() != ret.charAt(i)) { logger.log(Level.INFO, "Could not connect to host"); return false; } } output.write("< open " + bus + " >"); output.flush(); ret = "< ok >"; for(int i=0;i<6;i++) { if(input.read() != ret.charAt(i)) { logger.log(Level.INFO, "Could not open bus"); return false; } } } catch (IOException ex) { logger.log(Level.INFO, "Could not connect to host", ex); return false; } finally { if(input != null) { try { input.close(); output.close(); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } return true; }
#vulnerable code public Boolean checkConnection() { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(host, port); InputStreamReader input = null; try { socket.setSoTimeout(10); socket.connect(address, 50); input = new InputStreamReader( socket.getInputStream()); String ret = "< hi >"; for(int i=0;i<6;i++) { if(input.read() != ret.charAt(i)) { logger.log(Level.INFO, "Could not connect to host"); return false; } } } catch (IOException ex) { logger.log(Level.INFO, "Could not connect to host", ex); return false; } finally { if(input != null) { try { input.close(); } catch (IOException ex) { Logger.getLogger(BusURL.class.getName()).log(Level.SEVERE, null, ex); } } } return true; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateSendJob(Frame f) { StringBuilder sb = new StringBuilder(40); sb.append("< add "); sb.append(Integer.toHexString(f.getIdentifier())); sb.append(' '); sb.append(Integer.toString(f.getLength())); sb.append(' '); sb.append(Util.byteArrayToHexString(f.getData())); sb.append(" >"); send(sb.toString()); }
#vulnerable code public void updateSendJob(Frame f) { synchronized(output) { output.print("< add " + Integer.toHexString(f.getIdentifier()) + " " + Integer.toString(f.getLength()) + " " + Util.byteArrayToHexString(f.getData()) + " >"); output.flush(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); this.platform = platform; rewriteHeader(); }
#vulnerable code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("PLATFORM"))) { pw.println("PLATFORM " + platform); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("PLATFORM " + platform); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.platform = platform; } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void unsubscribed(int id, Subscription s) { if(subscriptionsBCM.contains(s)) { safeUnsubscribe(id); } else { logger.log(Level.WARNING, "Unregistered subscription tried to unsubscribe!"); } }
#vulnerable code @Override public void unsubscribed(int id, Subscription s) { if(subscriptionsBCM.contains(s)) { safeUnsubscribe(id); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setConnection(BusURL url) { disconnect(); this.url = url; rawConnection = new RAWConnection(url); bcmConnection = new BCMConnection(url); rawConnection.setReceiver(rawReceiver); bcmConnection.setReceiver(bcmReceiver); notifyListenersConnection(); }
#vulnerable code public void setConnection(BusURL url) { disconnect(); this.url = url; rawConnection = new RAWConnection(url); bcmConnection = new BCMConnection(url); rawConnection.setReceiver(rawReceiver); bcmConnection.setReceiver(bcmReceiver); notifyListenersConnection(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setDescription(String description) throws FileNotFoundException, IOException { if(!descriptionPattern.matcher(description).matches()) throw new IllegalArgumentException("Description must match " + descriptionPattern.pattern()); this.description = description; rewriteHeader(); }
#vulnerable code public void setDescription(String description) throws FileNotFoundException, IOException { if(!descriptionPattern.matcher(description).matches()) throw new IllegalArgumentException("Description must match " + descriptionPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("DESCRIPTION"))) { pw.println("DESCRIPTION \"" + description + "\""); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("DESCRIPTION \"" + description + "\""); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.description = description; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void unsubscribeRange(int from, int to) { synchronized(ids) { for (int i = from; i <= to; i++) { if(ids.contains(i)) { ids.remove(i); changeReceiver.unsubscribed(i, this); } } } }
#vulnerable code public void unsubscribeRange(int from, int to) { synchronized(this) { for (int i = from; i <= to; i++) { if(ids.contains(i)) { ids.remove(i); changeReceiver.unsubscribed(i, this); } } } logStatus(); } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void sendFrame(Frame f) { StringBuilder sb = new StringBuilder(50); sb.append("< send "); sb.append(Integer.toHexString(f.getIdentifier())); sb.append(' '); sb.append(Integer.toString(f.getLength())); sb.append(' '); String data = Util.byteArrayToHexString(f.getData()); for(int i=0;i<data.length();i+=2) { sb.append(data.charAt(i)); sb.append(data.charAt(i+1)); sb.append(' '); } sb.append(">"); send(sb.toString()); }
#vulnerable code public void sendFrame(Frame f) { StringBuilder sb = new StringBuilder(); sb.append("< send "); sb.append(Integer.toHexString(f.getIdentifier())); sb.append(' '); sb.append(Integer.toString(f.getLength())); sb.append(' '); String data = Util.byteArrayToHexString(f.getData()); for(int i=0;i<data.length();i+=2) { sb.append(data.charAt(i)); sb.append(data.charAt(i+1)); sb.append(' '); } sb.append(">"); synchronized(output) { output.print(sb.toString()); output.flush(); } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); this.platform = platform; rewriteHeader(); }
#vulnerable code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("PLATFORM"))) { pw.println("PLATFORM " + platform); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("PLATFORM " + platform); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.platform = platform; } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void writeProperties(java.util.Properties p) { p.setProperty("version", "1.0"); p.setProperty("busName", bus.getName()); ProjectManager manager = ProjectManager.getGlobalProjectManager(); p.setProperty("projectName", manager.getOpenedProject().getName()); }
#vulnerable code Object readProperties(java.util.Properties p) { if (instance == null) { instance = this; } instance.readPropertiesImpl(p); return instance; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clear() { Integer[] identifiers = null; synchronized(ids) { identifiers = ids.toArray(new Integer[ids.size()]); ids.clear(); } for (int i=0;i<identifiers.length;i++) { changeReceiver.unsubscribed(identifiers[i], this); } }
#vulnerable code public void clear() { Integer[] identifiers = new Integer[0]; synchronized(this) { identifiers = ids.toArray(new Integer[ids.size()]); } for (int i=0;i<identifiers.length;i++) { unsubscribe(identifiers[i]); } logStatus(); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void disconnect() { if (rawConnection != null && rawConnection.isConnected()) { rawConnection.close(); } if (bcmConnection != null && bcmConnection.isConnected()) { bcmConnection.close(); } notifyListenersConnection(); }
#vulnerable code public void disconnect() { if (rawConnection != null && rawConnection.isConnected()) { rawConnection.close(); } if (bcmConnection != null && bcmConnection.isConnected()) { bcmConnection.close(); } url = null; notifyListenersConnection(); } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void subscriptionAllChanged(boolean all, Subscription s) { /* BCM subscription switched to RAW subscription */ if (all == true) { subscriptionsBCM.remove(s); if(!subscriptionsRAW.contains(s)) subscriptionsRAW.add(s); Set<Integer> ids = s.getAllIdentifiers(); for(Integer identifier : ids) { safeUnsubscribe(identifier); } if(mode == TimeSource.Mode.PLAY) { openRAWConnection(); } /* RAW subscription switched to BCM subscription */ } else { subscriptionsRAW.remove(s); if(!subscriptionsBCM.contains(s)) subscriptionsBCM.add(s); if(subscriptionsRAW.isEmpty() && rawConnection != null && rawConnection.isConnected()) { logger.log(Level.INFO, "No more raw subscriptions. Closing connection."); rawConnection.close(); } /* Make sure BCM connection is opened */ if(mode == TimeSource.Mode.PLAY) { openBCMConnection(); for(Integer identifier : s.getAllIdentifiers()) { bcmConnection.subscribeTo(identifier, 0, 0); } } synchronized(subscribedIDs) { for(Integer identifier : s.getAllIdentifiers()) { subscribedIDs.add(identifier); } } } }
#vulnerable code @Override public void subscriptionAllChanged(boolean all, Subscription s) { /* BCM subscription switched to RAW subscription */ if (all == true) { subscriptionsBCM.remove(s); if(!subscriptionsRAW.contains(s)) subscriptionsRAW.add(s); Set<Integer> ids = s.getAllIdentifiers(); for(Integer identifier : ids) { safeUnsubscribe(identifier); } if(mode == TimeSource.Mode.PLAY) { openRAWConnection(); } /* RAW subscription switched to BCM subscription */ } else { subscriptionsRAW.remove(s); if(!subscriptionsBCM.contains(s)) subscriptionsBCM.add(s); if(subscriptionsRAW.isEmpty() && rawConnection != null && rawConnection.isConnected()) { logger.log(Level.INFO, "No more raw subscriptions. Closing connection."); rawConnection.close(); } /* Make sure BCM connection is opened */ if(mode == TimeSource.Mode.PLAY) { openBCMConnection(); for(Integer identifier : s.getAllIdentifiers()) { bcmConnection.subscribeTo(identifier, 0, 0); } } for(Integer identifier : s.getAllIdentifiers()) { subscribedIDs.add(identifier); } } } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); this.platform = platform; rewriteHeader(); }
#vulnerable code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("PLATFORM"))) { pw.println("PLATFORM " + platform); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("PLATFORM " + platform); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.platform = platform; } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setDescription(String description) throws FileNotFoundException, IOException { if(!descriptionPattern.matcher(description).matches()) throw new IllegalArgumentException("Description must match " + descriptionPattern.pattern()); this.description = description; rewriteHeader(); }
#vulnerable code public void setDescription(String description) throws FileNotFoundException, IOException { if(!descriptionPattern.matcher(description).matches()) throw new IllegalArgumentException("Description must match " + descriptionPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("DESCRIPTION"))) { pw.println("DESCRIPTION \"" + description + "\""); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("DESCRIPTION \"" + description + "\""); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.description = description; } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void waitForReady() throws MalformedURLException { LOGGER.info("Waiting for SonarQube to be available at {}", getUrl()); Awaitility .await("SonarQube is ready") .atMost(3, TimeUnit.MINUTES) .pollInterval(5, TimeUnit.SECONDS) .ignoreExceptionsInstanceOf(ConnectException.class) .until(this::isReady) ; }
#vulnerable code public void waitForReady() { while (true) { System.out.println("Waiting for SonarQube to be available at " + getUrl()); try { HttpURLConnection conn = (HttpURLConnection)getUrl("/api/settings/values.protobuf").openConnection(); conn.connect(); int code = conn.getResponseCode(); if (code == 200) { break; } } catch (IOException e) { /* noop */ } try { Thread.sleep(5000); } catch (InterruptedException e) { /* noop */ } } System.out.println("SonarQube is ready"); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Response getNonOAuth(String path, Map<String, String> parameters) { InputStream in = null; try { URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters); if (Flickr.debugRequest) { logger.debug("GET: " + url); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (proxyAuth) { conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials()); } setTimeouts(conn); conn.connect(); if (Flickr.debugStream) { in = new DebugInputStream(conn.getInputStream(), System.out); } else { in = conn.getInputStream(); } Response response; DocumentBuilder builder = getDocumentBuilder(); Document document = builder.parse(in); response = (Response) responseClass.newInstance(); response.parse(document); return response; } catch (IllegalAccessException | SAXException | IOException | InstantiationException | ParserConfigurationException e) { throw new FlickrRuntimeException(e); } finally { IOUtilities.close(in); } }
#vulnerable code @Override public Response getNonOAuth(String path, Map<String, String> parameters) { InputStream in = null; try { URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters); if (Flickr.debugRequest) { logger.debug("GET: " + url); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (proxyAuth) { conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials()); } setTimeouts(conn); conn.connect(); if (Flickr.debugStream) { in = new DebugInputStream(conn.getInputStream(), System.out); } else { in = conn.getInputStream(); } Response response; synchronized (mutex) { Document document = builder.parse(in); response = (Response) responseClass.newInstance(); response.parse(document); } return response; } catch (IllegalAccessException | SAXException | IOException | InstantiationException e) { throw new FlickrRuntimeException(e); } finally { IOUtilities.close(in); } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Response getNonOAuth(String path, Map<String, String> parameters) { InputStream in = null; try { URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters); if (Flickr.debugRequest) { logger.debug("GET: " + url); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (proxyAuth) { conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials()); } setTimeouts(conn); conn.connect(); if (Flickr.debugStream) { in = new DebugInputStream(conn.getInputStream(), System.out); } else { in = conn.getInputStream(); } Response response; DocumentBuilder builder = getDocumentBuilder(); Document document = builder.parse(in); response = (Response) responseClass.newInstance(); response.parse(document); return response; } catch (IllegalAccessException | SAXException | IOException | InstantiationException | ParserConfigurationException e) { throw new FlickrRuntimeException(e); } finally { IOUtilities.close(in); } }
#vulnerable code @Override public Response getNonOAuth(String path, Map<String, String> parameters) { InputStream in = null; try { URL url = UrlUtilities.buildUrl(getScheme(), getHost(), getPort(), path, parameters); if (Flickr.debugRequest) { logger.debug("GET: " + url); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (proxyAuth) { conn.setRequestProperty("Proxy-Authorization", "Basic " + getProxyCredentials()); } setTimeouts(conn); conn.connect(); if (Flickr.debugStream) { in = new DebugInputStream(conn.getInputStream(), System.out); } else { in = conn.getInputStream(); } Response response; synchronized (mutex) { Document document = builder.parse(in); response = (Response) responseClass.newInstance(); response.parse(document); } return response; } catch (IllegalAccessException | SAXException | IOException | InstantiationException e) { throw new FlickrRuntimeException(e); } finally { IOUtilities.close(in); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @JsonIgnore public List<Interval> getIntervals() { return getInnerQueryUnchecked().getIntervals(); }
#vulnerable code @Override @JsonIgnore public List<Interval> getIntervals() { return getInnerQuery().getIntervals(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public LookbackQuery withIntervals(Collection<Interval> intervals) { return withDataSource(new QueryDataSource(getInnerQueryUnchecked().withIntervals(intervals))); }
#vulnerable code @Override public LookbackQuery withIntervals(Collection<Interval> intervals) { return withDataSource(new QueryDataSource(getInnerQuery().withIntervals(intervals))); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @JsonIgnore public Filter getFilter() { return getInnerQueryUnchecked().getFilter(); }
#vulnerable code @Override @JsonIgnore public Filter getFilter() { return getInnerQuery().getFilter(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public LookbackQuery withFilter(Filter filter) { return withDataSource(new QueryDataSource(getInnerQueryUnchecked().withFilter(filter))); }
#vulnerable code @Override public LookbackQuery withFilter(Filter filter) { return withDataSource(new QueryDataSource(getInnerQuery().withFilter(filter))); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public LookbackQuery withAggregations(Collection<Aggregation> aggregations) { return withDataSource(new QueryDataSource(getInnerQueryUnchecked().withAggregations(aggregations))); }
#vulnerable code @Override public LookbackQuery withAggregations(Collection<Aggregation> aggregations) { return withDataSource(new QueryDataSource(getInnerQuery().withAggregations(aggregations))); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @JsonIgnore public Collection<Dimension> getDimensions() { return getInnerQueryUnchecked().getDimensions(); }
#vulnerable code @Override @JsonIgnore public Collection<Dimension> getDimensions() { return getInnerQuery().getDimensions(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void replaceIndex(String newLuceneIndexPathString) { LOG.debug( "Replacing Lucene indexes at {} for dimension {} with new index at {}", luceneDirectory.toString(), dimension.getApiName(), newLuceneIndexPathString ); writeLock(); try { Path oldLuceneIndexPath = Paths.get(luceneIndexPath); String tempDir = oldLuceneIndexPath.resolveSibling(oldLuceneIndexPath.getFileName() + "_old").toString(); LOG.trace("Moving old Lucene index directory from {} to {} ...", luceneIndexPath, tempDir); moveDirEntries(luceneIndexPath, tempDir); LOG.trace("Moving all new Lucene indexes from {} to {} ...", newLuceneIndexPathString, luceneIndexPath); moveDirEntries(newLuceneIndexPathString, luceneIndexPath); LOG.trace( "Deleting {} since new Lucene indexes have been moved away from there and is now empty", newLuceneIndexPathString ); deleteDir(newLuceneIndexPathString); LOG.trace("Deleting old Lucene indexes in {} ...", tempDir); deleteDir(tempDir); reopenIndexSearcher(false); } finally { writeUnlock(); } }
#vulnerable code @Override public void replaceIndex(String newLuceneIndexPathString) { LOG.debug( "Replacing Lucene indexes at {} for dimension {} with new index at {}", luceneDirectory.toString(), dimension.getApiName(), newLuceneIndexPathString ); lock.writeLock().lock(); try { Path oldLuceneIndexPath = Paths.get(luceneIndexPath); String tempDir = oldLuceneIndexPath.resolveSibling(oldLuceneIndexPath.getFileName() + "_old").toString(); LOG.trace("Moving old Lucene index directory from {} to {} ...", luceneIndexPath, tempDir); moveDirEntries(luceneIndexPath, tempDir); LOG.trace("Moving all new Lucene indexes from {} to {} ...", newLuceneIndexPathString, luceneIndexPath); moveDirEntries(newLuceneIndexPathString, luceneIndexPath); LOG.trace( "Deleting {} since new Lucene indexes have been moved away from there and is now empty", newLuceneIndexPathString ); deleteDir(newLuceneIndexPathString); LOG.trace("Deleting old Lucene indexes in {} ...", tempDir); deleteDir(tempDir); reopenIndexSearcher(false); } finally { lock.writeLock().unlock(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public LookbackQuery withInnerQueryPostAggregations(Collection<PostAggregation> postAggregations) { return new LookbackQuery(new QueryDataSource(getInnerQueryUnchecked().withPostAggregations(postAggregations)), granularity, filter, aggregations, getLookbackPostAggregations(), intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); }
#vulnerable code public LookbackQuery withInnerQueryPostAggregations(Collection<PostAggregation> postAggregations) { return new LookbackQuery(new QueryDataSource(getInnerQuery().withPostAggregations(postAggregations)), granularity, filter, aggregations, getLookbackPostAggregations(), intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) { if (executorService.isShutdown()) { throw new IllegalStateException("ExecutorService has been shutdown."); } publisherSession.init(extendedSequenceNumber, initialPositionInStreamExtended); if (!started) { log.info("{} : Starting prefetching thread.", shardId); executorService.execute(defaultGetRecordsCacheDaemon); } started = true; }
#vulnerable code @Override public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) { if (executorService.isShutdown()) { throw new IllegalStateException("ExecutorService has been shutdown."); } this.initialPositionInStreamExtended = initialPositionInStreamExtended; highestSequenceNumber = extendedSequenceNumber.sequenceNumber(); dataFetcher.initialize(extendedSequenceNumber, initialPositionInStreamExtended); if (!started) { log.info("{} : Starting prefetching thread.", shardId); executorService.execute(defaultGetRecordsCacheDaemon); } started = true; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Shard getShard(String shardId) { if (this.cachedShardMap == null) { synchronized (this) { if (this.cachedShardMap == null) { this.getShardList(); } } } Shard shard = cachedShardMap.get(shardId); if (shard == null) { if (cacheMisses.incrementAndGet() > MAX_CACHE_MISSES_BEFORE_RELOAD || cacheNeedsTimeUpdate()) { synchronized (this) { shard = cachedShardMap.get(shardId); // // If after synchronizing we resolve the shard, it means someone else already got it for us. // if (shard == null) { LOG.info("To many shard map cache misses or cache is out of date -- forcing a refresh"); this.getShardList(); shard = verifyAndLogShardAfterCacheUpdate(shardId); cacheMisses.set(0); } else { // // If someone else got us the shard go ahead and zero cache misses // cacheMisses.set(0); } } } } if (shard == null) { String message = "Cannot find the shard given the shardId " + shardId + ". Cache misses: " + cacheMisses; if (cacheMisses.get() % CACHE_MISS_WARNING_MODULUS == 0) { LOG.warn(message); } else { LOG.debug(message); } } return shard; }
#vulnerable code @Override public Shard getShard(String shardId) { if (this.listOfShardsSinceLastGet.get() == null) { //Update this.listOfShardsSinceLastGet as needed. this.getShardList(); } for (Shard shard : listOfShardsSinceLastGet.get()) { if (shard.getShardId().equals(shardId)) { return shard; } } LOG.warn("Cannot find the shard given the shardId " + shardId); return null; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) { if (executorService.isShutdown()) { throw new IllegalStateException("ExecutorService has been shutdown."); } publisherSession.init(extendedSequenceNumber, initialPositionInStreamExtended); if (!started) { log.info("{} : Starting prefetching thread.", shardId); executorService.execute(defaultGetRecordsCacheDaemon); } started = true; }
#vulnerable code @Override public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) { if (executorService.isShutdown()) { throw new IllegalStateException("ExecutorService has been shutdown."); } this.initialPositionInStreamExtended = initialPositionInStreamExtended; highestSequenceNumber = extendedSequenceNumber.sequenceNumber(); dataFetcher.initialize(extendedSequenceNumber, initialPositionInStreamExtended); if (!started) { log.info("{} : Starting prefetching thread.", shardId); executorService.execute(defaultGetRecordsCacheDaemon); } started = true; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRetryableRetrievalExceptionContinues() { GetRecordsResponse response = GetRecordsResponse.builder().millisBehindLatest(100L).records(Collections.emptyList()).build(); when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenThrow(new RetryableRetrievalException("Timeout", new TimeoutException("Timeout"))).thenReturn(response); getRecordsCache.start(sequenceNumber, initialPosition); RecordsRetrieved records = blockUntilRecordsAvailable(getRecordsCache::pollNextResultAndUpdatePrefetchCounters, 1000); assertThat(records.processRecordsInput().millisBehindLatest(), equalTo(response.millisBehindLatest())); }
#vulnerable code @Test public void testRetryableRetrievalExceptionContinues() { GetRecordsResponse response = GetRecordsResponse.builder().millisBehindLatest(100L).records(Collections.emptyList()).build(); when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenThrow(new RetryableRetrievalException("Timeout", new TimeoutException("Timeout"))).thenReturn(response); getRecordsCache.start(sequenceNumber, initialPosition); RecordsRetrieved records = getRecordsCache.getNextResult(); assertThat(records.processRecordsInput().millisBehindLatest(), equalTo(response.millisBehindLatest())); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void multipleItemTest() throws Exception { addItemsToReturn(100); setupNotifierAnswer(recordsPublisher.responses.size()); synchronized (processedNotifier) { subscriber.startSubscriptions(); processedNotifier.wait(5000); } verify(shardConsumer, times(100)).handleInput(any(ProcessRecordsInput.class), any(Subscription.class)); }
#vulnerable code @Test public void multipleItemTest() throws Exception { addItemsToReturn(100); setupNotifierAnswer(recordsPublisher.responses.size()); synchronized (processedNotifier) { subscriber.startSubscriptions(); processedNotifier.wait(5000); } verify(shardConsumer, times(100)).handleInput(argThat(eqProcessRecordsInput(processRecordsInput)), any(Subscription.class)); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = IllegalStateException.class) public void testGetNextRecordsWithoutStarting() { verify(executorService, times(0)).execute(any()); getRecordsCache.pollNextResultAndUpdatePrefetchCounters(); }
#vulnerable code @Test(expected = IllegalStateException.class) public void testGetNextRecordsWithoutStarting() { verify(executorService, times(0)).execute(any()); getRecordsCache.getNextResult(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = IllegalStateException.class) public void testCallAfterShutdown() { when(executorService.isShutdown()).thenReturn(true); getRecordsCache.drainQueueForRequests(); }
#vulnerable code @Test(expected = IllegalStateException.class) public void testCallAfterShutdown() { when(executorService.isShutdown()).thenReturn(true); getRecordsCache.pollNextResultAndUpdatePrefetchCounters(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void consumerErrorSkipsEntryTest() throws Exception { addItemsToReturn(20); Throwable testException = new Throwable("ShardConsumerError"); doAnswer(new Answer() { int expectedInvocations = recordsPublisher.responses.size(); @Override public Object answer(InvocationOnMock invocation) throws Throwable { expectedInvocations--; if (expectedInvocations == 10) { throw testException; } if (expectedInvocations <= 0) { synchronized (processedNotifier) { processedNotifier.notifyAll(); } } return null; } }).when(shardConsumer).handleInput(any(ProcessRecordsInput.class), any(Subscription.class)); synchronized (processedNotifier) { subscriber.startSubscriptions(); processedNotifier.wait(5000); } assertThat(subscriber.getAndResetDispatchFailure(), equalTo(testException)); assertThat(subscriber.getAndResetDispatchFailure(), nullValue()); verify(shardConsumer, times(20)).handleInput(any(ProcessRecordsInput.class), any(Subscription.class)); }
#vulnerable code @Test public void consumerErrorSkipsEntryTest() throws Exception { addItemsToReturn(20); Throwable testException = new Throwable("ShardConsumerError"); doAnswer(new Answer() { int expectedInvocations = recordsPublisher.responses.size(); @Override public Object answer(InvocationOnMock invocation) throws Throwable { expectedInvocations--; if (expectedInvocations == 10) { throw testException; } if (expectedInvocations <= 0) { synchronized (processedNotifier) { processedNotifier.notifyAll(); } } return null; } }).when(shardConsumer).handleInput(any(ProcessRecordsInput.class), any(Subscription.class)); synchronized (processedNotifier) { subscriber.startSubscriptions(); processedNotifier.wait(5000); } assertThat(subscriber.getAndResetDispatchFailure(), equalTo(testException)); assertThat(subscriber.getAndResetDispatchFailure(), nullValue()); verify(shardConsumer, times(20)).handleInput(argThat(eqProcessRecordsInput(processRecordsInput)), any(Subscription.class)); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout = 10000L) public void testNoDeadlockOnFullQueue() { // // Fixes https://github.com/awslabs/amazon-kinesis-client/issues/448 // // This test is to verify that the drain of a blocked queue no longer deadlocks. // If the test times out before starting the subscriber it means something went wrong while filling the queue. // After the subscriber is started one of the things that can trigger a timeout is a deadlock. // final int[] sequenceNumberInResponse = { 0 }; when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenAnswer( i -> GetRecordsResponse.builder().records( Record.builder().data(SdkBytes.fromByteArray(new byte[] { 1, 2, 3 })).sequenceNumber(++sequenceNumberInResponse[0] + "").build()) .nextShardIterator(NEXT_SHARD_ITERATOR).build()); getRecordsCache.start(sequenceNumber, initialPosition); // // Wait for the queue to fill up, and the publisher to block on adding items to the queue. // log.info("Waiting for queue to fill up"); while (getRecordsCache.getPublisherSession().prefetchRecordsQueue().size() < MAX_SIZE) { Thread.yield(); } log.info("Queue is currently at {} starting subscriber", getRecordsCache.getPublisherSession().prefetchRecordsQueue().size()); AtomicInteger receivedItems = new AtomicInteger(0); final int expectedItems = MAX_SIZE * 10; Object lock = new Object(); final boolean[] isRecordNotInorder = { false }; final String[] recordNotInOrderMessage = { "" }; Subscriber<RecordsRetrieved> delegateSubscriber = new Subscriber<RecordsRetrieved>() { Subscription sub; int receivedSeqNum = 0; @Override public void onSubscribe(Subscription s) { sub = s; s.request(1); } @Override public void onNext(RecordsRetrieved recordsRetrieved) { receivedItems.incrementAndGet(); if (Integer.parseInt(((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved) .lastBatchSequenceNumber()) != ++receivedSeqNum) { isRecordNotInorder[0] = true; recordNotInOrderMessage[0] = "Expected : " + receivedSeqNum + " Actual : " + ((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved) .lastBatchSequenceNumber(); } if (receivedItems.get() >= expectedItems) { synchronized (lock) { log.info("Notifying waiters"); lock.notifyAll(); } sub.cancel(); } else { sub.request(1); } } @Override public void onError(Throwable t) { log.error("Caught error", t); throw new RuntimeException(t); } @Override public void onComplete() { fail("onComplete not expected in this test"); } }; Subscriber<RecordsRetrieved> subscriber = new ShardConsumerNotifyingSubscriber(delegateSubscriber, getRecordsCache); synchronized (lock) { log.info("Awaiting notification"); Flowable.fromPublisher(getRecordsCache).subscribeOn(Schedulers.computation()) .observeOn(Schedulers.computation(), true, 8).subscribe(subscriber); try { lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } verify(getRecordsRetrievalStrategy, atLeast(expectedItems)).getRecords(anyInt()); assertThat(receivedItems.get(), equalTo(expectedItems)); assertFalse(recordNotInOrderMessage[0], isRecordNotInorder[0]); }
#vulnerable code @Test(timeout = 10000L) public void testNoDeadlockOnFullQueue() { // // Fixes https://github.com/awslabs/amazon-kinesis-client/issues/448 // // This test is to verify that the drain of a blocked queue no longer deadlocks. // If the test times out before starting the subscriber it means something went wrong while filling the queue. // After the subscriber is started one of the things that can trigger a timeout is a deadlock. // final int[] sequenceNumberInResponse = { 0 }; when(getRecordsRetrievalStrategy.getRecords(anyInt())).thenAnswer( i -> GetRecordsResponse.builder().records( Record.builder().data(SdkBytes.fromByteArray(new byte[] { 1, 2, 3 })).sequenceNumber(++sequenceNumberInResponse[0] + "").build()) .nextShardIterator(NEXT_SHARD_ITERATOR).build()); getRecordsCache.start(sequenceNumber, initialPosition); // // Wait for the queue to fill up, and the publisher to block on adding items to the queue. // log.info("Waiting for queue to fill up"); while (getRecordsCache.getPublisherSession().prefetchRecordsQueue().size() < MAX_SIZE) { Thread.yield(); } log.info("Queue is currently at {} starting subscriber", getRecordsCache.getPublisherSession().prefetchRecordsQueue().size()); AtomicInteger receivedItems = new AtomicInteger(0); final int expectedItems = MAX_SIZE * 10; Object lock = new Object(); final boolean[] isRecordNotInorder = { false }; final String[] recordNotInOrderMessage = { "" }; Subscriber<RecordsRetrieved> delegateSubscriber = new Subscriber<RecordsRetrieved>() { Subscription sub; int receivedSeqNum = 0; @Override public void onSubscribe(Subscription s) { sub = s; s.request(1); } @Override public void onNext(RecordsRetrieved recordsRetrieved) { receivedItems.incrementAndGet(); if (Integer.parseInt(((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved) .lastBatchSequenceNumber()) != ++receivedSeqNum) { isRecordNotInorder[0] = true; recordNotInOrderMessage[0] = "Expected : " + receivedSeqNum + " Actual : " + ((PrefetchRecordsPublisher.PrefetchRecordsRetrieved) recordsRetrieved) .lastBatchSequenceNumber(); } if (receivedItems.get() >= expectedItems) { synchronized (lock) { log.info("Notifying waiters"); lock.notifyAll(); } sub.cancel(); } else { sub.request(1); } } @Override public void onError(Throwable t) { log.error("Caught error", t); throw new RuntimeException(t); } @Override public void onComplete() { fail("onComplete not expected in this test"); } }; Subscriber<RecordsRetrieved> subscriber = new ShardConsumerNotifyingSubscriber(delegateSubscriber, getRecordsCache); synchronized (lock) { log.info("Awaiting notification"); Flowable.fromPublisher(getRecordsCache).subscribeOn(Schedulers.computation()) .observeOn(Schedulers.computation(), true, 8).subscribe(subscriber); try { lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } } verify(getRecordsRetrievalStrategy, atLeast(expectedItems)).getRecords(anyInt()); assertThat(receivedItems.get(), equalTo(expectedItems)); assertFalse(recordNotInOrderMessage[0], isRecordNotInorder[0]); } #location 80 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if (shutdown) { return; } try { initialize(); LOG.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e1) { LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1); shutdown(); } while (!shouldShutdown()) { runProcessLoop(); } finalShutdown(); LOG.info("Worker loop is complete. Exiting from worker."); }
#vulnerable code public void run() { if (shutdown) { return; } try { initialize(); LOG.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e1) { LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1); shutdown(); } while (!shouldShutdown()) { try { boolean foundCompletedShard = false; Set<ShardInfo> assignedShards = new HashSet<ShardInfo>(); for (ShardInfo shardInfo : getShardInfoForAssignments()) { ShardConsumer shardConsumer = createOrGetShardConsumer(shardInfo, recordProcessorFactory); if (shardConsumer.isShutdown() && shardConsumer.getShutdownReason().equals(ShutdownReason.TERMINATE)) { foundCompletedShard = true; } else { shardConsumer.consumeShard(); } assignedShards.add(shardInfo); } if (foundCompletedShard) { controlServer.syncShardAndLeaseInfo(null); } // clean up shard consumers for unassigned shards cleanupShardConsumers(assignedShards); wlog.info("Sleeping ..."); Thread.sleep(idleTimeInMilliseconds); } catch (Exception e) { LOG.error(String.format("Worker.run caught exception, sleeping for %s milli seconds!", String.valueOf(idleTimeInMilliseconds)), e); try { Thread.sleep(idleTimeInMilliseconds); } catch (InterruptedException ex) { LOG.info("Worker: sleep interrupted after catching exception ", ex); } } wlog.resetInfoLogging(); } finalShutdown(); LOG.info("Worker loop is complete. Exiting from worker."); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @RequestMapping("/error") @ResponseStatus(HttpStatus.OK) public Result<String> error() { RequestContext ctx = RequestContext.getCurrentContext(); Throwable throwable = ctx.getThrowable(); if(null != throwable && throwable instanceof ZuulException ){ ZuulException e = (ZuulException) ctx.getThrowable(); return Result.error(e.nStatusCode, e.errorCause); } return Result.error(ResultEnum.ERROR); }
#vulnerable code @RequestMapping("/error") @ResponseStatus(HttpStatus.OK) public Result<String> error() { RequestContext ctx = RequestContext.getCurrentContext(); Throwable throwable = ctx.getThrowable(); if(null != throwable && throwable instanceof ZuulException ){ ZuulException e = (ZuulException) ctx.getThrowable(); return Result.error(e.nStatusCode, e.errorCause); } return Result.error(99,throwable.getMessage()); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() throws Exception { for (int i = 0; i < 5; i++) { SpecCaptcha specCaptcha = new SpecCaptcha(); //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); System.out.println(specCaptcha.text()); //specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png"))); } }
#vulnerable code @Test public void test() throws Exception { for (int i = 0; i < 5; i++) { SpecCaptcha specCaptcha = new SpecCaptcha(); //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); System.out.println(specCaptcha.text()); specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png"))); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() throws Exception { SpecCaptcha specCaptcha = new SpecCaptcha(); System.out.println(specCaptcha.text()); //specCaptcha.out(new FileOutputStream(new File("D:/a/aa.png"))); }
#vulnerable code @Test public void test() throws Exception { SpecCaptcha specCaptcha = new SpecCaptcha(); System.out.println(specCaptcha.text()); specCaptcha.out(new FileOutputStream(new File("D:/a/aa.png"))); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testHan() throws Exception { ChineseCaptcha chineseCaptcha = new ChineseCaptcha(); //chineseCaptcha.setFont(new Font("微软雅黑", Font.PLAIN, 25)); System.out.println(chineseCaptcha.text()); //chineseCaptcha.out(new FileOutputStream(new File("D:/Java/aa.png"))); }
#vulnerable code @Test public void testHan() throws Exception { ChineseCaptcha chineseCaptcha = new ChineseCaptcha(); //chineseCaptcha.setFont(new Font("微软雅黑", Font.PLAIN, 25)); System.out.println(chineseCaptcha.text()); chineseCaptcha.out(new FileOutputStream(new File("D:/Java/aa.png"))); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() throws Exception { for (int i = 0; i < 5; i++) { SpecCaptcha specCaptcha = new SpecCaptcha(); //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); System.out.println(specCaptcha.text()); //specCaptcha.out(new FileOutputStream(new File("C:/aa" + i + ".png"))); } }
#vulnerable code @Test public void test() throws Exception { for (int i = 0; i < 100; i++) { SpecCaptcha specCaptcha = new SpecCaptcha(); specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); System.out.println(specCaptcha.text()); specCaptcha.out(new FileOutputStream(new File("D:/a/aa" + i + ".png"))); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code void link(final Linkage linkage) throws ModuleLoadException { final HashMap<String, List<LocalLoader>> importsMap = new HashMap<String, List<LocalLoader>>(); final HashMap<String, List<LocalLoader>> exportsMap = new HashMap<String, List<LocalLoader>>(); final Dependency[] dependencies = linkage.getSourceList(); final long start = Metrics.getCurrentCPUTime(); try { addPaths(dependencies, importsMap); addExportedPaths(dependencies, exportsMap); synchronized (this) { if (this.linkage == linkage) { this.linkage = new Linkage(linkage.getSourceList(), Linkage.State.LINKED, importsMap, exportsMap); notifyAll(); } // else all our efforts were just wasted since someone changed the deps in the meantime } } finally { moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static FactoryPermissionCollection parsePermissionsXml(final InputStream inputStream, ModuleLoader moduleLoader, final String moduleName) throws XmlPullParserException, IOException { final MXParser mxParser = new MXParser(); mxParser.setFeature(FEATURE_PROCESS_NAMESPACES, true); mxParser.setInput(inputStream, null); return parsePermissionsXml(mxParser, moduleLoader, moduleName); }
#vulnerable code public static FactoryPermissionCollection parsePermissionsXml(final InputStream inputStream, ModuleLoader moduleLoader, final String moduleName) throws XmlPullParserException, IOException { final MXParser mxParser = new MXParser(); mxParser.setInput(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); return parsePermissionsXml(mxParser, moduleLoader, moduleName); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException { long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); filterStack.add(importFilter); subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); filterStack.remove(importFilter); } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); final PathFilter importFilter = classLoaderDependency.getImportFilter(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { if (importFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>()); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; final LocalLoader localLoader = localDependency.getLocalLoader(); final PathFilter importFilter = localDependency.getImportFilter(); final Set<String> paths = localDependency.getPaths(); for (String path : paths) { if (importFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>()); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } return subtract; } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code Map<String, List<LocalLoader>> getPaths(final boolean exports) throws ModuleLoadException { Linkage linkage = this.linkage; Linkage.State state = linkage.getState(); if (state.compareTo(exports ? LINKED_EXPORTS : LINKED) >= 0) { return linkage.getPaths(exports); } // slow path loop boolean intr = false; try { for (;;) { synchronized (this) { linkage = this.linkage; state = linkage.getState(); while (state == (exports ? LINKING_EXPORTS : LINKING) || state == NEW) try { wait(); linkage = this.linkage; state = linkage.getState(); } catch (InterruptedException e) { intr = true; } if (state == (exports ? LINKED_EXPORTS : LINKED)) { return linkage.getPaths(exports); } this.linkage = linkage = new Linkage(linkage.getSourceList(), exports ? LINKING_EXPORTS : LINKING); // fall out and link } if (exports) { linkExports(linkage); } else { link(linkage); } } } finally { if (intr) { Thread.currentThread().interrupt(); } } } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ModuleLoader forClass(Class<?> clazz) { final Module module = Module.forClass(clazz); if (module == null) { return null; } return module.getModuleLoader(); }
#vulnerable code public static ModuleLoader forClass(Class<?> clazz) { return Module.forClass(clazz).getModuleLoader(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code void linkIfNecessary() throws ModuleLoadException { Linkage linkage = this.linkage; if (linkage.getState().compareTo(LINKING) >= 0) { return; } synchronized (this) { linkage = this.linkage; if (linkage.getState().compareTo(LINKING) >= 0) { return; } this.linkage = linkage = new Linkage(linkage.getSourceList(), LINKING); } link(linkage); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) { this.moduleLoader = moduleLoader; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; final Map<String, String> properties = spec.getProperties(); this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties); }
#vulnerable code long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException { if (!visited.add(new Visited(this, filterStack, classFilterStack, resourceFilterStack))) { return 0L; } long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { final PathFilter exportFilter = dependency.getExportFilter(); // skip non-exported dependencies altogether if (exportFilter != PathFilters.rejectAll()) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); final FastCopyHashSet<PathFilter> nestedFilters; final FastCopyHashSet<ClassFilter> nestedClassFilters; final FastCopyHashSet<PathFilter> nestedResourceFilters; if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { nestedFilters = filterStack; } else { nestedFilters = filterStack.clone(); nestedFilters.add(importFilter); nestedFilters.add(exportFilter); } final ClassFilter classImportFilter = dependency.getClassImportFilter(); final ClassFilter classExportFilter = dependency.getClassExportFilter(); if ((classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) && (classExportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classExportFilter))) { nestedClassFilters = classFilterStack; } else { nestedClassFilters = classFilterStack.clone(); if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter); if (classExportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classExportFilter); } final PathFilter resourceImportFilter = dependency.getResourceImportFilter(); final PathFilter resourceExportFilter = dependency.getResourceExportFilter(); if ((resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) && (resourceExportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceExportFilter))) { nestedResourceFilters = resourceFilterStack; } else { nestedResourceFilters = resourceFilterStack.clone(); if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter); if (resourceExportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceExportFilter); } subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited); } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; LocalLoader localLoader = classLoaderDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classImportFilter = classLoaderDependency.getClassImportFilter(); if (classImportFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classImportFilter, localLoader); } ClassFilter classExportFilter = classLoaderDependency.getClassExportFilter(); if (classExportFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classExportFilter, localLoader); } PathFilter resourceImportFilter = classLoaderDependency.getResourceImportFilter(); if (resourceImportFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceImportFilter, localLoader); } PathFilter resourceExportFilter = classLoaderDependency.getResourceExportFilter(); if (resourceExportFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceExportFilter, localLoader); } final PathFilter importFilter = classLoaderDependency.getImportFilter(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && importFilter.accept(path) && exportFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; LocalLoader localLoader = localDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classFilter = localDependency.getClassExportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } classFilter = localDependency.getClassImportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } PathFilter resourceFilter = localDependency.getResourceExportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } resourceFilter = localDependency.getResourceImportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } final Set<String> paths = localDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } } return subtract; } #location 64 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException { long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); filterStack.add(importFilter); subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); filterStack.remove(importFilter); } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); final PathFilter importFilter = classLoaderDependency.getImportFilter(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { if (importFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>()); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; final LocalLoader localLoader = localDependency.getLocalLoader(); final PathFilter importFilter = localDependency.getImportFilter(); final Set<String> paths = localDependency.getPaths(); for (String path : paths) { if (importFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>()); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } return subtract; } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException { if (!visited.add(new Visited(this, filterStack))) { return 0L; } long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { final PathFilter exportFilter = dependency.getExportFilter(); // skip non-exported dependencies altogether if (exportFilter != PathFilters.rejectAll()) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); } else { final FastCopyHashSet<PathFilter> clone = filterStack.clone(); clone.add(importFilter); clone.add(exportFilter); subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited); } } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; final LocalLoader localLoader = localDependency.getLocalLoader(); final Set<String> paths = localDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } } return subtract; } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name)); if (fp == null) return null; JarFile jarFile = JDKSpecific.getJarFile(fp, true); return ResourceLoaders.createJarResourceLoader(name, jarFile); }
#vulnerable code public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name)); if (fp == null) return null; JarFile jarFile = new JarFile(fp, true); return ResourceLoaders.createJarResourceLoader(name, jarFile); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) { this.moduleLoader = moduleLoader; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; final Map<String, String> properties = spec.getProperties(); this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties); }
#vulnerable code long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException { if (!visited.add(new Visited(this, filterStack, classFilterStack, resourceFilterStack))) { return 0L; } long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { final PathFilter exportFilter = dependency.getExportFilter(); // skip non-exported dependencies altogether if (exportFilter != PathFilters.rejectAll()) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); final FastCopyHashSet<PathFilter> nestedFilters; final FastCopyHashSet<ClassFilter> nestedClassFilters; final FastCopyHashSet<PathFilter> nestedResourceFilters; if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { nestedFilters = filterStack; } else { nestedFilters = filterStack.clone(); nestedFilters.add(importFilter); nestedFilters.add(exportFilter); } final ClassFilter classImportFilter = dependency.getClassImportFilter(); final ClassFilter classExportFilter = dependency.getClassExportFilter(); if ((classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) && (classExportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classExportFilter))) { nestedClassFilters = classFilterStack; } else { nestedClassFilters = classFilterStack.clone(); if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter); if (classExportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classExportFilter); } final PathFilter resourceImportFilter = dependency.getResourceImportFilter(); final PathFilter resourceExportFilter = dependency.getResourceExportFilter(); if ((resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) && (resourceExportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceExportFilter))) { nestedResourceFilters = resourceFilterStack; } else { nestedResourceFilters = resourceFilterStack.clone(); if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter); if (resourceExportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceExportFilter); } subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited); } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; LocalLoader localLoader = classLoaderDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classImportFilter = classLoaderDependency.getClassImportFilter(); if (classImportFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classImportFilter, localLoader); } ClassFilter classExportFilter = classLoaderDependency.getClassExportFilter(); if (classExportFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classExportFilter, localLoader); } PathFilter resourceImportFilter = classLoaderDependency.getResourceImportFilter(); if (resourceImportFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceImportFilter, localLoader); } PathFilter resourceExportFilter = classLoaderDependency.getResourceExportFilter(); if (resourceExportFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceExportFilter, localLoader); } final PathFilter importFilter = classLoaderDependency.getImportFilter(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && importFilter.accept(path) && exportFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; LocalLoader localLoader = localDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classFilter = localDependency.getClassExportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } classFilter = localDependency.getClassImportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } PathFilter resourceFilter = localDependency.getResourceExportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } resourceFilter = localDependency.getResourceImportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } final Set<String> paths = localDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } } return subtract; } #location 65 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code void relinkIfNecessary() throws ModuleLoadException { Linkage linkage = this.linkage; if (linkage.getState() != Linkage.State.UNLINKED) { return; } synchronized (this) { linkage = this.linkage; if (linkage.getState() != Linkage.State.UNLINKED) { return; } this.linkage = linkage = new Linkage(linkage.getSourceList(), Linkage.State.LINKING); } link(linkage); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException { if (!visited.add(new Visited(this, filterStack))) { return 0L; } long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { final PathFilter exportFilter = dependency.getExportFilter(); // skip non-exported dependencies altogether if (exportFilter != PathFilters.rejectAll()) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); } else { final FastCopyHashSet<PathFilter> clone = filterStack.clone(); clone.add(importFilter); clone.add(exportFilter); subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited); } } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; final LocalLoader localLoader = localDependency.getLocalLoader(); final Set<String> paths = localDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } } return subtract; } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, Set<Visited> visited) throws ModuleLoadException { if (!visited.add(new Visited(this, filterStack))) { return 0L; } long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { final PathFilter exportFilter = dependency.getExportFilter(); // skip non-exported dependencies altogether if (exportFilter != PathFilters.rejectAll()) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); } else { final FastCopyHashSet<PathFilter> clone = filterStack.clone(); clone.add(importFilter); clone.add(exportFilter); subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited); } } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; final LocalLoader localLoader = localDependency.getLocalLoader(); final Set<String> paths = localDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } } return subtract; } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) { this.moduleLoader = moduleLoader; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; final Map<String, String> properties = spec.getProperties(); this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties); }
#vulnerable code long addPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException { long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); final FastCopyHashSet<PathFilter> nestedFilters; final FastCopyHashSet<ClassFilter> nestedClassFilters; final FastCopyHashSet<PathFilter> nestedResourceFilters; if (filterStack.contains(importFilter)) { nestedFilters = filterStack; } else { nestedFilters = filterStack.clone(); nestedFilters.add(importFilter); } final ClassFilter classImportFilter = dependency.getClassImportFilter(); if (classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) { nestedClassFilters = classFilterStack; } else { nestedClassFilters = classFilterStack.clone(); if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter); } final PathFilter resourceImportFilter = dependency.getResourceImportFilter(); if (resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) { nestedResourceFilters = resourceFilterStack; } else { nestedResourceFilters = resourceFilterStack.clone(); if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter); } subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited); } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; LocalLoader localLoader = classLoaderDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classFilter = classLoaderDependency.getClassImportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } PathFilter resourceFilter = classLoaderDependency.getResourceImportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } final PathFilter importFilter = classLoaderDependency.getImportFilter(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { if (importFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>()); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; LocalLoader localLoader = localDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } final ClassFilter classFilter = localDependency.getClassImportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } final PathFilter resourceFilter = localDependency.getResourceImportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } final PathFilter importFilter = localDependency.getImportFilter(); final Set<String> paths = localDependency.getPaths(); for (String path : paths) { if (importFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>()); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } return subtract; } #location 54 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
#vulnerable code Class<?> loadModuleClass(final String className, final boolean exportsOnly, final boolean resolve) { for (String s : systemPackages) { if (className.startsWith(s)) { try { return moduleClassLoader.loadClass(className, resolve); } catch (ClassNotFoundException e) { return null; } } } final String path = pathOfClass(className); final Map<String, List<LocalLoader>> paths = getPathsUnchecked(exportsOnly); final List<LocalLoader> loaders = paths.get(path); if (loaders != null) { Class<?> clazz; for (LocalLoader loader : loaders) { clazz = loader.loadClassLocal(className, resolve); if (clazz != null) { return clazz; } } } final LocalLoader fallbackLoader = this.fallbackLoader; if (fallbackLoader != null) { return fallbackLoader.loadClassLocal(className, resolve); } return null; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSnapshotResolving()throws Exception{ ArtifactCoordinates coordinates = ArtifactCoordinates.fromString("org.wildfly.core:wildfly-version:2.0.5.Final-20151222.144931-1"); String path = MavenArtifactUtil.relativeArtifactPath('/', coordinates); Assert.assertEquals("org/wildfly/core/wildfly-version/2.0.5.Final-SNAPSHOT/wildfly-version-2.0.5.Final-20151222.144931-1", path); }
#vulnerable code @Test public void testSnapshotResolving()throws Exception{ ArtifactCoordinates coordinates = ArtifactCoordinates.fromString("org.wildfly.core:wildfly-version:2.0.5.Final-20151222.144931-1"); String path = MavenArtifactUtil.relativeArtifactPath('/', coordinates.getGroupId(), coordinates.getArtifactId(), coordinates.getVersion()); Assert.assertEquals("org/wildfly/core/wildfly-version/2.0.5.Final-SNAPSHOT/wildfly-version-2.0.5.Final-20151222.144931-1", path); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; BufferedReader in = null; try { in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore ... any errors should already have been // reported via an IOException from the final flush. } } } return lines; }
#vulnerable code public List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; try { BufferedReader in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); fail(e.getMessage()); } return lines; } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) { Comparison.Detail controlDetails = comparison.getControlDetails(); Node controlTarget = controlDetails.getTarget(); Comparison.Detail testDetails = comparison.getTestDetails(); Node testTarget = testDetails.getTarget(); // comparing textual content of elements if (comparison.getType() == ComparisonType.TEXT_VALUE) { return evaluateConsideringPlaceholders((String) controlDetails.getValue(), (String) testDetails.getValue(), outcome); // two versions of "test document has no text-like node but control document has" } else if (comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH && Integer.valueOf(1).equals(controlDetails.getValue()) && Integer.valueOf(0).equals(testDetails.getValue()) && isTextLikeNode(controlTarget.getFirstChild().getNodeType())) { String controlNodeChildValue = controlTarget.getFirstChild().getNodeValue(); return evaluateConsideringPlaceholders(controlNodeChildValue, null, outcome); } else if (comparison.getType() == ComparisonType.CHILD_LOOKUP && controlTarget != null && isTextLikeNode(controlTarget.getNodeType())) { String controlNodeValue = controlTarget.getNodeValue(); return evaluateConsideringPlaceholders(controlNodeValue, null, outcome); // may be comparing TEXT to CDATA } else if (comparison.getType() == ComparisonType.NODE_TYPE && isTextLikeNode(controlTarget.getNodeType()) && isTextLikeNode(testTarget.getNodeType())) { return evaluateConsideringPlaceholders(controlTarget.getNodeValue(), testTarget.getNodeValue(), outcome); // comparing textual content of attributes } else if (comparison.getType() == ComparisonType.ATTR_VALUE) { return evaluateConsideringPlaceholders((String) controlDetails.getValue(), (String) testDetails.getValue(), outcome); // two versions of "test document has no attribute but control document has" } else if (comparison.getType() == ComparisonType.ELEMENT_NUM_ATTRIBUTES) { Map<QName, String> controlAttrs = Nodes.getAttributes(controlTarget); Map<QName, String> testAttrs = Nodes.getAttributes(testTarget); int cAttrsMatched = 0; for (Map.Entry<QName, String> cAttr : controlAttrs.entrySet()) { String testValue = testAttrs.get(cAttr.getKey()); if (testValue == null) { ComparisonResult o = evaluateConsideringPlaceholders(cAttr.getValue(), null, outcome); if (o != ComparisonResult.EQUAL) { return outcome; } } else { cAttrsMatched++; } } if (cAttrsMatched != testAttrs.size()) { // there are unmatched test attributes return outcome; } return ComparisonResult.EQUAL; } else if (comparison.getType() == ComparisonType.ATTR_NAME_LOOKUP && controlTarget != null && controlDetails.getValue() != null) { String controlAttrValue = Nodes.getAttributes(controlTarget).get((QName) controlDetails.getValue()); return evaluateConsideringPlaceholders(controlAttrValue, null, outcome); // default, don't apply any placeholders at all } else { return outcome; } }
#vulnerable code public ComparisonResult evaluate(Comparison comparison, ComparisonResult outcome) { Comparison.Detail controlDetails = comparison.getControlDetails(); Node controlTarget = controlDetails.getTarget(); Comparison.Detail testDetails = comparison.getTestDetails(); Node testTarget = testDetails.getTarget(); // comparing textual content of elements if (comparison.getType() == ComparisonType.TEXT_VALUE) { return evaluateConsideringPlaceholders((String) controlDetails.getValue(), (String) testDetails.getValue(), outcome); // two possible cases of "test document has no text-like node but control document has" } else if (comparison.getType() == ComparisonType.CHILD_NODELIST_LENGTH && Integer.valueOf(1).equals(controlDetails.getValue()) && Integer.valueOf(0).equals(testDetails.getValue()) && isTextLikeNode(controlTarget.getFirstChild().getNodeType())) { String controlNodeChildValue = controlTarget.getFirstChild().getNodeValue(); return evaluateConsideringPlaceholders(controlNodeChildValue, null, outcome); } else if (comparison.getType() == ComparisonType.CHILD_LOOKUP && controlTarget != null && isTextLikeNode(controlTarget.getNodeType())) { String controlNodeValue = controlTarget.getNodeValue(); return evaluateConsideringPlaceholders(controlNodeValue, null, outcome); // may be comparing TEXT to CDATA } else if (comparison.getType() == ComparisonType.NODE_TYPE && isTextLikeNode(controlTarget.getNodeType()) && isTextLikeNode(testTarget.getNodeType())) { return evaluateConsideringPlaceholders(controlTarget.getNodeValue(), testTarget.getNodeValue(), outcome); // default, don't apply any placeholders at all } else { return outcome; } } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public NodeAssert hasAttribute(String attributeName, String attributeValue) { isNotNull(); final Map.Entry<QName, String> attribute = attributeForName(attributeName); if (attribute == null || !attribute.getValue().equals(attributeValue)) { throwAssertionError(shouldHaveAttributeWithValue(actual.getNodeName(), attributeName, attributeValue)); } return this; }
#vulnerable code public NodeAssert hasAttribute(String attributeName, String attributeValue) { isNotNull(); final Map.Entry<QName, String> attribute = requestAttributeForName(attributeName); if (!attribute.getValue().equals(attributeValue)) { throwAssertionError(shouldHaveAttributeWithValue(actual, attributeName, attributeValue)); } return this; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void sendSecureMessage( final AsyncWrite msg, final SecurityToken token, final int requestId, final int messageType, final AtomicInteger sendSequenceNumber ) { assert(token!=null); ByteBuffer chunks[], plaintexts[]; boolean concurrent; try { synchronized(msg) { if (msg.isCanceled()) return; msg.setQueued(); } //Probably more efficient to check isTraceEnabled before executing ObjectUtils.printFieldsDeep if (logger.isTraceEnabled()) logger.trace("sendSecureMessage: " + ObjectUtils.printFieldsDeep(msg.getMessage())); EncoderCalc calc = new EncoderCalc(); calc.setEncoderContext(encoderCtx); calc.putMessage(msg.getMessage()); int len = calc.getLength(); if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); SecurityPolicy policy = token.getSecurityPolicy(); MessageSecurityMode mode = token.getMessageSecurityMode(); SecurityAlgorithm symmEncryptAlgo = policy.getSymmetricEncryptionAlgorithm(); SecurityAlgorithm symmSignAlgo = policy.getSymmetricSignatureAlgorithm(); int cipherBlockSize = CryptoUtil.getCipherBlockSize(symmEncryptAlgo, null); int signatureSize = CryptoUtil.getSignatureSize(symmSignAlgo, null); int keySize = mode == MessageSecurityMode.SignAndEncrypt ? token.getRemoteEncryptingKey().length : 0; int paddingSize = mode == MessageSecurityMode.SignAndEncrypt ? keySize > 2048 ? 2 : 1 : 0; int maxPlaintextSize = ctx.maxSendChunkSize - 24 - paddingSize - signatureSize; maxPlaintextSize -= (maxPlaintextSize + paddingSize + signatureSize + 8) % cipherBlockSize; final int CORES = StackUtils.cores(); int optimalPayloadSize = (len+CORES-1) / CORES; if (optimalPayloadSize > maxPlaintextSize) optimalPayloadSize = maxPlaintextSize; if (optimalPayloadSize < 4096) optimalPayloadSize = 4096; int optimalChunkSize = optimalPayloadSize + 24 + paddingSize + signatureSize; ChunkFactory cf = new ChunkFactory( optimalChunkSize, 8, 8, 8, signatureSize, cipherBlockSize, mode, keySize); // Calculate chunk count final int count = (len + cf.maxPlaintextSize-1) / cf.maxPlaintextSize; if (count>ctx.maxSendChunkCount && ctx.maxSendChunkCount!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); concurrent = (count > 1) && (CORES>0) && (mode != MessageSecurityMode.None); // Allocate chunks int bytesLeft = len; plaintexts = new ByteBuffer[count]; chunks = new ByteBuffer[count]; for (int i=0; i<count; i++) { plaintexts[i] = cf.allocate(bytesLeft); chunks[i] = cf.expandToCompleteChunk(plaintexts[i]); bytesLeft -= plaintexts[i].remaining(); } assert(bytesLeft==0); // Start write synchronized(msg) { if (msg.isCanceled()) return; msg.setWriting(); } } catch (ServiceResultException se) { msg.setError(se); return; } final ByteBuffer _chunks[] = chunks; final ByteBuffer _plaintexts[] = plaintexts; final int count = chunks.length; final boolean parallel = concurrent; int sequenceNumber = 0; synchronized(this) { sequenceNumber = sendSequenceNumber.getAndAdd(chunks.length); startChunkSend(chunks); } // Add chunk headers for (ByteBuffer chunk : chunks) { boolean finalChunk = chunk == chunks[chunks.length-1]; chunk.rewind(); chunk.putInt( messageType | (finalChunk ? TcpMessageType.FINAL : TcpMessageType.CONTINUE) ); chunk.position(8); chunk.putInt(token.getSecureChannelId()); // -- Security Header -- chunk.putInt(token.getTokenId()); // -- Sequence Header -- chunk.putInt(sequenceNumber++); chunk.putInt(requestId); } // a Chunk-has-been-encoded handler final AtomicInteger chunksComplete = new AtomicInteger(); ChunkListener completitionListener = new ChunkListener() { @Override public void onChunkComplete(ByteBuffer[] bufs, final int index) { Runnable action = new Runnable() { @Override public void run() { // Chunk contains message data, it needs to be encrypted and signed // try { // Encrypt & sign new ChunkSymmEncryptSigner(_chunks[index], _plaintexts[index], token).run(); _chunks[index].rewind(); // Write chunk endChunkSend(_chunks[index]); // All chunks are completed if (chunksComplete.incrementAndGet()==count) msg.setWritten(); // } catch (ServiceResultException se) { // msg.setError(se); // } }}; if (parallel && count>1) { StackUtils.getNonBlockingWorkExecutor().execute(action); } else { action.run(); } } }; // Create encoder ByteBufferArrayWriteable2 out = new ByteBufferArrayWriteable2(plaintexts, completitionListener); out.order(ByteOrder.LITTLE_ENDIAN); final BinaryEncoder enc = new BinaryEncoder(out); enc.setEncoderContext(encoderCtx); Runnable encoder = new Runnable() { @Override public void run() { try { enc.putMessage(msg.getMessage()); } catch (ServiceResultException e) { msg.setError( StackUtils.toServiceResultException(e) ); } }}; StackUtils.getBlockingWorkExecutor().execute(encoder); }
#vulnerable code @Override protected void sendSecureMessage( final AsyncWrite msg, final SecurityToken token, final int requestId, final int messageType, final AtomicInteger sendSequenceNumber ) { assert(token!=null); ByteBuffer chunks[], plaintexts[]; boolean concurrent; try { synchronized(msg) { if (msg.isCanceled()) return; msg.setQueued(); } //Probably more efficient to check isTraceEnabled before executing ObjectUtils.printFieldsDeep if (logger.isTraceEnabled()) logger.trace("sendSecureMessage: " + ObjectUtils.printFieldsDeep(msg.getMessage())); EncoderCalc calc = new EncoderCalc(); calc.setEncoderContext(encoderCtx); calc.putMessage(msg.getMessage()); int len = calc.getLength(); if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); SecurityPolicy policy = token.getSecurityPolicy(); MessageSecurityMode mode = token.getMessageSecurityMode(); SecurityAlgorithm symmEncryptAlgo = policy.getSymmetricEncryptionAlgorithm(); SecurityAlgorithm symmSignAlgo = policy.getSymmetricSignatureAlgorithm(); int cipherBlockSize = CryptoUtil.getCipherBlockSize(symmEncryptAlgo, null); int signatureSize = CryptoUtil.getSignatureSize(symmSignAlgo, null); int keySize = mode == MessageSecurityMode.SignAndEncrypt ? token.getRemoteEncryptingKey().length : 0; int paddingSize = mode == MessageSecurityMode.SignAndEncrypt ? keySize > 2048 ? 2 : 1 : 0; int maxPlaintextSize = ctx.maxSendChunkSize - 24 - paddingSize - signatureSize; maxPlaintextSize -= (maxPlaintextSize + paddingSize + signatureSize + 8) % cipherBlockSize; final int CORES = StackUtils.cores(); int optimalPayloadSize = (len+CORES-1) / CORES; if (optimalPayloadSize > maxPlaintextSize) optimalPayloadSize = maxPlaintextSize; if (optimalPayloadSize < 4096) optimalPayloadSize = 4096; int optimalChunkSize = optimalPayloadSize + 24 + paddingSize + signatureSize; ChunkFactory cf = new ChunkFactory( optimalChunkSize, 8, 8, 8, signatureSize, cipherBlockSize, mode, keySize); // Calculate chunk count final int count = (len + cf.maxPlaintextSize-1) / cf.maxPlaintextSize; if (count>ctx.maxSendChunkCount && ctx.maxSendChunkCount!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); concurrent = (count > 1) && (CORES>0) && (mode != MessageSecurityMode.None); // Allocate chunks int bytesLeft = len; plaintexts = new ByteBuffer[count]; chunks = new ByteBuffer[count]; for (int i=0; i<count; i++) { plaintexts[i] = cf.allocate(bytesLeft); chunks[i] = cf.expandToCompleteChunk(plaintexts[i]); bytesLeft -= plaintexts[i].remaining(); } assert(bytesLeft==0); // Start write synchronized(msg) { if (msg.isCanceled()) return; msg.setWriting(); } } catch (ServiceResultException se) { msg.setError(se); return; } final ByteBuffer _chunks[] = chunks; final ByteBuffer _plaintexts[] = plaintexts; final int count = chunks.length; final boolean parallel = concurrent; int sequenceNumber = 0; synchronized(this) { sequenceNumber = sendSequenceNumber.getAndAdd(chunks.length); startChunkSend(chunks); } // Add chunk headers for (ByteBuffer chunk : chunks) { boolean finalChunk = chunk == chunks[chunks.length-1]; chunk.rewind(); chunk.putInt( messageType | (finalChunk ? TcpMessageType.FINAL : TcpMessageType.CONTINUE) ); chunk.position(8); chunk.putInt(token.getSecureChannelId()); // -- Security Header -- chunk.putInt(token.getTokenId()); // -- Sequence Header -- chunk.putInt(sequenceNumber++); chunk.putInt(requestId); } // a Chunk-has-been-encoded handler final AtomicInteger chunksComplete = new AtomicInteger(); ChunkListener completitionListener = new ChunkListener() { @Override public void onChunkComplete(ByteBuffer[] bufs, final int index) { Runnable action = new Runnable() { @Override public void run() { // Chunk contains message data, it needs to be encrypted and signed // try { // Encrypt & sign new ChunkSymmEncryptSigner(_chunks[index], _plaintexts[index], token).run(); _chunks[index].rewind(); // Write chunk endChunkSend(_chunks[index]); // All chunks are completed if (chunksComplete.incrementAndGet()==count) msg.setWritten(); // } catch (ServiceResultException se) { // msg.setError(se); // } }}; if (parallel && count>1) { StackUtils.getNonBlockingWorkExecutor().execute(action); } else { action.run(); } } }; // Create encoder ByteBufferArrayWriteable2 out = new ByteBufferArrayWriteable2(plaintexts, completitionListener); out.order(ByteOrder.LITTLE_ENDIAN); final BinaryEncoder enc = new BinaryEncoder(out); enc.setEncoderContext(encoderCtx); enc.setEncoderMode(EncoderMode.NonStrict); Runnable encoder = new Runnable() { @Override public void run() { try { enc.putMessage(msg.getMessage()); } catch (ServiceResultException e) { msg.setError( StackUtils.toServiceResultException(e) ); } }}; StackUtils.getBlockingWorkExecutor().execute(encoder); } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void putDecimal(String fieldName, BigDecimal bd) throws EncodingException{ ExtensionObject eo = EncoderUtils.decimalToExtensionObject(bd); putExtensionObject(fieldName, eo); }
#vulnerable code private void putDecimal(String fieldName, BigDecimal bd) throws EncodingException{ int scaleInt = bd.scale(); if(scaleInt > Short.MAX_VALUE) { throw new EncodingException("Decimal scale overflow Short max value: "+scaleInt); } if(scaleInt < Short.MIN_VALUE) { throw new EncodingException("Decimal scale underflow Short min value: "+scaleInt); } short scale = (short)scaleInt; ByteBuffer bb = ByteBuffer.allocate(2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.putShort(scale); byte[] scalebytes = bb.array(); //NOTE BigInteger uses big-endian, and UA Decimal encoding uses little-endian byte[] valuebytes = EncoderUtils.reverse(bd.unscaledValue().toByteArray()); byte[] combined = EncoderUtils.concat(scalebytes, valuebytes); ExpandedNodeId id = new ExpandedNodeId(NamespaceTable.OPCUA_NAMESPACE, Identifiers.Decimal.getValue()); ExtensionObject eo = new ExtensionObject(id, combined); putExtensionObject(fieldName, eo); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void sendResponse(int statusCode, IEncodeable responseObject) { try { HttpResponse responseHandle = httpExchange.getResponse(); responseHandle.setHeader("Content-Type", "application/octet-stream"); responseHandle.setStatusCode( statusCode ); if ( responseObject != null ) { try { logger.trace("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject); logger.debug("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject.getClass().getSimpleName()); //Check isDebugEnabled() here for possible performance reasons. if (logger.isDebugEnabled() && channel.getConnection() != null) { NHttpServerConnection nHttpServerConnection = ((HttpsServerConnection) channel.getConnection()).getNHttpServerConnection(); logger.debug("sendResponse: timeout={} {} context={}", httpExchange.getTimeout(), nHttpServerConnection.getSocketTimeout(), nHttpServerConnection.getContext()); } ByteArrayOutputStream data = new ByteArrayOutputStream(); BinaryEncoder enc = new BinaryEncoder( data ); enc.setEncoderContext( endpoint.getEncoderContext() ); enc.putMessage( responseObject ); responseHandle.setEntity( new NByteArrayEntity(data.toByteArray()) ); } catch (EncodingException e) { logger.info("sendResponse: Encoding failed", e); // Internal Error if ( responseObject instanceof ErrorMessage == false ) { responseHandle.setStatusCode( 500 ); } } } logger.debug("sendResponse: {} length={}", responseHandle, responseHandle.getEntity().getContentLength()); httpExchange.submitResponse(new BasicAsyncResponseProducer(responseHandle)); } finally { endpoint.pendingRequests.remove(requestId); } }
#vulnerable code void sendResponse(int statusCode, IEncodeable responseObject) { try { HttpResponse responseHandle = httpExchange.getResponse(); responseHandle.setHeader("Content-Type", "application/octet-stream"); responseHandle.setStatusCode( statusCode ); if ( responseObject != null ) { try { logger.trace("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject); logger.debug("sendResponse: requestId={} statusCode={} responseObject={}", requestId, statusCode, responseObject.getClass().getSimpleName()); //Check isDebugEnabled() here for possible performance reasons. if (logger.isDebugEnabled() && channel.getConnection() != null) { NHttpServerConnection nHttpServerConnection = ((HttpsServerConnection) channel.getConnection()).getNHttpServerConnection(); logger.debug("sendResponse: timeout={} {} context={}", httpExchange.getTimeout(), nHttpServerConnection.getSocketTimeout(), nHttpServerConnection.getContext()); } SizeCalculationOutputStream tmp = new SizeCalculationOutputStream(); BinaryEncoder calc = new BinaryEncoder(tmp); calc.setEncoderContext( endpoint.getEncoderContext() ); calc.putMessage( responseObject ); int len = tmp.getLength(); byte[] data = new byte[ len ]; BinaryEncoder enc = new BinaryEncoder( data ); enc.setEncoderContext( endpoint.getEncoderContext() ); enc.putMessage( responseObject ); responseHandle.setEntity( new NByteArrayEntity(data) ); } catch (EncodingException e) { logger.info("sendResponse: Encoding failed", e); // Internal Error if ( responseObject instanceof ErrorMessage == false ) { responseHandle.setStatusCode( 500 ); } } } logger.debug("sendResponse: {} length={}", responseHandle, responseHandle.getEntity().getContentLength()); httpExchange.submitResponse(new BasicAsyncResponseProducer(responseHandle)); } finally { endpoint.pendingRequests.remove(requestId); } } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { try { // Abort exit branch if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode ) ); return; } // Http Post InetSocketAddress inetAddress = UriUtil.getSocketAddress( httpsClient.connectUrl ); String host = inetAddress.getHostName(); int port = inetAddress.getPort(); String scheme = UriUtil.getTransportProtocol( httpsClient.connectUrl ); HttpHost httpHost = new HttpHost(host, port, scheme); String url = httpsClient.transportChannelSettings.getDescription().getEndpointUrl(); String endpointId = url == null ? "" : url; //UriUtil.getEndpointName(url); httpPost = new HttpPost( endpointId ); httpPost.addHeader("OPCUA-SecurityPolicy", httpsClient.securityPolicyUri); httpPost.addHeader("Content-Type", "application/octet-stream"); // Calculate message length SizeCalculationOutputStream calcBuf = new SizeCalculationOutputStream(); BinaryEncoder calc = new BinaryEncoder(calcBuf); calc.setEncoderContext( httpsClient.encoderCtx ); calc.putMessage( requestMessage ); int len = calcBuf.getLength(); // Assert max size is not exceeded int maxLen = httpsClient.encoderCtx.getMaxMessageSize(); if ( maxLen != 0 && len > maxLen ) { final EncodingException encodingException = new EncodingException(StatusCodes.Bad_EncodingLimitsExceeded, "MaxStringLength "+maxLen+" < "+len); logger.warn("run: failed", encodingException); throw encodingException; } // Encode message byte[] data = new byte[ len ]; BinaryEncoder enc = new BinaryEncoder( data ); enc.setEncoderContext( httpsClient.encoderCtx ); enc.putMessage( requestMessage ); httpPost.setEntity( new NByteArrayEntity(data) ); // Abort exit branch if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode ) ); return; } // Execute Post HttpResponse httpResponse; try { httpResponse = httpsClient.httpclient.execute( httpHost, httpPost ); } catch (SSLPeerUnverifiedException e) { // Currently, TLS_1_2 is not supported by JSSE implementations, for some odd reason // and it will give this exception when used. // Also, if the server certificate is rejected, we will get this error result.setError( new ServiceResultException(StatusCodes.Bad_SecurityPolicyRejected, e, "Could not negotiate a TLS security cipher or the server did not provide a valid certificate.")); return; } HttpEntity entity = httpResponse.getEntity(); // Error response int statusCode = httpResponse.getStatusLine().getStatusCode(); if ( statusCode != 200 ) { UnsignedInteger uacode = StatusCodes.Bad_UnknownResponse; if ( statusCode == 501 ) uacode = StatusCodes.Bad_ServiceUnsupported; String msg = EntityUtils.toString( entity ); result.setError( new ServiceResultException( uacode, statusCode+": "+msg ) ); return; } // Abort exit branch if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode ) ); return; } // Decode Message data = EntityUtils.toByteArray(entity); BinaryDecoder dec = new BinaryDecoder( data ); dec.setEncoderContext( httpsClient.encoderCtx ); IEncodeable response = dec.getMessage(); // Client sent an error if ( response instanceof ErrorMessage ) { ErrorMessage error = (ErrorMessage) response; ServiceResultException errorResult = new ServiceResultException(new StatusCode(error.getError()), error.getReason()); result.setError(errorResult); return; } try { // Client sent a valid message result.setResult((ServiceResponse) response); } catch (ClassCastException e) { result.setError(new ServiceResultException(e)); logger.error( "Cannot cast response to ServiceResponse, response=" + response.getClass(), e); } } catch (EncodingException e) { // Internal Error result.setError( new ServiceResultException( StatusCodes.Bad_EncodingError, e ) ); } catch (ClientProtocolException e) { result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e) ); } catch (IOException e) { if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode, e ) ); } else { result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e ) ); } } catch (DecodingException e) { result.setError( new ServiceResultException( StatusCodes.Bad_DecodingError, e ) ); } catch (ServiceResultException e) { result.setError( e ); } catch (RuntimeException rte) { // http-client seems to be throwing these, IllegalArgumentException for one result.setError( new ServiceResultException( rte ) ); } catch(StackOverflowError e){ // Payloads of high nesting levels may cause stack overflow. Structure, VariantArray and DiagnosticInfo at least may cause this. // JVM setting -Xss influences possible level of nesting. At least 100 levels of nesting must be supported, this should not be a problem with normal thread stack sizes. // Inform receiving side that error has happened. result.setError(new ServiceResultException(StatusCodes.Bad_DecodingError, "Stack overflow: " + Arrays.toString(Arrays.copyOf(e.getStackTrace(), 30)) + "...")); } finally { httpsClient.requests.remove( requestId ); } }
#vulnerable code @Override public void run() { try { // Abort exit branch if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode ) ); return; } // Http Post InetSocketAddress inetAddress = UriUtil.getSocketAddress( httpsClient.connectUrl ); String host = inetAddress.getHostName(); int port = inetAddress.getPort(); String scheme = UriUtil.getTransportProtocol( httpsClient.connectUrl ); HttpHost httpHost = new HttpHost(host, port, scheme); String url = httpsClient.transportChannelSettings.getDescription().getEndpointUrl(); String endpointId = url == null ? "" : url; //UriUtil.getEndpointName(url); httpPost = new HttpPost( endpointId ); httpPost.addHeader("OPCUA-SecurityPolicy", httpsClient.securityPolicyUri); httpPost.addHeader("Content-Type", "application/octet-stream"); // Calculate message length SizeCalculationOutputStream tmp = new SizeCalculationOutputStream(); BinaryEncoder calc = new BinaryEncoder(tmp); calc.setEncoderContext( httpsClient.encoderCtx ); calc.putMessage( requestMessage ); int len = tmp.getLength(); // Assert max size is not exceeded int maxLen = httpsClient.encoderCtx.getMaxMessageSize(); if ( maxLen != 0 && len > maxLen ) { final EncodingException encodingException = new EncodingException(StatusCodes.Bad_EncodingLimitsExceeded, "MaxStringLength "+maxLen+" < "+len); logger.warn("run: failed", encodingException); throw encodingException; } // Encode message byte[] data = new byte[ len ]; BinaryEncoder enc = new BinaryEncoder( data ); enc.setEncoderContext( httpsClient.encoderCtx ); enc.putMessage( requestMessage ); httpPost.setEntity( new NByteArrayEntity(data) ); // Abort exit branch if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode ) ); return; } // Execute Post HttpResponse httpResponse; try { httpResponse = httpsClient.httpclient.execute( httpHost, httpPost ); } catch (SSLPeerUnverifiedException e) { // Currently, TLS_1_2 is not supported by JSSE implementations, for some odd reason // and it will give this exception when used. // Also, if the server certificate is rejected, we will get this error result.setError( new ServiceResultException(StatusCodes.Bad_SecurityPolicyRejected, e, "Could not negotiate a TLS security cipher or the server did not provide a valid certificate.")); return; } HttpEntity entity = httpResponse.getEntity(); // Error response int statusCode = httpResponse.getStatusLine().getStatusCode(); if ( statusCode != 200 ) { UnsignedInteger uacode = StatusCodes.Bad_UnknownResponse; if ( statusCode == 501 ) uacode = StatusCodes.Bad_ServiceUnsupported; String msg = EntityUtils.toString( entity ); result.setError( new ServiceResultException( uacode, statusCode+": "+msg ) ); return; } // Abort exit branch if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode ) ); return; } // Decode Message data = EntityUtils.toByteArray(entity); BinaryDecoder dec = new BinaryDecoder( data ); dec.setEncoderContext( httpsClient.encoderCtx ); IEncodeable response = dec.getMessage(); // Client sent an error if ( response instanceof ErrorMessage ) { ErrorMessage error = (ErrorMessage) response; ServiceResultException errorResult = new ServiceResultException(new StatusCode(error.getError()), error.getReason()); result.setError(errorResult); return; } try { // Client sent a valid message result.setResult((ServiceResponse) response); } catch (ClassCastException e) { result.setError(new ServiceResultException(e)); logger.error( "Cannot cast response to ServiceResponse, response=" + response.getClass(), e); } } catch (EncodingException e) { // Internal Error result.setError( new ServiceResultException( StatusCodes.Bad_EncodingError, e ) ); } catch (ClientProtocolException e) { result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e) ); } catch (IOException e) { if ( abortCode != null ) { result.setError( new ServiceResultException( abortCode, e ) ); } else { result.setError( new ServiceResultException( StatusCodes.Bad_CommunicationError, e ) ); } } catch (DecodingException e) { result.setError( new ServiceResultException( StatusCodes.Bad_DecodingError, e ) ); } catch (ServiceResultException e) { result.setError( e ); } catch (RuntimeException rte) { // http-client seems to be throwing these, IllegalArgumentException for one result.setError( new ServiceResultException( rte ) ); } catch(StackOverflowError e){ // Payloads of high nesting levels may cause stack overflow. Structure, VariantArray and DiagnosticInfo at least may cause this. // JVM setting -Xss influences possible level of nesting. At least 100 levels of nesting must be supported, this should not be a problem with normal thread stack sizes. // Inform receiving side that error has happened. result.setError(new ServiceResultException(StatusCodes.Bad_DecodingError, "Stack overflow: " + Arrays.toString(Arrays.copyOf(e.getStackTrace(), 30)) + "...")); } finally { httpsClient.requests.remove( requestId ); } } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ByteBuffer[] call() throws RuntimeServiceResultException { try { SizeCalculationOutputStream calcBuf = new SizeCalculationOutputStream(); BinaryEncoder calc = new BinaryEncoder(calcBuf); calc.setEncoderContext(encoderCtx); if (type == MessageType.Encodeable) calc.putEncodeable(null, msg); else calc.putMessage(msg); int len = calcBuf.getLength(); if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); ByteQueue bq = new ByteQueue(); bq.order(ByteOrder.LITTLE_ENDIAN); bq.setWriteLimit(len); bq.setByteBufferFactory(chunkFactory); bq.setChunkSize(chunkFactory.maxPlaintextSize); ByteBufferArrayWriteable array = new ByteBufferArrayWriteable(bq); array.order(ByteOrder.LITTLE_ENDIAN); BinaryEncoder enc = new BinaryEncoder(array); enc.setEncoderContext(encoderCtx); if (type == MessageType.Message) enc.putMessage(msg); else enc.putEncodeable(null, msg); ByteBuffer[] plaintexts = bq.getChunks(len); if (plaintexts.length>ctx.maxRecvChunkCount && ctx.maxRecvChunkCount!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); return plaintexts; } catch (ServiceResultException e) { throw new RuntimeServiceResultException(e); } }
#vulnerable code @Override public ByteBuffer[] call() throws RuntimeServiceResultException { try { SizeCalculationOutputStream tmp = new SizeCalculationOutputStream(); BinaryEncoder calc = new BinaryEncoder(tmp); calc.setEncoderContext(encoderCtx); if (type == MessageType.Encodeable) calc.putEncodeable(null, msg); else calc.putMessage(msg); int len = tmp.getLength(); if (len>ctx.maxSendMessageSize && ctx.maxSendMessageSize!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); ByteQueue bq = new ByteQueue(); bq.order(ByteOrder.LITTLE_ENDIAN); bq.setWriteLimit(len); bq.setByteBufferFactory(chunkFactory); bq.setChunkSize(chunkFactory.maxPlaintextSize); ByteBufferArrayWriteable array = new ByteBufferArrayWriteable(bq); array.order(ByteOrder.LITTLE_ENDIAN); BinaryEncoder enc = new BinaryEncoder(array); enc.setEncoderContext(encoderCtx); if (type == MessageType.Message) enc.putMessage(msg); else enc.putEncodeable(null, msg); ByteBuffer[] plaintexts = bq.getChunks(len); if (plaintexts.length>ctx.maxRecvChunkCount && ctx.maxRecvChunkCount!=0) throw new ServiceResultException(StatusCodes.Bad_TcpMessageTooLarge); return plaintexts; } catch (ServiceResultException e) { throw new RuntimeServiceResultException(e); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @EventHandler public void onStructureGrow(StructureGrowEvent event) { Location location = event.getLocation(); GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName()); TreeTable treeTable = gw.getTableManager().getTreeTable(); GPlayer planter; // TODO: Add TreeType species to reduction model if (treeTable.getLocationMap().containsKey(location)) { Tree tree = treeTable.getTreeMap().get(treeTable.getLocationMap().get(location)); planter = tree.getOwner(); Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks()); int carbonScore = planter.getCarbonScore(); planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue())); tree.setSapling(false); tree.setSize(event.getBlocks().size()); // TODO: Only consider core species blocks as tree size // Queue tree update query TreeUpdateQuery treeUpdateQuery = new TreeUpdateQuery(tree); AsyncDBQueue.getInstance().queueUpdateQuery(treeUpdateQuery); } else { PlayerTable playerTable = GlobalWarming.getInstance().getTableManager().getPlayerTable(); planter = playerTable.getOrCreatePlayer(untrackedUUID, true); // First create a new tree object and store it Long uniqueId = GlobalWarming.getInstance().getRandom().nextLong(); // TODO: Only consider core species blocks as tree size Tree tree = new Tree(uniqueId, planter, location, false, event.getBlocks().size()); TreeInsertQuery insertQuery = new TreeInsertQuery(tree); AsyncDBQueue.getInstance().queueInsertQuery(insertQuery); gw.getLogger().warning("Untracked structure grow occured:"); gw.getLogger().warning("@ " + location.toString()); } // Create a new reduction object using the worlds climate engine Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks()); int carbonScore = planter.getCarbonScore(); planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue())); // Queue player update query PlayerUpdateQuery playerUpdateQuery = new PlayerUpdateQuery(planter); AsyncDBQueue.getInstance().queueUpdateQuery(playerUpdateQuery); // Queue reduction insert query ReductionInsertQuery insertQuery = new ReductionInsertQuery(reduction); AsyncDBQueue.getInstance().queueInsertQuery(insertQuery); }
#vulnerable code @EventHandler public void onStructureGrow(StructureGrowEvent event) { Location location = event.getLocation(); GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName()); TreeTable treeTable = gw.getTableManager().getTreeTable(); if (treeTable.getLocationMap().containsKey(location)) { Long uuid = treeTable.getLocationMap().get(location); Tree tree = treeTable.getTreeMap().get(uuid); UUID ownerUUID = tree.getOwner().getUuid(); GPlayer planter = gw.getTableManager().getPlayerTable().getPlayers().get(ownerUUID); Reduction reduction = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).treeGrow(planter, event.getSpecies(), event.getBlocks()); int carbonScore = planter.getCarbonScore(); planter.setCarbonScore((int) (carbonScore - reduction.getReductionValue())); tree.setSapling(false); // TODO: Queue tree DB update // TODO: Queue planter score DB update // TODO: Queue new reduction DB insert } else { gw.getLogger().severe("Untracked structure grow occured:"); gw.getLogger().severe("@ " + location.toString()); } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @EventHandler public void onFurnaceSmelt(FurnaceBurnEvent event) { Location location = event.getBlock().getLocation(); GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName()); FurnaceTable furnaceTable = gw.getTableManager().getFurnaceTable(); GPlayer polluter; if (furnaceTable.getLocationMap().containsKey(location)) { Furnace furnace = furnaceTable.getFurnaceMap().get(furnaceTable.getLocationMap().get(location)); polluter = furnace.getOwner(); // whoever placed the furnace is charged. } else { /* * This might happen if a player has a redstone hopper setup that feeds untracked furnaces * In this case, just consider it to be untracked emissions. */ PlayerTable playerTable = GlobalWarming.getInstance().getTableManager().getPlayerTable(); polluter = playerTable.getOrCreatePlayer(untrackedUUID, true); // First create a new furnace object and store it Long uniqueId = GlobalWarming.getInstance().getRandom().nextLong(); Furnace furnace = new Furnace(uniqueId, polluter, location, true); // Update all furnace collections furnaceTable.updateFurnace(furnace); // Create a new furnace insert query and queue it FurnaceInsertQuery insertQuery = new FurnaceInsertQuery(furnace); AsyncDBQueue.getInstance().queueInsertQuery(insertQuery); gw.getLogger().warning(event.getFuel().getType().name() + " burned as fuel in an untracked furnace!"); gw.getLogger().warning("@ " + location.toString()); } // Create a contribution object using this worlds climate engine Contribution contrib = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).furnaceBurn(polluter, event.getFuel()); int carbonScore = polluter.getCarbonScore(); polluter.setCarbonScore((int) (carbonScore + contrib.getContributionValue())); // Queue an update to the player table PlayerUpdateQuery updateQuery = new PlayerUpdateQuery(polluter); AsyncDBQueue.getInstance().queueUpdateQuery(updateQuery); // Queue an insert into the contributions table ContributionInsertQuery insertQuery = new ContributionInsertQuery(contrib); AsyncDBQueue.getInstance().queueInsertQuery(insertQuery); }
#vulnerable code @EventHandler public void onFurnaceSmelt(FurnaceBurnEvent event) { Location location = event.getBlock().getLocation(); GWorld world = gw.getTableManager().getWorldTable().getWorld(location.getWorld().getName()); FurnaceTable furnaceTable = gw.getTableManager().getFurnaceTable(); if (furnaceTable.getLocationMap().containsKey(location)) { Long uuid = furnaceTable.getLocationMap().get(location); Furnace furnace = furnaceTable.getFurnaceMap().get(uuid); // Note: We hold the owner of the furnace responsible for emissions // If the furnace isn't protected, the furnace owner is still charged GPlayer polluter = gw.getTableManager().getPlayerTable().getPlayers().get(furnace.getOwner().getUuid()); Contribution emissions = ClimateEngine.getInstance().getClimateEngine(world.getWorldName()).furnaceBurn(polluter, event.getFuel()); int carbonScore = polluter.getCarbonScore(); polluter.setCarbonScore((int) (carbonScore + emissions.getContributionValue())); // TODO: Queue polluter score DB update // TODO: Queue new contribution DB insert } else { gw.getLogger().severe(event.getFuel().getType().name() + " burned as fuel in an untracked furnace!"); gw.getLogger().severe("@ " + location.toString()); } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OutputStream createUnsortedOutputStream() { try { return new BufferedOutputStream(new FileOutputStream(unsortedFile)); } catch (IOException e) { throw new RuntimeException(e); } }
#vulnerable code OutputStream createSortedOutputStream() { try { return new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sortedFile))); } catch (IOException e) { throw new RuntimeException(e); } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OutputStream createUnsortedOutputStream() { try { return new BufferedOutputStream(new FileOutputStream(unsortedFile)); } catch (IOException e) { throw new RuntimeException(e); } }
#vulnerable code OutputStream createUnsortedOutputStream() { try { return new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(unsortedFile))); } catch (IOException e) { throw new RuntimeException(e); } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void verify() { Function<Long, Object> formatter = createFormatter(); IdAndVersionStreamVerifierListener verifierListener = createVerifierListener(formatter); this.verify(verifierListener); }
#vulnerable code public void verify() { idAndVersionFactory = createIdAndVersionFactory(); ElasticSearchIdAndVersionStream elasticSearchIdAndVersionStream = createElasticSearchIdAndVersionStream(options); JdbcIdAndVersionStream jdbcIdAndVersionStream = createJdbcIdAndVersionStream(options); verify(elasticSearchIdAndVersionStream, jdbcIdAndVersionStream, new IdAndVersionStreamVerifier()); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code OutputStream createUnsortedOutputStream() { try { return new BufferedOutputStream(new FileOutputStream(unsortedFile)); } catch (IOException e) { throw new RuntimeException(e); } }
#vulnerable code InputStream createUnSortedInputStream() { try { return new ObjectInputStream(new BufferedInputStream(new FileInputStream(unsortedFile))); } catch (IOException e) { throw new RuntimeException(e); } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCustomResourceWatch() throws Exception { Assume.assumeTrue(TestUtils.isKubernetesAvailable()); ClientHolder client = ClientHelper.getInstance().take(); Watch<Domain> watch = Watch.createWatch( client.getApiClient(), client.getWeblogicApiClient().listWebLogicOracleV1DomainForAllNamespacesCall(null, null, null, null, 5, null, null, 60, Boolean.TRUE, null, null), new TypeToken<Watch.Response<Domain>>() { }.getType()); }
#vulnerable code @Test public void testCustomResourceWatch() { Assume.assumeTrue(System.getProperty("os.name").toLowerCase().contains("nix")); ClientHolder client = ClientHelper.getInstance().take(); try { // create a watch Watch<Domain> watch = Watch.createWatch( client.getApiClient(), client.getWeblogicApiClient().listWebLogicOracleV1DomainForAllNamespacesCall(null, null, null, null, 5, null, null, 60, Boolean.TRUE, null, null), new TypeToken<Watch.Response<Domain>>() { }.getType()); for (Watch.Response<Domain> item : watch) { System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName()); } } catch (ApiException e) { if (e.getCode() == 404) { System.out.println("***\n***This test is not able to run because the CRD that I want to watch does not exist on the server\n***"); } else { fail(); } } catch (RuntimeException e) { System.out.println("stream finished"); } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void serverStartupInfo_containsEnvironmentVariable() { configureServer("wls1") .withEnvironmentVariable("item1", "value1") .withEnvironmentVariable("item2", "value2"); addWlsServer("wls1"); invokeStep(); assertThat( getServerStartupInfo("wls1").getEnvironment(), containsInAnyOrder(envVar("item1", "value1"), envVar("item2", "value2"))); }
#vulnerable code @Test public void serverStartupInfo_containsEnvironmentVariable() { configureServer("ms1") .withEnvironmentVariable("item1", "value1") .withEnvironmentVariable("item2", "value2"); addWlsServer("ms1"); invokeStep(); assertThat( getServerStartupInfo("ms1").getEnvironment(), containsInAnyOrder(envVar("item1", "value1"), envVar("item2", "value2"))); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { if (status.get() == NOT_COMPLETE) { // Clear the interrupted status, if present Thread.interrupted(); final Fiber oldFiber = CURRENT_FIBER.get(); CURRENT_FIBER.set(this); Container oldContainer = ContainerResolver.getDefault().enterContainer(owner.getContainer()); try { // doRun returns true to indicate an early exit from fiber processing if (!doRun(next)) { completionCheck(); } } finally { ContainerResolver.getDefault().exitContainer(oldContainer); CURRENT_FIBER.set(oldFiber); } } }
#vulnerable code @Override public void run() { // Clear the interrupted status, if present Thread.interrupted(); final Fiber oldFiber = CURRENT_FIBER.get(); CURRENT_FIBER.set(this); Container oldContainer = ContainerResolver.getDefault().enterContainer(owner.getContainer()); try { // doRun returns true to indicate an early exit from fiber processing if (!doRun(next)) { completionCheck(); } // Trigger exitCallback synchronized (this) { if (exitCallback != null && exitCallback != PLACEHOLDER) { if (LOGGER.isFineEnabled()) { LOGGER.fine("{0} invoking exit callback", new Object[] { getName() }); } exitCallback.onExit(); } exitCallback = PLACEHOLDER; } } finally { ContainerResolver.getDefault().exitContainer(oldContainer); CURRENT_FIBER.set(oldFiber); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenDomainReadFromYaml_unconfiguredServerHasDomainDefaults() throws IOException { Domain domain = readDomain(DOMAIN_V2_SAMPLE_YAML); ServerSpec serverSpec = domain.getServer("server0", null); assertThat(serverSpec.getImage(), equalTo(DEFAULT_IMAGE)); assertThat(serverSpec.getImagePullPolicy(), equalTo(IFNOTPRESENT_IMAGEPULLPOLICY)); assertThat(serverSpec.getImagePullSecrets().get(0).getName(), equalTo("pull-secret")); assertThat(serverSpec.getEnvironmentVariables(), empty()); assertThat(serverSpec.getNodePort(), nullValue()); assertThat(serverSpec.getDesiredState(), equalTo("RUNNING")); }
#vulnerable code @Test public void whenDomainReadFromYaml_unconfiguredServerHasDomainDefaults() throws IOException { Domain domain = readDomain(DOMAIN_V2_SAMPLE_YAML); ServerSpec serverSpec = domain.getServer("server0", null); assertThat(serverSpec.getImage(), equalTo(DEFAULT_IMAGE)); assertThat(serverSpec.getImagePullPolicy(), equalTo(IFNOTPRESENT_IMAGEPULLPOLICY)); assertThat(serverSpec.getImagePullSecret().getName(), equalTo("pull-secret")); assertThat(serverSpec.getEnvironmentVariables(), empty()); assertThat(serverSpec.getNodePort(), nullValue()); assertThat(serverSpec.getDesiredState(), equalTo("RUNNING")); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTwoDomainsManagedByTwoOperators() throws Exception { Assume.assumeFalse(QUICKTEST); String testMethodName = new Object() {}.getClass().getEnclosingMethod().getName(); logTestBegin(testMethodName); logger.info("Creating Domain domain4 & verifing the domain creation"); logger.info("Checking if operator1 and domain1 are running, if not creating"); if (operator1 == null) { operator1 = TestUtils.createOperator(opManagingdefaultAndtest1NSYamlFile); } Domain domain1 = null, domain2 = null; boolean testCompletedSuccessfully = false; try { // load input yaml to map and add configOverrides Map<String, Object> wlstDomainMap = TestUtils.loadYaml(domainOnPVUsingWLSTYamlFile); wlstDomainMap.put("domainUID", "domain1onpvwlst"); wlstDomainMap.put("adminNodePort", new Integer("30702")); wlstDomainMap.put("t3ChannelPort", new Integer("30031")); domain1 = TestUtils.createDomain(wlstDomainMap); domain1.verifyDomainCreated(); testBasicUseCases(domain1); logger.info("Checking if operator2 is running, if not creating"); if (operator2 == null) { operator2 = TestUtils.createOperator(opManagingtest2NSYamlFile); } // create domain5 with configured cluster // ToDo: configured cluster support is removed from samples, modify the test to create // configured cluster Map<String, Object> wdtDomainMap = TestUtils.loadYaml(domainOnPVUsingWDTYamlFile); wdtDomainMap.put("domainUID", "domain2onpvwdt"); wdtDomainMap.put("adminNodePort", new Integer("30703")); wdtDomainMap.put("t3ChannelPort", new Integer("30041")); // wdtDomainMap.put("clusterType", "Configured"); domain2 = TestUtils.createDomain(wdtDomainMap); domain2.verifyDomainCreated(); testBasicUseCases(domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); testClusterScaling(operator2, domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); logger.info("Destroy and create domain4 and verify no impact on domain2"); domain1.destroy(); domain1.create(); logger.info("Verify no impact on domain2"); domain2.verifyDomainCreated(); testCompletedSuccessfully = true; } finally { String domainUidsToBeDeleted = ""; if (domain1 != null && (JENKINS || testCompletedSuccessfully)) { domainUidsToBeDeleted = domain1.getDomainUid(); } if (domain2 != null && (JENKINS || testCompletedSuccessfully)) { domainUidsToBeDeleted = domainUidsToBeDeleted + "," + domain2.getDomainUid(); } if (!domainUidsToBeDeleted.equals("")) { logger.info("About to delete domains: " + domainUidsToBeDeleted); TestUtils.deleteWeblogicDomainResources(domainUidsToBeDeleted); TestUtils.verifyAfterDeletion(domain1); TestUtils.verifyAfterDeletion(domain2); } } logger.info("SUCCESS - " + testMethodName); }
#vulnerable code @Test public void testTwoDomainsManagedByTwoOperators() throws Exception { Assume.assumeFalse(QUICKTEST); String testMethodName = new Object() {}.getClass().getEnclosingMethod().getName(); logTestBegin(testMethodName); logger.info("Creating Domain domain4 & verifing the domain creation"); logger.info("Checking if operator1 and domain1 are running, if not creating"); if (operator1 == null) { operator1 = TestUtils.createOperator(opManagingdefaultAndtest1NSYamlFile); } Domain domain1 = null, domain2 = null; boolean testCompletedSuccessfully = false; try { // load input yaml to map and add configOverrides Map<String, Object> wlstDomainMap = TestUtils.loadYaml(domainOnPVUsingWLSTYamlFile); wlstDomainMap.put("domainUID", "domain1onpvwlst"); wlstDomainMap.put("adminNodePort", new Integer("30702")); wlstDomainMap.put("t3ChannelPort", new Integer("30031")); domain1 = TestUtils.createDomain(wlstDomainMap); domain1.verifyDomainCreated(); testBasicUseCases(domain1); logger.info("Checking if operator2 is running, if not creating"); if (operator2 == null) { operator2 = TestUtils.createOperator(opManagingtest2NSYamlFile); } // create domain5 with configured cluster // ToDo: configured cluster support is removed from samples, modify the test to create // configured cluster Map<String, Object> wdtDomainMap = TestUtils.loadYaml(domainOnPVUsingWDTYamlFile); wdtDomainMap.put("domainUID", "domain2onpvwdt"); wdtDomainMap.put("adminNodePort", new Integer("30703")); wdtDomainMap.put("t3ChannelPort", new Integer("30041")); // wdtDomainMap.put("clusterType", "Configured"); domain2 = TestUtils.createDomain(wdtDomainMap); domain2.verifyDomainCreated(); testBasicUseCases(domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); testClusterScaling(operator2, domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); logger.info("Destroy and create domain4 and verify no impact on domain2"); domain1.destroy(); domain1.create(); logger.info("Verify no impact on domain2"); domain2.verifyDomainCreated(); testCompletedSuccessfully = true; } finally { String domainUidsToBeDeleted = ""; if (domain1 != null && (JENKINS || testCompletedSuccessfully)) { domainUidsToBeDeleted = domain1.getDomainUid(); } if (domain2 != null && (JENKINS || testCompletedSuccessfully)) { domainUidsToBeDeleted = domainUidsToBeDeleted + "," + domain2.getDomainUid(); } if (!domainUidsToBeDeleted.equals("")) { logger.info("About to delete domains: " + domainUidsToBeDeleted); TestUtils.deleteWeblogicDomainResources(domainUidsToBeDeleted); logger.info("domain1 domainMap " + domain1.getDomainMap()); TestUtils.verifyAfterDeletion(domain1); logger.info("domain2 domainMap " + domain2.getDomainMap()); TestUtils.verifyAfterDeletion(domain2); } } logger.info("SUCCESS - " + testMethodName); } #location 69 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenDesiredStateIsAdmin_serverStartupAddsToJavaOptionsEnvironment() { configureServer("wls1") .withDesiredState(ADMIN_STATE) .withEnvironmentVariable("JAVA_OPTIONS", "value1"); addWlsServer("wls1"); invokeStep(); assertThat( getServerStartupInfo("wls1").getEnvironment(), hasItem(envVar("JAVA_OPTIONS", "-Dweblogic.management.startupMode=ADMIN value1"))); }
#vulnerable code @Test public void whenDesiredStateIsAdmin_serverStartupAddsToJavaOptionsEnvironment() { configureServer("ms1") .withDesiredState(ADMIN_STATE) .withEnvironmentVariable("JAVA_OPTIONS", "value1"); addWlsServer("ms1"); invokeStep(); assertThat( getServerStartupInfo("ms1").getEnvironment(), hasItem(envVar("JAVA_OPTIONS", "-Dweblogic.management.startupMode=ADMIN value1"))); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenDesiredStateIsAdmin_serverStartupCreatesJavaOptionsEnvironment() { configureServer("wls1").withDesiredState(ADMIN_STATE); addWlsServer("wls1"); invokeStep(); assertThat( getServerStartupInfo("wls1").getEnvironment(), hasItem(envVar("JAVA_OPTIONS", "-Dweblogic.management.startupMode=ADMIN"))); }
#vulnerable code @Test public void whenDesiredStateIsAdmin_serverStartupCreatesJavaOptionsEnvironment() { configureServer("ms1").withDesiredState(ADMIN_STATE); addWlsServer("ms1"); invokeStep(); assertThat( getServerStartupInfo("ms1").getEnvironment(), hasItem(envVar("JAVA_OPTIONS", "-Dweblogic.management.startupMode=ADMIN"))); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTwoDomainsManagedByTwoOperators() throws Exception { Assume.assumeFalse(QUICKTEST); String testMethodName = new Object() {}.getClass().getEnclosingMethod().getName(); logTestBegin(testMethodName); logger.info("Creating Domain domain4 & verifing the domain creation"); logger.info("Checking if operator1 and domain1 are running, if not creating"); if (operator1 == null) { operator1 = TestUtils.createOperator(opManagingdefaultAndtest1NSYamlFile); } Domain domain1 = null, domain2 = null; boolean testCompletedSuccessfully = false; try { // load input yaml to map and add configOverrides Map<String, Object> wlstDomainMap = TestUtils.loadYaml(domainOnPVUsingWLSTYamlFile); wlstDomainMap.put("domainUID", "domain1onpvwlst"); wlstDomainMap.put("adminNodePort", new Integer("30702")); wlstDomainMap.put("t3ChannelPort", new Integer("30031")); domain1 = TestUtils.createDomain(wlstDomainMap); domain1.verifyDomainCreated(); testBasicUseCases(domain1); logger.info("Checking if operator2 is running, if not creating"); if (operator2 == null) { operator2 = TestUtils.createOperator(opManagingtest2NSYamlFile); } // create domain5 with configured cluster // ToDo: configured cluster support is removed from samples, modify the test to create // configured cluster Map<String, Object> wdtDomainMap = TestUtils.loadYaml(domainOnPVUsingWDTYamlFile); wdtDomainMap.put("domainUID", "domain2onpvwdt"); wdtDomainMap.put("adminNodePort", new Integer("30703")); wdtDomainMap.put("t3ChannelPort", new Integer("30041")); // wdtDomainMap.put("clusterType", "Configured"); domain2 = TestUtils.createDomain(wdtDomainMap); domain2.verifyDomainCreated(); testBasicUseCases(domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); testClusterScaling(operator2, domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); logger.info("Destroy and create domain4 and verify no impact on domain2"); domain1.destroy(); domain1.create(); logger.info("Verify no impact on domain2"); domain2.verifyDomainCreated(); testCompletedSuccessfully = true; } finally { String domainUidsToBeDeleted = ""; if (domain1 != null && (JENKINS || testCompletedSuccessfully)) { domainUidsToBeDeleted = domain1.getDomainUid(); } if (domain2 != null && (JENKINS || testCompletedSuccessfully)) { domainUidsToBeDeleted = domainUidsToBeDeleted + "," + domain2.getDomainUid(); } if (!domainUidsToBeDeleted.equals("")) { logger.info("About to delete domains: " + domainUidsToBeDeleted); TestUtils.deleteWeblogicDomainResources(domainUidsToBeDeleted); logger.info("domain1 domainMap " + domain1.getDomainMap()); TestUtils.verifyAfterDeletion(domain1); logger.info("domain2 domainMap " + domain2.getDomainMap()); TestUtils.verifyAfterDeletion(domain2); } } logger.info("SUCCESS - " + testMethodName); }
#vulnerable code @Test public void testTwoDomainsManagedByTwoOperators() throws Exception { Assume.assumeFalse(QUICKTEST); String testMethodName = new Object() {}.getClass().getEnclosingMethod().getName(); logTestBegin(testMethodName); logger.info("Creating Domain domain4 & verifing the domain creation"); logger.info("Checking if operator1 and domain1 are running, if not creating"); if (operator1 == null) { operator1 = TestUtils.createOperator(opManagingdefaultAndtest1NSYamlFile); } Domain domain1 = null, domain2 = null; boolean testCompletedSuccessfully = false; try { // load input yaml to map and add configOverrides Map<String, Object> wlstDomainMap = TestUtils.loadYaml(domainOnPVUsingWLSTYamlFile); wlstDomainMap.put("domainUID", "domain1onpvwlst"); domain1 = TestUtils.createDomain(wlstDomainMap); domain1.verifyDomainCreated(); testBasicUseCases(domain1); logger.info("Checking if operator2 is running, if not creating"); if (operator2 == null) { operator2 = TestUtils.createOperator(opManagingtest2NSYamlFile); } // create domain5 with configured cluster // ToDo: configured cluster support is removed from samples, modify the test to create // configured cluster Map<String, Object> wdtDomainMap = TestUtils.loadYaml(domainOnPVUsingWDTYamlFile); wdtDomainMap.put("domainUID", "domain2onpvwdt"); // wdtDomainMap.put("clusterType", "Configured"); domain2 = TestUtils.createDomain(wdtDomainMap); domain2.verifyDomainCreated(); testBasicUseCases(domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); testClusterScaling(operator2, domain2); logger.info("Verify the only remaining running domain domain1 is unaffected"); domain1.verifyDomainCreated(); logger.info("Destroy and create domain4 and verify no impact on domain2"); domain1.destroy(); domain1.create(); logger.info("Verify no impact on domain2"); domain2.verifyDomainCreated(); testCompletedSuccessfully = true; } finally { String domainUidsToBeDeleted = ""; if (domain1 != null && (JENKINS || testCompletedSuccessfully)) { // domain1.destroy(); // TestUtils.verifyBeforeDeletion(domain1); domainUidsToBeDeleted = domain1.getDomainUid(); } if (domain2 != null && (JENKINS || testCompletedSuccessfully)) { // domain2.destroy(); domainUidsToBeDeleted = domainUidsToBeDeleted + "," + domain2.getDomainUid(); } if (!domainUidsToBeDeleted.equals("")) { logger.info("About to delete domains: " + domainUidsToBeDeleted); TestUtils.deleteWeblogicDomainResources(domainUidsToBeDeleted); TestUtils.verifyAfterDeletion(domain1); TestUtils.verifyAfterDeletion(domain2); } } logger.info("SUCCESS - " + testMethodName); } #location 68 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenWlsServerNotInCluster_serverStartupInfoHasNoClusterConfig() { configureServer("wls1"); addWlsServer("wls1"); invokeStep(); assertThat(getServerStartupInfo("wls1").getClusterName(), nullValue()); }
#vulnerable code @Test public void whenWlsServerNotInCluster_serverStartupInfoHasNoClusterConfig() { configureServer("ms1"); addWlsServer("ms1"); invokeStep(); assertThat(getServerStartupInfo("ms1").getClusterName(), nullValue()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNamespaceWatch() throws Exception { Assume.assumeTrue(TestUtils.isKubernetesAvailable()); ClientHolder client = ClientHelper.getInstance().take(); Watch<V1Namespace> watch = Watch.createWatch( client.getApiClient(), client.getCoreApiClient().listNamespaceCall(null, null, null, null, null, 5, null, 60, Boolean.TRUE, null, null), new TypeToken<Watch.Response<V1Namespace>>() { }.getType()); }
#vulnerable code @Test public void testNamespaceWatch() { Assume.assumeTrue(System.getProperty("os.name").toLowerCase().contains("nix")); ClientHolder client = ClientHelper.getInstance().take(); try { Watch<V1Namespace> watch = Watch.createWatch( client.getApiClient(), client.getCoreApiClient().listNamespaceCall(null, null, null, null, null, 5, null, 60, Boolean.TRUE, null, null), new TypeToken<Watch.Response<V1Namespace>>() { }.getType()); for (Watch.Response<V1Namespace> item : watch) { System.out.printf("%s : %s%n", item.type, item.object.getMetadata().getName()); } } catch (ApiException e) { fail(); } catch (RuntimeException e) { System.out.println("stream finished"); } } #location 3 #vulnerability type NULL_DEREFERENCE