input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override public boolean isEquivalentTo(JSType otherType) { if (!(otherType instanceof FunctionType)) { return false; } FunctionType that = (FunctionType) otherType; if (!that.isFunctionType()) { return false; } if (this.isConstructor()) { if (that.isConstructor()) { return this == that; } return false; } if (this.isInterface()) { if (that.isInterface()) { return this.getReferenceName().equals(that.getReferenceName()); } return false; } if (that.isInterface()) { return false; } return this.typeOfThis.isEquivalentTo(that.typeOfThis) && this.call.isEquivalentTo(that.call); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean isEquivalentTo(JSType otherType) { FunctionType that = JSType.toMaybeFunctionType(otherType.toMaybeFunctionType()); if (that == null) { return false; } if (this.isConstructor()) { if (that.isConstructor()) { return this == that; } return false; } if (this.isInterface()) { if (that.isInterface()) { return this.getReferenceName().equals(that.getReferenceName()); } return false; } if (that.isInterface()) { return false; } return this.typeOfThis.isEquivalentTo(that.typeOfThis) && this.call.isEquivalentTo(that.call); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<JSSourceFile> getDefaultExterns() { try { InputStream input = Compiler.class.getResourceAsStream( "/externs.zip"); ZipInputStream zip = new ZipInputStream(input); List<JSSourceFile> externs = Lists.newLinkedList(); for (ZipEntry entry; (entry = zip.getNextEntry()) != null; ) { LimitInputStream entryStream = new LimitInputStream(zip, entry.getSize()); externs.add( JSSourceFile.fromInputStream(entry.getName(), entryStream)); } return externs; } catch (IOException e) { throw new BuildException(e); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private List<JSSourceFile> getDefaultExterns() { try { return CommandLineRunner.getDefaultExterns(); } catch (IOException e) { throw new BuildException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Symbol getSymbolDeclaredBy(FunctionType fn) { Preconditions.checkState(fn.isConstructor() || fn.isInterface()); ObjectType instanceType = fn.getInstanceType(); String name = instanceType.getReferenceName(); if (name == null || globalScope == null) { return null; } Node source = fn.getSource(); return (source == null ? globalScope : getEnclosingScope(source)).getSlot(name); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public Symbol getSymbolDeclaredBy(FunctionType fn) { Preconditions.checkState(fn.isConstructor() || fn.isInterface()); ObjectType instanceType = fn.getInstanceType(); return getSymbolForName(fn.getSource(), instanceType.getReferenceName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void toDebugString(StringBuilder builder, Symbol symbol) { SymbolScope scope = symbol.scope; if (scope.isGlobalScope()) { builder.append( String.format("'%s' : in global scope:\n", symbol.getName())); } else { builder.append( String.format("'%s' : in scope %s:%d\n", symbol.getName(), scope.getRootNode().getSourceFileName(), scope.getRootNode().getLineno())); } int refCount = 0; for (Reference ref : getReferences(symbol)) { builder.append( String.format(" Ref %d: %s:%d\n", refCount, ref.getNode().getSourceFileName(), ref.getNode().getLineno())); refCount++; } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private void toDebugString(StringBuilder builder, Symbol symbol) { SymbolScope scope = symbol.scope; if (scope.isGlobalScope()) { builder.append( String.format("'%s' : in global scope:\n", symbol.getName())); } else if (scope.getRootNode() != null) { builder.append( String.format("'%s' : in scope %s:%d\n", symbol.getName(), scope.getRootNode().getSourceFileName(), scope.getRootNode().getLineno())); } else if (scope.getSymbolForScope() != null) { builder.append( String.format("'%s' : in scope %s\n", symbol.getName(), scope.getSymbolForScope().getName())); } else { builder.append( String.format("'%s' : in unknown scope\n", symbol.getName())); } int refCount = 0; for (Reference ref : getReferences(symbol)) { builder.append( String.format(" Ref %d: %s:%d\n", refCount, ref.getNode().getSourceFileName(), ref.getNode().getLineno())); refCount++; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void setSqlSource(MappedStatement ms) { MapperTemplate mapperTemplate = getMapperTemplate(ms.getId()); try { mapperTemplate.setSqlSource(ms); } catch (Exception e) { throw new RuntimeException("调用方法异常:" + e.getMessage()); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void setSqlSource(MappedStatement ms) { MapperTemplate mapperTemplate = getMapperTemplate(ms.getId()); try { if (mapperTemplate != null) { mapperTemplate.setSqlSource(ms); } } catch (Exception e) { throw new RuntimeException("调用方法异常:" + e.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected String read(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer stringBuffer = new StringBuffer(); String line = reader.readLine(); while (line != null) { stringBuffer.append(line).append("\n"); line = reader.readLine(); } return stringBuffer.toString(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code protected String read(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, encoding)); StringBuffer stringBuffer = new StringBuffer(); String line = reader.readLine(); while (line != null) { stringBuffer.append(line).append("\n"); line = reader.readLine(); } return stringBuffer.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { @SuppressWarnings("resource") ApplicationContext context = new ClassPathXmlApplicationContext("exampleContext.xml"); SpringCacheExample example = context.getBean(SpringCacheExample.class); example.getBook(0); example.getBook(0); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { example(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { Cache<Integer, Integer> cache = CacheBuilder.transactionalHeapCache() .transactionCommitter(new TransactionCommitter<Integer, Integer>() { int counter = 0; public void doPut(Integer key, Integer value) { if (counter < 3) { System.out.println("key[" + key + "]," + "value[" + value + "]"); counter++; } else { throw new RuntimeException(); } } }).build(); Transaction transaction1 = CacheTransaction.get(); transaction1.begin(); try { cache.put(3, 5); cache.put(10, 14); transaction1.commit(); } catch (TransactionException exception) { transaction1.rollback(); } finally { transaction1.close(); } System.out.println("Value for the key 3 is " + cache.get(3)); System.out.println("Value for the key 10 is " + cache.get(10)); Transaction transaction2 = CacheTransaction.get(); transaction2.begin(); try { cache.put(1, 10); cache.put(10, 13); transaction2.commit(); } catch (TransactionException exception) { transaction2.rollback(); } finally { transaction2.close(); } System.out.println("Value for the key 1 is " + cache.get(1)); System.out.println("Value for the key 10 is " + cache.get(10)); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { example(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { @SuppressWarnings({ "resource", "unused" }) ApplicationContext context = new ClassPathXmlApplicationContext("exampleContext.xml"); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) { example(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { Cache<Integer, Integer> cache = CacheBuilder.transactionalHeapCache() .transactionCommitter(new TransactionCommitter<Integer, Integer>() { int counter = 0; public void doPut(Integer key, Integer value) { if (counter < 3) { System.out.println("key[" + key + "]," + "value[" + value + "]"); counter++; } else { throw new RuntimeException(); } } }).build(); Transaction transaction1 = CacheTransaction.get(); transaction1.begin(); try { cache.put(3, 5); cache.put(10, 14); transaction1.commit(); } catch (TransactionException exception) { transaction1.rollback(); } finally { transaction1.close(); } System.out.println("Value for the key 3 is " + cache.get(3)); System.out.println("Value for the key 10 is " + cache.get(10)); Transaction transaction2 = CacheTransaction.get(); transaction2.begin(); try { cache.put(1, 10); cache.put(10, 13); transaction2.commit(); } catch (TransactionException exception) { transaction2.rollback(); } finally { transaction2.close(); } System.out.println("Value for the key 1 is " + cache.get(1)); System.out.println("Value for the key 10 is " + cache.get(10)); } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { example(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static void installDependencies(PrintStream logger, Launcher launcher, AndroidSdk sdk, EmulatorConfig emuConfig) throws IOException, InterruptedException { // Get AVD platform from emulator config String platform = getPlatformForEmulator(launcher, emuConfig); // Install platform and any dependencies it may have final boolean requiresAbi = emuConfig.getOsVersion().requiresAbi(); String abi = requiresAbi ? emuConfig.getTargetAbi() : null; installPlatform(logger, launcher, sdk, platform, abi, emuConfig.isNamedEmulator()); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code static void installDependencies(PrintStream logger, Launcher launcher, AndroidSdk sdk, EmulatorConfig emuConfig) throws IOException, InterruptedException { // Get AVD platform from emulator config String platform = getPlatformForEmulator(launcher, emuConfig); // Install platform and any dependencies it may have final boolean skipSystemImageInstall = emuConfig.isNamedEmulator() || !emuConfig.getOsVersion().requiresAbi(); installPlatform(logger, launcher, sdk, platform, emuConfig.getTargetAbi(), skipSystemImageInstall); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeAvdConfigFile(File homeDir, Map<String,String> values) throws FileNotFoundException { StringBuilder sb = new StringBuilder(); for (String key : values.keySet()) { sb.append(key); sb.append("="); sb.append(values.get(key)); sb.append("\r\n"); } File configFile = new File(getAvdDirectory(homeDir), "config.ini"); PrintWriter out = new PrintWriter(configFile); out.print(sb.toString()); out.flush(); out.close(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private void writeAvdConfigFile(File homeDir, Map<String,String> values) throws IOException { final File configFile = getAvdConfigFile(homeDir); ConfigFileUtils.writeConfigFile(configFile, values); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTargetName() { assertEquals("Google Inc.:Google APIs:23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getTargetName()); assertEquals("Google Inc.:Google APIs:24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getTargetName()); assertEquals("Apple Inc.:Apple APIs:24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getTargetName()); assertEquals("android-23", AndroidPlatform.valueOf("android-23").getTargetName()); assertEquals("android-24", AndroidPlatform.valueOf("android-24").getTargetName()); assertEquals("android-26", AndroidPlatform.valueOf("android-26").getTargetName()); assertEquals("android-10", AndroidPlatform.valueOf("2.3.3").getTargetName()); assertEquals("android-26", AndroidPlatform.valueOf("8.0").getTargetName()); assertEquals("android-26", AndroidPlatform.valueOf("26").getTargetName()); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testTargetName() { assertEquals("Some:Addon:11", AndroidPlatform.valueOf("Some:Addon:11").getTargetName()); assertEquals("Google Inc.:Google APIs:23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getTargetName()); assertEquals("Google Inc.:Google APIs:24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getTargetName()); assertEquals("Apple Inc.:Apple APIs:24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getTargetName()); assertEquals("android-23", AndroidPlatform.valueOf("android-23").getTargetName()); assertEquals("android-24", AndroidPlatform.valueOf("android-24").getTargetName()); assertEquals("android-26", AndroidPlatform.valueOf("android-26").getTargetName()); assertEquals("android-10", AndroidPlatform.valueOf("2.3.3").getTargetName()); assertEquals("android-26", AndroidPlatform.valueOf("8.0").getTargetName()); assertEquals("android-26", AndroidPlatform.valueOf("26").getTargetName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSystemImageName() { assertEquals("sys-img-x86-android-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("x86")); assertEquals("sys-img-x86-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86")); assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("x86_64")); assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("x86_64")); assertEquals("sys-img-armabi-v7a-android-23", AndroidPlatform.valueOf("android-23").getSystemImageName("armabi-v7a")); assertEquals("sys-img-armabi-v7a-android-24", AndroidPlatform.valueOf("android-24").getSystemImageName("armabi-v7a")); assertEquals("sys-img-arm64-v8a-android-26", AndroidPlatform.valueOf("android-26").getSystemImageName("arm64-v8a")); assertEquals("sys-img-x86-test-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("test/x86")); assertEquals("sys-img-x86-test-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("test/x86")); assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("test/x86_64")); assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("test/x86_64")); assertEquals("sys-img-armabi-v7a-test-23", AndroidPlatform.valueOf("android-23").getSystemImageName("test/armabi-v7a")); assertEquals("sys-img-armabi-v7a-test-24", AndroidPlatform.valueOf("android-24").getSystemImageName("test/armabi-v7a")); assertEquals("sys-img-arm64-v8a-test-26", AndroidPlatform.valueOf("android-26").getSystemImageName("test/arm64-v8a")); assertEquals("sys-img-x86-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("/x86")); assertEquals("sys-img-x86-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("///////x86")); assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64/")); assertEquals("sys-img-x86_64-android-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64////")); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testSystemImageName() { assertEquals("sys-img-x86-android-23", AndroidPlatform.valueOf("android-23").getSystemImageName("x86")); assertEquals("sys-img-x86-google_apis-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("x86")); assertEquals("sys-img-x86-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86")); assertEquals("sys-img-x86_64-apple_apis-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("x86_64")); assertEquals("sys-img-x86_64-ms_apis-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("x86_64")); assertEquals("sys-img-armabi-v7a-android-23", AndroidPlatform.valueOf("android-23").getSystemImageName("armabi-v7a")); assertEquals("sys-img-armabi-v7a-android-24", AndroidPlatform.valueOf("android-24").getSystemImageName("armabi-v7a")); assertEquals("sys-img-arm64-v8a-android-26", AndroidPlatform.valueOf("android-26").getSystemImageName("arm64-v8a")); assertEquals("sys-img-x86-test-23", AndroidPlatform.valueOf("Google Inc.:Google APIs:23").getSystemImageName("test/x86")); assertEquals("sys-img-x86-test-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("test/x86")); assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("Apple Inc.:Apple APIs:24").getSystemImageName("test/x86_64")); assertEquals("sys-img-x86_64-test-24", AndroidPlatform.valueOf("MS Company:MS APIs:24").getSystemImageName("test/x86_64")); assertEquals("sys-img-armabi-v7a-test-23", AndroidPlatform.valueOf("android-23").getSystemImageName("test/armabi-v7a")); assertEquals("sys-img-armabi-v7a-test-24", AndroidPlatform.valueOf("android-24").getSystemImageName("test/armabi-v7a")); assertEquals("sys-img-arm64-v8a-test-26", AndroidPlatform.valueOf("android-26").getSystemImageName("test/arm64-v8a")); assertEquals("sys-img-x86-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("/x86")); assertEquals("sys-img-x86-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("///////x86")); assertEquals("sys-img-x86_64-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64/")); assertEquals("sys-img-x86_64-google_apis-24", AndroidPlatform.valueOf("Google Inc.:Google APIs:24").getSystemImageName("x86_64////")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void determinesItemBSourceSetter() { Target target = new Target(); target.setItemB( new ItemB() ); SourceWithItemB source = new SourceWithItemB(); GenericsHierarchyMapper.INSTANCE.intoSourceWithItemB( target, source ); assertThat( source.getItem().typeParameterIsResolvedToItemB() ).isTrue(); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void determinesItemBSourceSetter() { Target target = new Target(); target.setKeyOfAllBeings( new KeyOfAllBeings() ); Child source = new Child(); GenericsHierarchyMapper.INSTANCE.updateSourceWithKeyOfAllBeings( target, source ); assertThat( source.getKey().typeParameterIsResolvedToKeyOfAllBeings() ).isTrue(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isIterableMapping() { return getSingleSourceType().isIterableType() && resultType.isIterableType(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isIterableMapping() { return getSingleSourceParameter().getType().isIterableType() && getResultType().isIterableType(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Mapping getMapping(MappingPrism mapping) { Type converterType = typeUtil.retrieveType( mapping.converter() ); return new Mapping( mapping.source(), mapping.target(), converterType.getName().equals( "NoOpConverter" ) ? null : converterType ); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private Mapping getMapping(MappingPrism mapping) { return new Mapping( mapping.source(), mapping.target() ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { Element returnTypeElement = typeUtils.asElement( method.getReturnType() ); Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( parameterElement.getEnclosedElements() ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( returnTypeElement.getEnclosedElements() ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingSetterMethod( parameterElement, getterMethod ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingGetterMethod( returnTypeElement, setterMethod ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) { for ( TypeElement oneAnnotation : annotations ) { //Indicates that the annotation's type isn't on the class path of the compiled //project. Let the compiler deal with that and print an appropriate error. if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) { continue; } for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) { oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv, configuration ), null ); } } return ANNOTATIONS_CLAIMED_EXCLUSIVELY; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean process( final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) { for ( TypeElement oneAnnotation : annotations ) { //Indicates that the annotation's type isn't on the class path of the compiled //project. Let the compiler deal with that and print an appropriate error. if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) { continue; } for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) { oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv ), null ); } } return ANNOTATIONS_CLAIMED_EXCLUSIVELY; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Mapper process(ProcessorContext context, TypeElement mapperTypeElement, Mapper mapper) { String componentModel = MapperPrism.getInstanceOn( mapperTypeElement ).componentModel(); if ( !componentModel.equals( "cdi" ) ) { return mapper; } mapper.addAnnotation( new Annotation( new Type( "javax.enterprise.context", "ApplicationScoped" ) ) ); ListIterator<MapperReference> iterator = mapper.getReferencedMappers().listIterator(); while ( iterator.hasNext() ) { MapperReference reference = iterator.next(); iterator.remove(); iterator.add( new CdiMapperReference( reference.getMapperType() ) ); } return mapper; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Mapper process(ProcessorContext context, TypeElement mapperTypeElement, Mapper mapper) { String componentModel = MapperPrism.getInstanceOn( mapperTypeElement ).componentModel(); String effectiveComponentModel = OptionsHelper.getEffectiveComponentModel( context.getOptions(), componentModel ); if ( !"cdi".equalsIgnoreCase( effectiveComponentModel ) ) { return mapper; } mapper.addAnnotation( new Annotation( new Type( "javax.enterprise.context", "ApplicationScoped" ) ) ); ListIterator<MapperReference> iterator = mapper.getReferencedMappers().listIterator(); while ( iterator.hasNext() ) { MapperReference reference = iterator.next(); iterator.remove(); iterator.add( new CdiMapperReference( reference.getMapperType() ) ); } return mapper; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { Element returnTypeElement = typeUtils.asElement( method.getReturnType() ); Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( parameterElement.getEnclosedElements() ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( returnTypeElement.getEnclosedElements() ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingSetterMethod( parameterElement, getterMethod ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingGetterMethod( returnTypeElement, setterMethod ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) { List<Method> methods = new ArrayList<Method>(); MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null; //TODO Extract to separate method for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) { Parameter parameter = executables.retrieveParameter( method ); Type returnType = executables.retrieveReturnType( method ); boolean mappingErroneous = false; if ( implementationRequired ) { if ( parameter.getType().isIterableType() && !returnType.isIterableType() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method from iterable type to non-iterable type.", method ); mappingErroneous = true; } if ( !parameter.getType().isIterableType() && returnType.isIterableType() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method from non-iterable type to iterable type.", method ); mappingErroneous = true; } if ( parameter.getType().isPrimitive() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method with primitive parameter type.", method ); mappingErroneous = true; } if ( returnType.isPrimitive() ) { printMessage( ReportingPolicy.ERROR, "Can't generate mapping method with primitive return type.", method ); mappingErroneous = true; } if ( mappingErroneous ) { continue; } } //add method with property mappings if an implementation needs to be generated if ( implementationRequired ) { methods.add( Method.forMethodRequiringImplementation( method, parameter.getName(), parameter.getType(), returnType, getMappings( method ) ) ); } //otherwise add reference to existing mapper method else { methods.add( Method.forReferencedMethod( typeUtil.getType( typeUtils.getDeclaredType( element ) ), method, parameter.getName(), parameter.getType(), returnType ) ); } } //Add all methods of used mappers in order to reference them in the aggregated model if ( implementationRequired ) { for ( TypeMirror usedMapper : mapperPrism.uses() ) { methods.addAll( retrieveMethods( (TypeElement) ( (DeclaredType) usedMapper ).asElement(), false ) ); } } return methods; } #location 57 #vulnerability type NULL_DEREFERENCE
#fixed code private List<Method> retrieveMethods(TypeElement element, boolean implementationRequired) { List<Method> methods = new ArrayList<Method>(); MapperPrism mapperPrism = implementationRequired ? MapperPrism.getInstanceOn( element ) : null; for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) { Method method = getMethod( element, executable, implementationRequired ); if ( method != null ) { methods.add( method ); } } //Add all methods of used mappers in order to reference them in the aggregated model if ( implementationRequired ) { for ( TypeMirror usedMapper : mapperPrism.uses() ) { methods.addAll( retrieveMethods( (TypeElement) ( (DeclaredType) usedMapper ).asElement(), false ) ); } } return methods; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences, List<Method> methods, Method method, Parameter parameter, ExecutableElement sourceAccessor, ExecutableElement targetAcessor, String dateFormat) { Type sourceType = typeFactory.getReturnType( sourceAccessor ); Type targetType = null; String conversionString = null; conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()"; if ( Executables.isSetterMethod( targetAcessor ) ) { targetType = typeFactory.getSingleParameter( targetAcessor ).getType(); } else if ( Executables.isGetterMethod( targetAcessor ) ) { targetType = typeFactory.getReturnType( targetAcessor ); } MethodReference propertyMappingMethod = getMappingMethodReference( mapperReferences, methods, sourceType, targetType ); TypeConversion conversion = getConversion( sourceType, targetType, dateFormat, conversionString ); PropertyMapping property = new PropertyMapping( parameter.getName(), Executables.getPropertyName( sourceAccessor ), sourceAccessor.getSimpleName().toString(), sourceType, Executables.getPropertyName( targetAcessor ), targetAcessor.getSimpleName().toString(), targetType, propertyMappingMethod, conversion ); reportErrorIfPropertyCanNotBeMapped( method, property ); return property; } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences, List<Method> methods, Method method, Parameter parameter, ExecutableElement sourceAccessor, ExecutableElement targetAcessor, String dateFormat) { Type sourceType = typeFactory.getReturnType( sourceAccessor ); Type targetType = null; String conversionString = null; conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()"; if ( Executables.isSetterMethod( targetAcessor ) ) { targetType = typeFactory.getSingleParameter( targetAcessor ).getType(); } else if ( Executables.isGetterMethod( targetAcessor ) ) { targetType = typeFactory.getReturnType( targetAcessor ); } MethodReference propertyMappingMethod = getMappingMethodReference( method, "property '" + Executables.getPropertyName( sourceAccessor ) + "'", mapperReferences, methods, sourceType, targetType ); TypeConversion conversion = getConversion( sourceType, targetType, dateFormat, conversionString ); PropertyMapping property = new PropertyMapping( parameter.getName(), Executables.getPropertyName( sourceAccessor ), sourceAccessor.getSimpleName().toString(), sourceType, Executables.getPropertyName( targetAcessor ), targetAcessor.getSimpleName().toString(), targetType, propertyMappingMethod, conversion ); reportErrorIfPropertyCanNotBeMapped( method, property ); return property; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isMapMapping() { return getSingleSourceType().isMapType() && resultType.isMapType(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean isMapMapping() { return getSingleSourceParameter().getType().isMapType() && getResultType().isMapType(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void deleteDirectory(File path) { if ( path.exists() ) { File[] files = path.listFiles(); for ( int i = 0; i < files.length; i++ ) { if ( files[i].isDirectory() ) { deleteDirectory( files[i] ); } else { files[i].delete(); } } } path.delete(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private void deleteDirectory(File path) { if ( path.exists() ) { File[] files = path.listFiles(); for ( File file : files ) { if ( file.isDirectory() ) { deleteDirectory( file ); } else { file.delete(); } } } path.delete(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Method> retrieveMethods(TypeElement element, boolean mapperRequiresImplementation) { List<Method> methods = new ArrayList<Method>(); MapperPrism mapperPrism = mapperRequiresImplementation ? MapperPrism.getInstanceOn( element ) : null; for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) { Method method = getMethod( element, executable, mapperRequiresImplementation ); if ( method != null ) { methods.add( method ); } } //Add all methods of used mappers in order to reference them in the aggregated model if ( mapperRequiresImplementation ) { for ( TypeMirror usedMapper : mapperPrism.uses() ) { methods.addAll( retrieveMethods( (TypeElement) ( (DeclaredType) usedMapper ).asElement(), false ) ); } } return methods; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private List<Method> retrieveMethods(TypeElement element, boolean mapperRequiresImplementation) { List<Method> methods = new ArrayList<Method>(); for ( ExecutableElement executable : methodsIn( element.getEnclosedElements() ) ) { Method method = getMethod( element, executable, mapperRequiresImplementation ); if ( method != null ) { methods.add( method ); } } //Add all methods of used mappers in order to reference them in the aggregated model if ( mapperRequiresImplementation ) { MapperPrism mapperPrism = MapperPrism.getInstanceOn( element ); if ( !mapperPrism.isValid ) { throw new AnnotationProcessingException( "Couldn't retrieve @Mapper annotation", element, mapperPrism.mirror ); } for ( TypeMirror usedMapper : mapperPrism.uses() ) { methods.addAll( retrieveMethods( (TypeElement) ( (DeclaredType) usedMapper ).asElement(), false ) ); } } return methods; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ); ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ); properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null, retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null, setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void determinesItemCSourceSetter() { Target target = new Target(); target.setItemC( new ItemC() ); SourceWithItemC source = new SourceWithItemC(); GenericsHierarchyMapper.INSTANCE.intoSourceWithItemC( target, source ); assertThat( source.getItem().typeParameterIsResolvedToItemC() ).isTrue(); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void determinesItemCSourceSetter() { Target target = new Target(); target.setAnimalKey( new AnimalKey() ); Elephant source = new Elephant(); GenericsHierarchyMapper.INSTANCE.updateSourceWithAnimalKey( target, source ); assertThat( source.getKey().typeParameterIsResolvedToAnimalKey() ).isTrue(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private MappingMethod getBeanMappingMethod(List<Method> methods, Method method, ReportingPolicy unmappedTargetPolicy) { List<PropertyMapping> propertyMappings = new ArrayList<PropertyMapping>(); Set<String> mappedTargetProperties = new HashSet<String>(); Map<String, Mapping> mappings = method.getMappings(); TypeElement resultTypeElement = elementUtils.getTypeElement( method.getResultType().getCanonicalName() ); TypeElement parameterElement = elementUtils.getTypeElement( method.getSingleSourceType().getCanonicalName() ); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( resultTypeElement ) ); Set<String> sourceProperties = executables.getPropertyNames( Filters.getterMethodsIn( sourceGetters ) ); Set<String> targetProperties = executables.getPropertyNames( Filters.setterMethodsIn( targetSetters ) ); reportErrorIfMappedPropertiesDontExist( method, sourceProperties, targetProperties ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); String dateFormat = mapping != null ? mapping.getDateFormat() : null; for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { PropertyMapping property = getPropertyMapping( methods, method, getterMethod, setterMethod, dateFormat ); propertyMappings.add( property ); mappedTargetProperties.add( targetPropertyName ); } } } reportErrorForUnmappedTargetPropertiesIfRequired( method, unmappedTargetPolicy, targetProperties, mappedTargetProperties ); return new BeanMappingMethod( method.getName(), method.getParameters(), method.getSourceParameters(), method.getResultType(), method.getResultName(), method.getReturnType(), propertyMappings ); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private MappingMethod getBeanMappingMethod(List<Method> methods, Method method, ReportingPolicy unmappedTargetPolicy) { List<PropertyMapping> propertyMappings = new ArrayList<PropertyMapping>(); Set<String> mappedTargetProperties = new HashSet<String>(); Map<String, Mapping> mappings = method.getMappings(); TypeElement resultTypeElement = elementUtils.getTypeElement( method.getResultType().getCanonicalName() ); TypeElement parameterElement = elementUtils.getTypeElement( method.getSingleSourceParameter() .getType() .getCanonicalName() ); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( resultTypeElement ) ); Set<String> sourceProperties = executables.getPropertyNames( Filters.getterMethodsIn( sourceGetters ) ); Set<String> targetProperties = executables.getPropertyNames( Filters.setterMethodsIn( targetSetters ) ); reportErrorIfMappedPropertiesDontExist( method, sourceProperties, targetProperties ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); String dateFormat = mapping != null ? mapping.getDateFormat() : null; for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { PropertyMapping property = getPropertyMapping( methods, method, getterMethod, setterMethod, dateFormat ); propertyMappings.add( property ); mappedTargetProperties.add( targetPropertyName ); } } } reportErrorForUnmappedTargetPropertiesIfRequired( method, unmappedTargetPolicy, targetProperties, mappedTargetProperties ); return new BeanMappingMethod( method, propertyMappings ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean matches() { // check & collect generic types. List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters(); if ( candidateParameters.size() == parameters.length ) { for ( int i = 0; i < parameters.length; i++ ) { TypeMatcher parameterMatcher = new TypeMatcher(); typesMatch = parameterMatcher.visit( candidateParameters.get( i ).asType(), parameters[i].getTypeMirror() ); if ( !typesMatch ) { break; } } } else { typesMatch = false; } // check return type if ( typesMatch ) { TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType(); TypeMatcher returnTypeMatcher = new TypeMatcher(); typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() ); } // check if all type parameters are indeed mapped if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) { typesMatch = false; } else { // check if all entries are in the bounds for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) { if (!isWithinBounds( entry.getValue(), getTypeParamFromCandite( entry.getKey() ) ) ) { // checks if the found Type is in bounds of the TypeParameters bounds. typesMatch = false; } } } return typesMatch; } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean matches() { // check & collect generic types. List<? extends VariableElement> candidateParameters = candidateMethod.getExecutable().getParameters(); if ( candidateParameters.size() != 1 ) { typesMatch = false; } else { TypeMatcher parameterMatcher = new TypeMatcher(); typesMatch = parameterMatcher.visit( candidateParameters.iterator().next().asType(), parameter.getTypeMirror() ); } // check return type if ( typesMatch ) { TypeMirror candidateReturnType = candidateMethod.getExecutable().getReturnType(); TypeMatcher returnTypeMatcher = new TypeMatcher(); typesMatch = returnTypeMatcher.visit( candidateReturnType, returnType.getTypeMirror() ); } // check if all type parameters are indeed mapped if ( candidateMethod.getExecutable().getTypeParameters().size() != this.genericTypesMap.size() ) { typesMatch = false; } else { // check if all entries are in the bounds for (Map.Entry<TypeVariable, TypeMirror> entry : genericTypesMap.entrySet()) { if (!isWithinBounds( entry.getValue(), getTypeParamFromCandidate( entry.getKey() ) ) ) { // checks if the found Type is in bounds of the TypeParameters bounds. typesMatch = false; } } } return typesMatch; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Mapper retrieveModel(TypeElement element) { //1.) build up "source" model List<Method> methods = retrieveMethods( element, true ); //2.) build up aggregated "target" model List<BeanMapping> mappings = getMappings( methods, ReportingPolicy.valueOf( MapperPrism.getInstanceOn( element ).unmappedTargetPolicy() ) ); List<Type> usedMapperTypes = getUsedMapperTypes( element ); Mapper mapper = new Mapper( elementUtils.getPackageOf( element ).getQualifiedName().toString(), element.getSimpleName().toString(), element.getSimpleName() + IMPLEMENTATION_SUFFIX, mappings, usedMapperTypes, options ); return mapper; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private Mapper retrieveModel(TypeElement element) { //1.) build up "source" model List<Method> methods = retrieveMethods( element, true ); //2.) build up aggregated "target" model List<BeanMapping> mappings = getMappings( methods, getEffectiveUnmappedTargetPolicy( element ) ); List<Type> usedMapperTypes = getUsedMapperTypes( element ); Mapper mapper = new Mapper( elementUtils.getPackageOf( element ).getQualifiedName().toString(), element.getSimpleName().toString(), element.getSimpleName() + IMPLEMENTATION_SUFFIX, mappings, usedMapperTypes, options ); return mapper; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ); ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ); properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null, retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null, setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private PropertyMapping getConstantMapping(List<MapperReference> mapperReferences, List<SourceMethod> methods, SourceMethod method, String constantExpression, ExecutableElement targetAccessor, String dateFormat, List<TypeMirror> qualifiers) { // source String mappedElement = "constant '" + constantExpression + "'"; Type sourceType = typeFactory.getType( String.class ); // target Type targetType = typeFactory.getSingleParameter( targetAccessor ).getType(); String targetPropertyName = Executables.getPropertyName( targetAccessor ); Assignment assignment = mappingResolver.getTargetAssignment( method, mappedElement, mapperReferences, methods, sourceType, targetType, targetPropertyName, dateFormat, qualifiers, constantExpression ); if ( assignment != null ) { // target accessor is setter, so decorate assignment as setter assignment = new SetterWrapper( assignment, method.getThrownTypes() ); } else { messager.printMessage( Kind.ERROR, String.format( "Can't map \"%s %s\" to \"%s %s\".", sourceType, constantExpression, targetType, targetPropertyName ), method.getExecutable() ); } return new PropertyMapping( targetAccessor.getSimpleName().toString(), targetType, assignment ); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code private PropertyMapping getConstantMapping(List<MapperReference> mapperReferences, List<SourceMethod> methods, SourceMethod method, String constantExpression, ExecutableElement targetAccessor, String dateFormat, List<TypeMirror> qualifiers) { // source String mappedElement = "constant '" + constantExpression + "'"; Type sourceType = typeFactory.getType( String.class ); // target Type targetType; if ( Executables.isSetterMethod( targetAccessor ) ) { targetType = typeFactory.getSingleParameter( targetAccessor ).getType(); } else { targetType = typeFactory.getReturnType( targetAccessor ); } String targetPropertyName = Executables.getPropertyName( targetAccessor ); Assignment assignment = mappingResolver.getTargetAssignment( method, mappedElement, mapperReferences, methods, sourceType, targetType, targetPropertyName, dateFormat, qualifiers, constantExpression ); if ( assignment != null ) { // target accessor is setter, so decorate assignment as setter assignment = new SetterWrapper( assignment, method.getThrownTypes() ); // wrap when dealing with getter only on target if ( Executables.isGetterMethod( targetAccessor ) ) { assignment = new GetterCollectionOrMapWrapper( assignment ); } } else { messager.printMessage( Kind.ERROR, String.format( "Can't map \"%s %s\" to \"%s %s\".", sourceType, constantExpression, targetType, targetPropertyName ), method.getExecutable() ); } return new PropertyMapping( targetAccessor.getSimpleName().toString(), targetType, assignment ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void reportErrorIfPropertyCanNotBeMapped(Method method, PropertyMapping property) { if ( property.getSourceType().equals( property.getTargetType() ) || property.getMappingMethod() != null || property.getConversion() != null || property.getTargetType().getImplementationType() != null ) { return; } messager.printMessage( Kind.ERROR, String.format( "Can't map property \"%s %s\" to \"%s %s\".", property.getSourceType().getName(), property.getSourceName(), property.getTargetType().getName(), property.getTargetName() ), method.getExecutable() ); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private void reportErrorIfPropertyCanNotBeMapped(Method method, PropertyMapping property) { if ( property.getSourceType().isAssignableTo( property.getTargetType() ) || property.getMappingMethod() != null || property.getConversion() != null || property.getTargetType().getImplementationType() != null ) { return; } messager.printMessage( Kind.ERROR, String.format( "Can't map property \"%s %s\" to \"%s %s\".", property.getSourceType(), property.getSourceName(), property.getTargetType(), property.getTargetName() ), method.getExecutable() ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) .getSimpleName() .toString(), retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) .getSimpleName() .toString(), setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; } #location 43 #vulnerability type NULL_DEREFERENCE
#fixed code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); List<ExecutableElement> sourceGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); List<ExecutableElement> sourceSetters = Filters.setterMethodsIn( elementUtils.getAllMembers( parameterElement ) ); List<ExecutableElement> targetGetters = Filters.getterMethodsIn( elementUtils.getAllMembers( returnTypeElement ) ); reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); for ( ExecutableElement getterMethod : sourceGetters ) { String sourcePropertyName = Executables.getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : targetSetters ) { String targetPropertyName = Executables.getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ); ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ); properties.add( new MappedProperty( sourcePropertyName, getterMethod.getSimpleName().toString(), correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null, retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null, setterMethod.getSimpleName().toString(), retrieveParameter( setterMethod ).getType() ) ); } } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences, List<SourceMethod> methods, SourceMethod method, Parameter parameter, ExecutableElement sourceAccessor, ExecutableElement targetAcessor, String dateFormat) { Type sourceType = typeFactory.getReturnType( sourceAccessor ); Type targetType = null; String conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()"; if ( Executables.isSetterMethod( targetAcessor ) ) { targetType = typeFactory.getSingleParameter( targetAcessor ).getType(); } else if ( Executables.isGetterMethod( targetAcessor ) ) { targetType = typeFactory.getReturnType( targetAcessor ); } String targetPropertyName = Executables.getPropertyName( targetAcessor ); String mappedElement = "property '" + Executables.getPropertyName( sourceAccessor ) + "'"; MethodReference mappingMethodReference = mappingMethodResolver.getMappingMethodReferenceBasedOnMethod( method, mappedElement, mapperReferences, methods, sourceType, targetType, targetPropertyName, dateFormat ); TypeConversion conversion = mappingMethodResolver.getConversion( sourceType, targetType, dateFormat, conversionString ); PropertyMapping property = new PropertyMapping( parameter.getName(), Executables.getPropertyName( sourceAccessor ), sourceAccessor.getSimpleName().toString(), sourceType, Executables.getPropertyName( targetAcessor ), targetAcessor.getSimpleName().toString(), targetType, mappingMethodReference, conversion ); if ( !isPropertyMappable( property ) ) { // when not mappable, try again with another property mapping method based on parameter only. mappingMethodReference = mappingMethodResolver.getMappingMethodReferenceBasedOnParameter( method, "property '" + Executables.getPropertyName( sourceAccessor ) + "'", mapperReferences, methods, sourceType, targetType, targetPropertyName, dateFormat ); property = new PropertyMapping( parameter.getName(), Executables.getPropertyName( sourceAccessor ), sourceAccessor.getSimpleName().toString(), sourceType, Executables.getPropertyName( targetAcessor ), targetAcessor.getSimpleName().toString(), targetType, mappingMethodReference, conversion ); } if ( !isPropertyMappable( property ) ) { messager.printMessage( Kind.ERROR, String.format( "Can't map property \"%s %s\" to \"%s %s\".", property.getSourceType(), property.getSourceName(), property.getTargetType(), property.getTargetName() ), method.getExecutable() ); } return property; } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code private PropertyMapping getPropertyMapping(List<MapperReference> mapperReferences, List<SourceMethod> methods, SourceMethod method, Parameter parameter, ExecutableElement sourceAccessor, ExecutableElement targetAcessor, String dateFormat) { Type sourceType = typeFactory.getReturnType( sourceAccessor ); Type targetType = null; String conversionString = parameter.getName() + "." + sourceAccessor.getSimpleName().toString() + "()"; if ( Executables.isSetterMethod( targetAcessor ) ) { targetType = typeFactory.getSingleParameter( targetAcessor ).getType(); } else if ( Executables.isGetterMethod( targetAcessor ) ) { targetType = typeFactory.getReturnType( targetAcessor ); } String targetPropertyName = Executables.getPropertyName( targetAcessor ); String mappedElement = "property '" + Executables.getPropertyName( sourceAccessor ) + "'"; ParameterAssignment parameterAssignment = mappingResolver.getParameterAssignment( method, mappedElement, mapperReferences, methods, sourceType, targetType, targetPropertyName, dateFormat, conversionString ); PropertyMapping property = new PropertyMapping( parameter.getName(), Executables.getPropertyName( sourceAccessor ), sourceAccessor.getSimpleName().toString(), sourceType, Executables.getPropertyName( targetAcessor ), targetAcessor.getSimpleName().toString(), targetType, parameterAssignment != null ? parameterAssignment.getMethodReference() : null, parameterAssignment != null ? parameterAssignment.getTypeConversion() : null ); if ( !isPropertyMappable( property ) ) { messager.printMessage( Kind.ERROR, String.format( "Can't map property \"%s %s\" to \"%s %s\".", property.getSourceType(), property.getSourceName(), property.getTargetType(), property.getTargetName() ), method.getExecutable() ); } return property; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Type getType(TypeMirror mirror, boolean isLiteral) { if ( !canBeProcessed( mirror ) ) { throw new TypeHierarchyErroneousException( mirror ); } ImplementationType implementationType = getImplementationType( mirror ); boolean isIterableType = typeUtils.isSubtype( mirror, iterableType ); boolean isCollectionType = typeUtils.isSubtype( mirror, collectionType ); boolean isMapType = typeUtils.isSubtype( mirror, mapType ); boolean isStreamType = streamType != null && typeUtils.isSubtype( mirror, streamType ); boolean isEnumType; boolean isInterface; String name; String packageName; String qualifiedName; TypeElement typeElement; Type componentType; Boolean toBeImported = null; if ( mirror.getKind() == TypeKind.DECLARED ) { DeclaredType declaredType = (DeclaredType) mirror; isEnumType = declaredType.asElement().getKind() == ElementKind.ENUM; isInterface = declaredType.asElement().getKind() == ElementKind.INTERFACE; name = declaredType.asElement().getSimpleName().toString(); typeElement = (TypeElement) declaredType.asElement(); if ( typeElement != null ) { packageName = elementUtils.getPackageOf( typeElement ).getQualifiedName().toString(); qualifiedName = typeElement.getQualifiedName().toString(); } else { packageName = null; qualifiedName = name; } componentType = null; } else if ( mirror.getKind() == TypeKind.ARRAY ) { TypeMirror componentTypeMirror = getComponentType( mirror ); StringBuilder builder = new StringBuilder("[]"); while ( componentTypeMirror.getKind() == TypeKind.ARRAY ) { componentTypeMirror = getComponentType( componentTypeMirror ); builder.append( "[]" ); } if ( componentTypeMirror.getKind() == TypeKind.DECLARED ) { DeclaredType declaredType = (DeclaredType) componentTypeMirror; TypeElement componentTypeElement = (TypeElement) declaredType.asElement(); String arraySuffix = builder.toString(); name = componentTypeElement.getSimpleName().toString() + arraySuffix; packageName = elementUtils.getPackageOf( componentTypeElement ).getQualifiedName().toString(); qualifiedName = componentTypeElement.getQualifiedName().toString() + arraySuffix; } else if (componentTypeMirror.getKind().isPrimitive()) { // When the component type is primitive and is annotated with ElementType.TYPE_USE then // the typeMirror#toString returns (@CustomAnnotation :: byte) for the javac compiler name = NativeTypes.getName( componentTypeMirror.getKind() ) + builder.toString(); packageName = null; // for primitive types only name (e.g. byte, short..) required as qualified name qualifiedName = name; toBeImported = false; } else { name = mirror.toString(); packageName = null; qualifiedName = name; toBeImported = false; } isEnumType = false; isInterface = false; typeElement = null; componentType = getType( getComponentType( mirror ) ); } else { isEnumType = false; isInterface = false; name = mirror.toString(); packageName = null; qualifiedName = name; typeElement = null; componentType = null; toBeImported = false; } return new Type( typeUtils, elementUtils, this, roundContext.getAnnotationProcessorContext().getAccessorNaming(), mirror, typeElement, getTypeParameters( mirror, false ), implementationType, componentType, packageName, name, qualifiedName, isInterface, isEnumType, isIterableType, isCollectionType, isMapType, isStreamType, toBeImportedTypes, notToBeImportedTypes, toBeImported, isLiteral, loggingVerbose ); } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code private Type getType(TypeMirror mirror, boolean isLiteral) { if ( !canBeProcessed( mirror ) ) { throw new TypeHierarchyErroneousException( mirror ); } ImplementationType implementationType = getImplementationType( mirror ); boolean isIterableType = typeUtils.isSubtype( mirror, iterableType ); boolean isCollectionType = typeUtils.isSubtype( mirror, collectionType ); boolean isMapType = typeUtils.isSubtype( mirror, mapType ); boolean isStreamType = streamType != null && typeUtils.isSubtype( mirror, streamType ); boolean isEnumType; boolean isInterface; String name; String packageName; String qualifiedName; TypeElement typeElement; Type componentType; Boolean toBeImported = null; if ( mirror.getKind() == TypeKind.DECLARED ) { DeclaredType declaredType = (DeclaredType) mirror; isEnumType = declaredType.asElement().getKind() == ElementKind.ENUM; isInterface = declaredType.asElement().getKind() == ElementKind.INTERFACE; name = declaredType.asElement().getSimpleName().toString(); typeElement = (TypeElement) declaredType.asElement(); if ( typeElement != null ) { packageName = elementUtils.getPackageOf( typeElement ).getQualifiedName().toString(); qualifiedName = typeElement.getQualifiedName().toString(); } else { packageName = null; qualifiedName = name; } componentType = null; } else if ( mirror.getKind() == TypeKind.ARRAY ) { TypeMirror componentTypeMirror = getComponentType( mirror ); StringBuilder builder = new StringBuilder("[]"); while ( componentTypeMirror.getKind() == TypeKind.ARRAY ) { componentTypeMirror = getComponentType( componentTypeMirror ); builder.append( "[]" ); } if ( componentTypeMirror.getKind() == TypeKind.DECLARED ) { DeclaredType declaredType = (DeclaredType) componentTypeMirror; TypeElement componentTypeElement = (TypeElement) declaredType.asElement(); String arraySuffix = builder.toString(); name = componentTypeElement.getSimpleName().toString() + arraySuffix; packageName = elementUtils.getPackageOf( componentTypeElement ).getQualifiedName().toString(); qualifiedName = componentTypeElement.getQualifiedName().toString() + arraySuffix; } else if (componentTypeMirror.getKind().isPrimitive()) { // When the component type is primitive and is annotated with ElementType.TYPE_USE then // the typeMirror#toString returns (@CustomAnnotation :: byte) for the javac compiler name = NativeTypes.getName( componentTypeMirror.getKind() ) + builder.toString(); packageName = null; // for primitive types only name (e.g. byte, short..) required as qualified name qualifiedName = name; toBeImported = false; } else { name = mirror.toString(); packageName = null; qualifiedName = name; toBeImported = false; } isEnumType = false; isInterface = false; typeElement = null; componentType = getType( getComponentType( mirror ) ); } else { isEnumType = false; isInterface = false; // When the component type is primitive and is annotated with ElementType.TYPE_USE then // the typeMirror#toString returns (@CustomAnnotation :: byte) for the javac compiler name = mirror.getKind().isPrimitive() ? NativeTypes.getName( mirror.getKind() ) : mirror.toString(); packageName = null; qualifiedName = name; typeElement = null; componentType = null; toBeImported = false; } return new Type( typeUtils, elementUtils, this, roundContext.getAnnotationProcessorContext().getAccessorNaming(), mirror, typeElement, getTypeParameters( mirror, false ), implementationType, componentType, packageName, name, qualifiedName, isInterface, isEnumType, isIterableType, isCollectionType, isMapType, isStreamType, toBeImportedTypes, notToBeImportedTypes, toBeImported, isLiteral, loggingVerbose ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { Element returnTypeElement = typeUtils.asElement( method.getReturnType() ); Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); for ( ExecutableElement getterMethod : getterMethodsIn( parameterElement.getEnclosedElements() ) ) { String sourcePropertyName = Introspector.decapitalize( getterMethod.getSimpleName() .toString() .substring( 3 ) ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : setterMethodsIn( returnTypeElement.getEnclosedElements() ) ) { String targetPropertyName = Introspector.decapitalize( setterMethod.getSimpleName() .toString() .substring( 3 ) ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, retrieveParameter( setterMethod ).getType(), mapping != null ? mapping.getConverterType() : null ) ); } } } return properties; } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) { Element returnTypeElement = typeUtils.asElement( method.getReturnType() ); Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() ); List<MappedProperty> properties = new ArrayList<MappedProperty>(); for ( ExecutableElement getterMethod : getterMethodsIn( parameterElement.getEnclosedElements() ) ) { String sourcePropertyName = getPropertyName( getterMethod ); Mapping mapping = mappings.get( sourcePropertyName ); for ( ExecutableElement setterMethod : setterMethodsIn( returnTypeElement.getEnclosedElements() ) ) { String targetPropertyName = getPropertyName( setterMethod ); if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { properties.add( new MappedProperty( sourcePropertyName, retrieveReturnType( getterMethod ), mapping != null ? mapping.getTargetName() : targetPropertyName, retrieveParameter( setterMethod ).getType(), mapping != null ? mapping.getConverterType() : null ) ); } } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toTypedArray(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index); try { return new ArrayBuffer(buffer.getBackingStore()); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toTypedArray(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) { if (!nativeLibraryLoaded) { synchronized (lock) { if (!nativeLibraryLoaded) { load(tempDirectory); } } } checkNativeLibraryLoaded(); if (!initialized) { _setFlags(v8Flags); initialized = true; } if (debugThread == null) { debugThread = Thread.currentThread(); } V8 runtime = new V8(globalAlias); synchronized (lock) { runtimeCounter++; } return runtime; } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) { if (!nativeLibraryLoaded) { synchronized (lock) { if (!nativeLibraryLoaded) { load(tempDirectory); } } } checkNativeLibraryLoaded(); if (!initialized) { _setFlags(v8Flags); initialized = true; } V8 runtime = new V8(globalAlias); synchronized (lock) { runtimeCounter++; } return runtime; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); if (debugEnabled) { disableDebugSupport(); } releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void release(final boolean reportMemoryLeaks) { checkThread(); if (isReleased()) { return; } if (debugEnabled) { disableDebugSupport(); } runtimeCounter--; _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void release(final boolean reportMemoryLeaks) { checkThread(); if (isReleased()) { return; } if (debugEnabled) { disableDebugSupport(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) { int valueType = object.getType(key); switch (valueType) { case V8Value.INTEGER: return object.getInteger(key); case V8Value.DOUBLE: return object.getDouble(key); case V8Value.BOOLEAN: return object.getBoolean(key); case V8Value.STRING: return object.getString(key); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) object.get(key); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = object.getArray(key); try { return toByteBuffer(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array array = object.getArray(key); try { return toList(array, cache); } finally { if (array instanceof V8Array) { array.release(); } } case V8Value.V8_OBJECT: V8Object child = object.getObject(key); try { return toMap(child, cache); } finally { if (child instanceof V8Object) { child.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for key: " + key); } } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) { int valueType = object.getType(key); switch (valueType) { case V8Value.INTEGER: return object.getInteger(key); case V8Value.DOUBLE: return object.getDouble(key); case V8Value.BOOLEAN: return object.getBoolean(key); case V8Value.STRING: return object.getString(key); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) object.get(key); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = object.getArray(key); try { return toTypedArray(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array array = object.getArray(key); try { return toList(array, cache); } finally { if (array instanceof V8Array) { array.release(); } } case V8Value.V8_OBJECT: V8Object child = object.getObject(key); try { return toMap(child, cache); } finally { if (child instanceof V8Object) { child.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for key: " + key); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) { if (!nativeLibraryLoaded) { synchronized (lock) { if (!nativeLibraryLoaded) { load(tempDirectory); } } } checkNativeLibraryLoaded(); if (!initialized) { _setFlags(v8Flags); initialized = true; } if (debugThread == null) { debugThread = Thread.currentThread(); } V8 runtime = new V8(globalAlias); synchronized (lock) { runtimeCounter++; } return runtime; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static V8 createV8Runtime(final String globalAlias, final String tempDirectory) { if (!nativeLibraryLoaded) { synchronized (lock) { if (!nativeLibraryLoaded) { load(tempDirectory); } } } checkNativeLibraryLoaded(); if (!initialized) { _setFlags(v8Flags); initialized = true; } V8 runtime = new V8(globalAlias); synchronized (lock) { runtimeCounter++; } return runtime; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toByteBuffer(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) array.get(index); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toTypedArray(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); try { notifyReleaseHandlers(this); } finally { releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } releaseNativeMethodDescriptors(); synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (getObjectReferenceCount() > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } } } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); try { notifyReleaseHandlers(this); } finally { releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } releaseNativeMethodDescriptors(); synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (getObjectReferenceCount() > 0)) { throw new IllegalStateException(getObjectReferenceCount() + " Object(s) still exist in runtime"); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return ((V8TypedArray) typedArray).getByteBuffer(); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Array array, final int index, final V8Map<Object> cache) { int valueType = array.getType(index); switch (valueType) { case V8Value.INTEGER: return array.getInteger(index); case V8Value.DOUBLE: return array.getDouble(index); case V8Value.BOOLEAN: return array.getBoolean(index); case V8Value.STRING: return array.getString(index); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_TYPED_ARRAY: V8Array typedArray = array.getArray(index); try { return toByteBuffer(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array arrayValue = array.getArray(index); try { return toList(arrayValue, cache); } finally { if (arrayValue instanceof V8Array) { arrayValue.release(); } } case V8Value.V8_OBJECT: V8Object objectValue = array.getObject(index); try { return toMap(objectValue, cache); } finally { if (objectValue instanceof V8Object) { objectValue.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for index: " + index); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTypedArrayGetValue_Float32Array() { V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(100);\n" + "var floatsArray = new Float32Array(buf);\n" + "floatsArray[0] = 16.2;\n" + "floatsArray;\n"); V8TypedArray result = (V8TypedArray) V8ObjectUtils.getValue(floatsArray); assertEquals(25, result.length()); assertEquals(16.2, (Float) result.get(0), 0.00001); floatsArray.close(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testTypedArrayGetValue_Float32Array() { V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(100);\n" + "var floatsArray = new Float32Array(buf);\n" + "floatsArray[0] = 16.2;\n" + "floatsArray;\n"); V8TypedArray result = ((TypedArray) V8ObjectUtils.getValue(floatsArray)).getV8TypedArray(); assertEquals(25, result.length()); assertEquals(16.2, (Float) result.get(0), 0.00001); floatsArray.close(); result.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) { int valueType = object.getType(key); switch (valueType) { case V8Value.INTEGER: return object.getInteger(key); case V8Value.DOUBLE: return object.getDouble(key); case V8Value.BOOLEAN: return object.getBoolean(key); case V8Value.STRING: return object.getString(key); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_TYPED_ARRAY: V8Array typedArray = object.getArray(key); try { return toByteBuffer(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array array = object.getArray(key); try { return toList(array, cache); } finally { if (array instanceof V8Array) { array.release(); } } case V8Value.V8_OBJECT: V8Object child = object.getObject(key); try { return toMap(child, cache); } finally { if (child instanceof V8Object) { child.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for key: " + key); } } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) { int valueType = object.getType(key); switch (valueType) { case V8Value.INTEGER: return object.getInteger(key); case V8Value.DOUBLE: return object.getDouble(key); case V8Value.BOOLEAN: return object.getBoolean(key); case V8Value.STRING: return object.getString(key); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_ARRAY_BUFFER: V8ArrayBuffer buffer = (V8ArrayBuffer) object.get(key); try { return buffer.getBackingStore(); } finally { buffer.release(); } case V8Value.V8_TYPED_ARRAY: V8Array typedArray = object.getArray(key); try { return toByteBuffer(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array array = object.getArray(key); try { return toList(array, cache); } finally { if (array instanceof V8Array) { array.release(); } } case V8Value.V8_OBJECT: V8Object child = object.getObject(key); try { return toMap(child, cache); } finally { if (child instanceof V8Object) { child.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for key: " + key); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); if (debugEnabled) { disableDebugSupport(); } releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void release(final boolean reportMemoryLeaks) { if (isReleased()) { return; } checkThread(); releaseResources(); shutdownExecutors(forceTerminateExecutors); if (executors != null) { executors.clear(); } synchronized (lock) { runtimeCounter--; } _releaseRuntime(v8RuntimePtr); v8RuntimePtr = 0L; released = true; if (reportMemoryLeaks && (objectReferences > 0)) { throw new IllegalStateException(objectReferences + " Object(s) still exist in runtime"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTypedArrayGetValue_Float64Array() { V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n" + "var floatsArray = new Float64Array(buf);\n" + "floatsArray[0] = 16.2;\n" + "floatsArray;\n"); V8TypedArray result = (V8TypedArray) V8ObjectUtils.getValue(floatsArray); assertEquals(10, result.length()); assertEquals(16.2, (Double) result.get(0), 0.0001); floatsArray.close(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testTypedArrayGetValue_Float64Array() { V8Array floatsArray = v8.executeArrayScript("var buf = new ArrayBuffer(80);\n" + "var floatsArray = new Float64Array(buf);\n" + "floatsArray[0] = 16.2;\n" + "floatsArray;\n"); V8TypedArray result = ((TypedArray) V8ObjectUtils.getValue(floatsArray)).getV8TypedArray(); assertEquals(10, result.length()); assertEquals(16.2, (Double) result.get(0), 0.0001); floatsArray.close(); result.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) { int valueType = object.getType(key); switch (valueType) { case V8Value.INTEGER: return object.getInteger(key); case V8Value.DOUBLE: return object.getDouble(key); case V8Value.BOOLEAN: return object.getBoolean(key); case V8Value.STRING: return object.getString(key); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_TYPED_ARRAY: V8Array typedArray = object.getArray(key); try { return ((V8TypedArray) typedArray).getByteBuffer(); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array array = object.getArray(key); try { return toList(array, cache); } finally { if (array instanceof V8Array) { array.release(); } } case V8Value.V8_OBJECT: V8Object child = object.getObject(key); try { return toMap(child, cache); } finally { if (child instanceof V8Object) { child.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for key: " + key); } } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private static Object getValue(final V8Object object, final String key, final V8Map<Object> cache) { int valueType = object.getType(key); switch (valueType) { case V8Value.INTEGER: return object.getInteger(key); case V8Value.DOUBLE: return object.getDouble(key); case V8Value.BOOLEAN: return object.getBoolean(key); case V8Value.STRING: return object.getString(key); case V8Value.V8_FUNCTION: return IGNORE; case V8Value.V8_TYPED_ARRAY: V8Array typedArray = object.getArray(key); try { return toByteBuffer(typedArray); } finally { if (typedArray instanceof V8Array) { typedArray.release(); } } case V8Value.V8_ARRAY: V8Array array = object.getArray(key); try { return toList(array, cache); } finally { if (array instanceof V8Array) { array.release(); } } case V8Value.V8_OBJECT: V8Object child = object.getObject(key); try { return toMap(child, cache); } finally { if (child instanceof V8Object) { child.release(); } } case V8Value.NULL: return null; case V8Value.UNDEFINED: return V8.getUndefined(); default: throw new IllegalStateException("Cannot find type for key: " + key); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean enableDebugSupport(final int port, final boolean waitForConnection) { V8.checkDebugThread(); debugEnabled = enableDebugSupport(getHandle(), port, waitForConnection); return debugEnabled; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public boolean enableDebugSupport(final int port, final boolean waitForConnection) { V8.checkDebugThread(); debugEnabled = enableDebugSupport(getV8RuntimePtr(), port, waitForConnection); return debugEnabled; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public CommandLine parse(final String[] args) throws ParseException, IllegalArgumentException { final CommandLine cmd = super.parse(args); final Report report = ReportFactory.createReport(cmd, ReportType.REDIS); ExtractionResult match = null; if (cmd.hasOption("reporter-status")) { match = ExtractionResult.get(((Number) cmd.getParsedOptionValue("reporter-status"))); if (null == match) { throw new IllegalArgumentException(String.format("%s is not a valid report status.", cmd.getOptionValue("reporter-status"))); } } final ProgressBar progressBar = ConsoleProgressBar.on(System.err) .withFormat("[:bar] :percent% :elapsed/:total ETA: :eta") .withTotalSteps(report.size()); final ObjectMapper mapper = new ObjectMapper(); final SimpleModule module = new SimpleModule(); module.addSerializer(Report.class, new ReportSerializer(progressBar, match)); mapper.registerModule(module); try ( final JsonGenerator jsonGenerator = new JsonFactory() .setCodec(mapper) .createGenerator(System.out, JsonEncoding.UTF8) ) { jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(report); jsonGenerator.writeRaw('\n'); } catch (IOException e) { throw new RuntimeException("Unable to output JSON.", e); } try { report.close(); } catch (IOException e) { throw new RuntimeException("Exception while closing report.", e); } return cmd; } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public CommandLine parse(final String[] args) throws ParseException, IllegalArgumentException { final CommandLine cmd = super.parse(args); final String[] files = cmd.getArgs(); if (files.length > 1) { throw new IllegalArgumentException("Only one dump file path may be passed at a time."); } final Report report = ReportFactory.createReport(cmd, ReportType.REDIS); final OutputStream output; // Write to stdout if no path is specified. if (0 == files.length) { logger.info("No path given. Writing to standard output."); output = System.out; } else { try { output = new FileOutputStream(files[0]); } catch (FileNotFoundException e) { throw new RuntimeException("Unable to open dump file for writing.", e); } } ExtractionResult match = null; if (cmd.hasOption("reporter-status")) { match = ExtractionResult.get(((Number) cmd.getParsedOptionValue("reporter-status"))); if (null == match) { throw new IllegalArgumentException(String.format("%s is not a valid report status.", cmd.getOptionValue("reporter-status"))); } } final ProgressBar progressBar = ConsoleProgressBar.on(System.err) .withFormat("[:bar] :percent% :elapsed/:total ETA: :eta") .withTotalSteps(report.size()); final ObjectMapper mapper = new ObjectMapper(); final SimpleModule module = new SimpleModule(); module.addSerializer(Report.class, new ReportSerializer(progressBar, match)); mapper.registerModule(module); try ( final JsonGenerator jsonGenerator = new JsonFactory() .setCodec(mapper) .createGenerator(output, JsonEncoding.UTF8) ) { jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(report); jsonGenerator.writeRaw('\n'); } catch (IOException e) { throw new RuntimeException("Unable to output JSON.", e); } try { report.close(); } catch (IOException e) { throw new RuntimeException("Exception while closing report.", e); } return cmd; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public void run() { // restart the clock. lastResponseMs = clock.currentTimeMillis(); this.rowMerger = new RowMerger(rowObserver); synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter = new CallToStreamObserverAdapter<ReadRowsRequest>(call); adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public void run() { // restart the clock. this.rowMerger = new RowMerger(rowObserver); adapter = new CallToStreamObserverAdapter(); synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Test public void testMutation() throws IOException, InterruptedException { final ReentrantLock lock = new ReentrantLock(); final Condition mutateRowAsyncCalled = lock.newCondition(); when(mockClient.mutateRowAsync(any(MutateRowRequest.class))) .thenAnswer( new Answer<ListenableFuture<Empty>>() { @Override public ListenableFuture<Empty> answer(InvocationOnMock invocation) throws Throwable { lock.lock(); try { mutateRowAsyncCalled.signalAll(); return mockFuture; } finally { lock.unlock(); } } }); BigtableBufferedMutator underTest = createMutator(new Configuration(false)); underTest.mutate(SIMPLE_PUT); Assert.assertTrue(underTest.hasInflightRequests()); // Leave some time for the async worker to handle the request. lock.lock(); try { mutateRowAsyncCalled.await(100, TimeUnit.SECONDS); } finally { lock.unlock(); } verify(mockClient, times(1)).mutateRowAsync(any(MutateRowRequest.class)); Assert.assertTrue(underTest.hasInflightRequests()); completeCall(); Assert.assertFalse(underTest.hasInflightRequests()); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Test public void testMutation() throws IOException, InterruptedException { when(mockClient.mutateRowAsync(any(MutateRowRequest.class))) .thenReturn(mockFuture); BigtableBufferedMutator underTest = createMutator(new Configuration(false)); underTest.mutate(SIMPLE_PUT); Assert.assertTrue(underTest.hasInflightRequests()); // Leave some time for the async worker to handle the request. Thread.sleep(100); verify(mockClient, times(1)).mutateRowAsync(any(MutateRowRequest.class)); Assert.assertTrue(underTest.hasInflightRequests()); completeCall(); Assert.assertFalse(underTest.hasInflightRequests()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Credentials getCredentialFromPrivateKeyServiceAccount( String serviceAccountEmail, String privateKeyFile, List<String> scopes) throws IOException, GeneralSecurityException { PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore( SecurityUtils.getPkcs12KeyStore(), new FileInputStream(privateKeyFile), "notasecret", "privatekey", "notasecret"); // Since the user specified scopes, we can't use JWT tokens return ServiceAccountCredentials.newBuilder() .setClientEmail(serviceAccountEmail) .setPrivateKey(privateKey) .setScopes(scopes) .setHttpTransportFactory(getHttpTransportFactory()) .build(); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static Credentials getCredentialFromPrivateKeyServiceAccount( String serviceAccountEmail, String privateKeyFile, List<String> scopes) throws IOException, GeneralSecurityException { PrivateKey privateKey = SecurityUtils.loadPrivateKeyFromKeyStore( SecurityUtils.getPkcs12KeyStore(), new FileInputStream(privateKeyFile), "notasecret", "privatekey", "notasecret"); // Since the user specified scopes, we can't use JWT tokens return patchCredentials( ServiceAccountCredentials.newBuilder() .setClientEmail(serviceAccountEmail) .setPrivateKey(privateKey) .setScopes(scopes) .setHttpTransportFactory(getHttpTransportFactory()) .build()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRefresh() throws IOException { Mockito.when(credentials.refreshAccessToken()).thenReturn( new AccessToken("", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1))); underTest = new RefreshingOAuth2CredentialsInterceptor(MoreExecutors.newDirectExecutorService(), credentials); underTest.syncRefresh(); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); Assert.assertFalse(underTest.isRefreshing()); } #location 8 #vulnerability type UNSAFE_GUARDED_BY_ACCESS
#fixed code @Test public void testRefresh() throws IOException { Mockito.when(mockCredentials.refreshAccessToken()).thenReturn( new AccessToken("", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1))); underTest = new RefreshingOAuth2CredentialsInterceptor(MoreExecutors.newDirectExecutorService(), mockCredentials); underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, underTest.getCacheState()); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Future<Void> future = executorService.submit(syncRefreshCallable); // let the Thread running syncRefreshCallable() have a turn so that it can initiate the call // to refreshAccessToken(). Thread.yield(); synchronized(lock) { lock.notifyAll(); } // Try to get the access token, which should be calculated at this point. There's // a possibility that some hanging occurs in the test code. If the operation times out // so timeout after 1 second, this will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); future = executorService.submit(syncRefreshCallable); // Let the asyncRefreshes do their thing. Thread.yield(); // There should be a single thread kicked off by the underTest.asyncRefresh() calls about // actually doing a refresh at this point; the other ones will have see that a refresh is in // progress and finish the invocation of the Thread without performing a refres().. Make sure // that at least 1 refresh process is in progress. Assert.assertTrue(underTest.isRefreshing.get()); synchronized(lock) { // Release the lock so that all of the async refreshing can complete. lock.notifyAll(); } // Wait for no more than a second to make sure that the call to underTest.syncRefresh() // completes properly. If a second passes without syncRefresh() completing, future.get(..) // will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); Assert.assertFalse(underTest.isRefreshing.get()); } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Future<Void> future = executorService.submit(syncRefreshCallable); // let the Thread running syncRefreshCallable() have a turn so that it can initiate the call // to refreshAccessToken(). Thread.yield(); synchronized(lock) { lock.notifyAll(); } // Try to get the access token, which should be calculated at this point. There's // a possibility that some hanging occurs in the test code. If the operation times out // so timeout after 1 second, this will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); future = executorService.submit(syncRefreshCallable); // Let the asyncRefreshes do their thing. Thread.yield(); // There should be a single thread kicked off by the underTest.asyncRefresh() calls about // actually doing a refresh at this point; the other ones will have see that a refresh is in // progress and finish the invocation of the Thread without performing a refres().. Make sure // that at least 1 refresh process is in progress. Assert.assertTrue(underTest.isRefreshing.get()); synchronized(lock) { // Release the lock so that all of the async refreshing can complete. lock.notifyAll(); } // Wait for no more than a second to make sure that the call to underTest.syncRefresh() // completes properly. If a second passes without syncRefresh() completing, future.get(..) // will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); Assert.assertFalse(underTest.isRefreshing.get()); } #location 70 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{ ServerSocket serverSocket = new ServerSocket(0); final int availablePort = serverSocket.getLocalPort(); serverSocket.close(); //Creates non-ssl server. createServer(availablePort); BigtableOptions bigtableOptions = BigtableOptions.builder() .setDataHost("localhost") .setAdminHost("localhost") .setProjectId(TEST_PROJECT_ID) .setInstanceId(TEST_INSTANCE_ID) .setUserAgent(TEST_USER_AGENT) .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setPort(availablePort) .build(); xGoogApiPattern = Pattern.compile(".* cbt/.*"); try (BigtableSession session = new BigtableSession(bigtableOptions)) { session.getDataClient() .readFlatRows(ReadRowsRequest.getDefaultInstance()).next(); Assert.assertTrue(serverPasses.get()); } } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{ ServerSocket serverSocket = new ServerSocket(0); final int availablePort = serverSocket.getLocalPort(); serverSocket.close(); //Creates non-ssl server. createServer(availablePort); BigtableOptions bigtableOptions = BigtableOptions.builder() .setDataHost("localhost") .setAdminHost("localhost") .setProjectId(TEST_PROJECT_ID) .setInstanceId(TEST_INSTANCE_ID) .setUserAgent(TEST_USER_AGENT) .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setPort(availablePort) .build(); xGoogApiPattern = Pattern.compile(".* cbt/.*"); try (BigtableSession session = new BigtableSession(bigtableOptions)) { session.getClientWrapper() .readFlatRows(Query.create("fake-table")).next(); Assert.assertTrue(serverPasses.get()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Future<Void> future = executorService.submit(syncRefreshCallable); // let the Thread running syncRefreshCallable() have a turn so that it can initiate the call // to refreshAccessToken(). Thread.yield(); synchronized(lock) { lock.notifyAll(); } // Try to get the access token, which should be calculated at this point. There's // a possibility that some hanging occurs in the test code. If the operation times out // so timeout after 1 second, this will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); future = executorService.submit(syncRefreshCallable); // Let the asyncRefreshes do their thing. Thread.yield(); // There should be a single thread kicked off by the underTest.asyncRefresh() calls about // actually doing a refresh at this point; the other ones will have see that a refresh is in // progress and finish the invocation of the Thread without performing a refres().. Make sure // that at least 1 refresh process is in progress. Assert.assertTrue(underTest.isRefreshing.get()); synchronized(lock) { // Release the lock so that all of the async refreshing can complete. lock.notifyAll(); } // Wait for no more than a second to make sure that the call to underTest.syncRefresh() // completes properly. If a second passes without syncRefresh() completing, future.get(..) // will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); Assert.assertFalse(underTest.isRefreshing.get()); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRetyableCheckAndMutateRow() throws InterruptedException { final CheckAndMutateRowRequest request = CheckAndMutateRowRequest.getDefaultInstance(); final AtomicBoolean done = new AtomicBoolean(false); executor.submit(new Callable<Void>(){ @Override public Void call() throws Exception { underTest.checkAndMutateRow(request); done.set(true); synchronized (done) { done.notify(); } return null; } }); Thread.sleep(100); future.set(CheckAndMutateRowResponse.getDefaultInstance()); synchronized (done) { done.wait(1000); } assertTrue(done.get()); verify(clientCallService, times(1)).listenableAsyncCall(any(ClientCall.class), same(request)); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRetyableCheckAndMutateRow() throws Exception { final CheckAndMutateRowRequest request = CheckAndMutateRowRequest.getDefaultInstance(); when(mockFuture.get()).thenReturn(CheckAndMutateRowResponse.getDefaultInstance()); underTest.checkAndMutateRow(request); verify(clientCallService, times(1)).listenableAsyncCall(any(ClientCall.class), same(request)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRefreshAfterStale() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); final AccessToken staleToken = new AccessToken("stale", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); AccessToken goodToken = new AccessToken("good", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 11)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will setup a stale token .thenReturn(staleToken) // Second call will give a good token .thenReturn(goodToken); // First call - setup HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, firstResult.getCacheState()); Assert.assertThat(firstResult.header, containsString("stale")); // Fast forward until token is stale setTimeInMillieconds(10); // Second call - return stale token, but schedule refresh HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Stale, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("stale")); // Wait for the refresh to finish final Future<?> waiter; synchronized (underTest.lock) { waiter = underTest.isRefreshing ? underTest.futureToken : Futures.immediateFuture(null); } waiter.get(); // Third call - now returns good token HeaderCacheElement thirdResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, thirdResult.getCacheState()); Assert.assertThat(thirdResult.header, containsString("good")); // Make sure that the token was only requested twice: once for the stale token & second time for the good token Mockito.verify(credentials, times(2)).refreshAccessToken(); } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRefreshAfterStale() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); final AccessToken staleToken = new AccessToken("stale", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); AccessToken goodToken = new AccessToken("good", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 11)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will setup a stale token .thenReturn(staleToken) // Second call will give a good token .thenReturn(goodToken); // First call - setup HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, firstResult.getCacheState()); Assert.assertThat(firstResult.header, containsString("stale")); // Fast forward until token is stale setTimeInMillieconds(10); // Second call - return stale token, but schedule refresh HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Stale, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("stale")); // Wait for the refresh to finish underTest.syncRefresh(); // Third call - now returns good token HeaderCacheElement thirdResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, thirdResult.getCacheState()); Assert.assertThat(thirdResult.header, containsString("good")); // Make sure that the token was only requested twice: once for the stale token & second time for the good token Mockito.verify(credentials, times(2)).refreshAccessToken(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void run() { try (Scope scope = TRACER.withSpan(operationSpan)) { rpcTimerContext = rpc.getRpcMetrics().timeRpc(); operationSpan.addAnnotation(Annotation.fromDescriptionAndAttributes("rpcStart", ImmutableMap.of("attempt", AttributeValue.longAttributeValue(failedCount)))); Metadata metadata = new Metadata(); metadata.merge(originalMetadata); synchronized (callLock) { // There's a subtle race condition in RetryingStreamOperation which requires a separate // newCall/start split. The call variable needs to be set before onMessage() happens; that // usually will occur, but some unit tests broke with a merged newCall and start. call = rpc.newCall(getRpcCallOptions()); rpc.start(getRetryRequest(), this, metadata, call); } } catch (Exception e) { setException(e); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void run() { try (Scope scope = TRACER.withSpan(operationSpan)) { rpcTimerContext = rpc.getRpcMetrics().timeRpc(); operationSpan.addAnnotation(Annotation.fromDescriptionAndAttributes("rpcStart", ImmutableMap.of("attempt", AttributeValue.longAttributeValue(failedCount)))); Metadata metadata = new Metadata(); metadata.merge(originalMetadata); callWrapper.setCallAndStart(rpc, getRpcCallOptions(), getRetryRequest(), this, metadata); } catch (Exception e) { setException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRefreshAfterStale() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); final AccessToken staleToken = new AccessToken("stale", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); AccessToken goodToken = new AccessToken("good", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 11)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will setup a stale token .thenReturn(staleToken) // Second call will give a good token .thenReturn(goodToken); // First call - setup HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, firstResult.getCacheState()); Assert.assertThat(firstResult.header, containsString("stale")); // Fast forward until token is stale setTimeInMillieconds(10); // Second call - return stale token, but schedule refresh HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Stale, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("stale")); // Wait for the refresh to finish final Future<?> waiter; synchronized (underTest.lock) { waiter = underTest.isRefreshing ? underTest.futureToken : Futures.immediateFuture(null); } waiter.get(); // Third call - now returns good token HeaderCacheElement thirdResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, thirdResult.getCacheState()); Assert.assertThat(thirdResult.header, containsString("good")); // Make sure that the token was only requested twice: once for the stale token & second time for the good token Mockito.verify(credentials, times(2)).refreshAccessToken(); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRefreshAfterStale() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); final AccessToken staleToken = new AccessToken("stale", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); AccessToken goodToken = new AccessToken("good", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 11)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will setup a stale token .thenReturn(staleToken) // Second call will give a good token .thenReturn(goodToken); // First call - setup HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, firstResult.getCacheState()); Assert.assertThat(firstResult.header, containsString("stale")); // Fast forward until token is stale setTimeInMillieconds(10); // Second call - return stale token, but schedule refresh HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Stale, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("stale")); // Wait for the refresh to finish underTest.syncRefresh(); // Third call - now returns good token HeaderCacheElement thirdResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, thirdResult.getCacheState()); Assert.assertThat(thirdResult.header, containsString("good")); // Make sure that the token was only requested twice: once for the stale token & second time for the good token Mockito.verify(credentials, times(2)).refreshAccessToken(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPartialResults() throws Exception { byte[] key1 = randomBytes(8); byte[] key2 = randomBytes(8); FlatRow response1 = FlatRow.newBuilder() .withRowKey(ByteString.copyFrom(key1)) .addCell( new Cell( "cf", ByteString.EMPTY, 10, ByteString.copyFromUtf8("hi!"), new ArrayList<String>())) .build(); RuntimeException exception = new RuntimeException("Something bad happened"); when(mockBulkRead.add(any(Query.class))) .thenReturn(ApiFutures.immediateFuture(response1)) .thenReturn(ApiFutures.<FlatRow>immediateFailedFuture(exception)); List<Get> gets = Arrays.asList(new Get(key1), new Get(key2)); Object[] results = new Object[2]; try { createExecutor(options).batch(gets, results); } catch (RetriesExhaustedWithDetailsException ignored) { } Assert.assertTrue("first result is a result", results[0] instanceof Result); Assert.assertTrue(Bytes.equals(((Result) results[0]).getRow(), key1)); Assert.assertEquals(exception, results[1]); } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPartialResults() throws Exception { byte[] key1 = randomBytes(8); byte[] key2 = randomBytes(8); FlatRow response1 = FlatRow.newBuilder() .withRowKey(ByteString.copyFrom(key1)) .addCell( new Cell( "cf", ByteString.EMPTY, 10, ByteString.copyFromUtf8("hi!"), new ArrayList<String>())) .build(); RuntimeException exception = new RuntimeException("Something bad happened"); when(mockBulkRead.add(any(Query.class))) .thenReturn(ApiFutures.immediateFuture(response1)) .thenReturn(ApiFutures.<FlatRow>immediateFailedFuture(exception)); List<Get> gets = Arrays.asList(new Get(key1), new Get(key2)); Object[] results = new Object[2]; try { createExecutor().batch(gets, results); } catch (RetriesExhaustedWithDetailsException ignored) { } Assert.assertTrue("first result is a result", results[0] instanceof Result); Assert.assertTrue(Bytes.equals(((Result) results[0]).getRow(), key1)); Assert.assertEquals(exception, results[1]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncRefresh() throws IOException { initialize(HeaderCacheElement.TOKEN_STALENESS_MS + 1); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); Assert.assertFalse(underTest.isRefreshing()); } #location 4 #vulnerability type UNSAFE_GUARDED_BY_ACCESS
#fixed code @Test public void testSyncRefresh() throws IOException { Mockito.when(mockCredentials.refreshAccessToken()).thenReturn( new AccessToken("", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1))); underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, mockCredentials); Assert.assertEquals(CacheState.Expired, underTest.getCacheState()); underTest.getHeaderSafe(); Assert.assertNotEquals(CacheState.Exception, underTest.getCacheState()); Assert.assertEquals(CacheState.Good, underTest.getCacheState()); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /* * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTimeInMillieconds(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new Object(); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); // Check to make sure we're no longer refreshing. synchronized (underTest.lock) { Assert.assertFalse(underTest.isRefreshing); } // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing); } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test /* * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTimeInMillieconds(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new Object(); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void flush() throws IOException { // If there is a bulk mutation in progress, then send it. if (bulkMutation != null) { try { bulkMutation.flush(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("flush() was interrupted", e); } } asyncExecutor.flush(); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void flush() throws IOException { // If there is a bulk mutation in progress, then send it. if (bulkMutation != null) { try { bulkMutation.flush(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("flush() was interrupted", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); Future<Void> future = executorService.submit(syncRefreshCallable); // let the Thread running syncRefreshCallable() have a turn so that it can initiate the call // to refreshAccessToken(). Thread.yield(); synchronized(lock) { lock.notifyAll(); } // Try to get the access token, which should be calculated at this point. There's // a possibility that some hanging occurs in the test code. If the operation times out // so timeout after 1 second, this will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); future = executorService.submit(syncRefreshCallable); // Let the asyncRefreshes do their thing. Thread.yield(); // There should be a single thread kicked off by the underTest.asyncRefresh() calls about // actually doing a refresh at this point; the other ones will have see that a refresh is in // progress and finish the invocation of the Thread without performing a refres().. Make sure // that at least 1 refresh process is in progress. Assert.assertTrue(underTest.isRefreshing.get()); synchronized(lock) { // Release the lock so that all of the async refreshing can complete. lock.notifyAll(); } // Wait for no more than a second to make sure that the call to underTest.syncRefresh() // completes properly. If a second passes without syncRefresh() completing, future.get(..) // will throw a TimeoutException. future.get(1, TimeUnit.SECONDS); Assert.assertFalse(underTest.isRefreshing.get()); } #location 79 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test /** * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception, TimeoutException { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTime(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new String(""); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, RefreshingOAuth2CredentialsInterceptor.getCacheState(underTest.headerCache.get())); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing.get()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testStaleAndExpired() throws IOException { long expiration = HeaderCacheElement.TOKEN_STALENESS_MS + 1; initialize(expiration); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); long startTime = 2L; setTimeInMillieconds(startTime); Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); long expiredStaleDiff = HeaderCacheElement.TOKEN_STALENESS_MS - HeaderCacheElement.TOKEN_EXPIRES_MS; setTimeInMillieconds(startTime + expiredStaleDiff); Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); } #location 5 #vulnerability type UNSAFE_GUARDED_BY_ACCESS
#fixed code @Test public void testStaleAndExpired() throws IOException { long expiration = HeaderCacheElement.TOKEN_STALENESS_MS + 1; initialize(expiration); Assert.assertEquals(CacheState.Good, underTest.getCacheState()); long startTime = 2L; setTimeInMillieconds(startTime); Assert.assertEquals(CacheState.Stale, underTest.getCacheState()); long expiredStaleDiff = HeaderCacheElement.TOKEN_STALENESS_MS - HeaderCacheElement.TOKEN_EXPIRES_MS; setTimeInMillieconds(startTime + expiredStaleDiff); Assert.assertEquals(CacheState.Expired, underTest.getCacheState()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testOptionsAreConstructedWithValidInput() throws IOException { configuration.set(BigtableOptionsFactory.BIGTABLE_HOST_KEY, TEST_HOST); configuration.setBoolean(BigtableOptionsFactory.BIGTABLE_USE_SERVICE_ACCOUNTS_KEY, false); configuration.setBoolean(BigtableOptionsFactory.BIGTABLE_NULL_CREDENTIAL_ENABLE_KEY, true); configuration.setLong(BIGTABLE_BUFFERED_MUTATOR_MAX_MEMORY_KEY, 100_000L); BigtableOptions options = ((BigtableHBaseClassicSettings) BigtableHBaseSettings.create(configuration)) .getBigtableOptions(); assertEquals(TEST_HOST, options.getDataHost()); assertEquals(TEST_PROJECT_ID, options.getProjectId()); assertEquals(TEST_INSTANCE_ID, options.getInstanceId()); assertEquals(100_000L, options.getBulkOptions().getMaxMemory()); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testOptionsAreConstructedWithValidInput() throws IOException { configuration.set(BigtableOptionsFactory.BIGTABLE_HOST_KEY, TEST_HOST); configuration.setBoolean(BigtableOptionsFactory.BIGTABLE_USE_SERVICE_ACCOUNTS_KEY, false); configuration.setBoolean(BigtableOptionsFactory.BIGTABLE_NULL_CREDENTIAL_ENABLE_KEY, true); configuration.setBoolean(BigtableOptionsFactory.ALLOW_NO_TIMESTAMP_RETRIES_KEY, true); configuration.setLong(BIGTABLE_BUFFERED_MUTATOR_MAX_MEMORY_KEY, 100_000L); BigtableHBaseSettings settings = BigtableHBaseSettings.create(configuration); assertTrue(settings.isRetriesWithoutTimestampAllowed()); BigtableOptions options = ((BigtableHBaseClassicSettings) settings).getBigtableOptions(); assertEquals(TEST_HOST, options.getDataHost()); assertEquals(TEST_PROJECT_ID, options.getProjectId()); assertEquals(TEST_INSTANCE_ID, options.getInstanceId()); assertEquals(100_000L, options.getBulkOptions().getMaxMemory()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRetyableCheckAndMutateRow() throws InterruptedException { final CheckAndMutateRowRequest request = CheckAndMutateRowRequest.getDefaultInstance(); final AtomicBoolean done = new AtomicBoolean(false); executor.submit(new Callable<Void>(){ @Override public Void call() throws Exception { underTest.checkAndMutateRow(request); done.set(true); synchronized (done) { done.notify(); } return null; } }); Thread.sleep(100); future.set(CheckAndMutateRowResponse.getDefaultInstance()); synchronized (done) { done.wait(1000); } assertTrue(done.get()); verify(clientCallService, times(1)).listenableAsyncCall(any(ClientCall.class), same(request)); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRetyableCheckAndMutateRow() throws Exception { final CheckAndMutateRowRequest request = CheckAndMutateRowRequest.getDefaultInstance(); when(mockFuture.get()).thenReturn(CheckAndMutateRowResponse.getDefaultInstance()); underTest.checkAndMutateRow(request); verify(clientCallService, times(1)).listenableAsyncCall(any(ClientCall.class), same(request)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onClose(Status status, Metadata trailers) { if (status.getCode() == Status.Code.CANCELLED && status.getDescription().contains(TIMEOUT_CANCEL_MSG)) { // If this was canceled because of handleTimeout(). The cancel is immediately retried or // completed in another fashion. return; } super.onClose(status, trailers); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onClose(Status status, Metadata trailers) { if (status.getCode() == Status.Code.CANCELLED && status.getDescription() != null && status.getDescription().contains(TIMEOUT_CANCEL_MSG)) { // If this was canceled because of handleTimeout(). The cancel is immediately retried or // completed in another fashion. return; } super.onClose(status, trailers); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /* * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTimeInMillieconds(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new Object(); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); // Check to make sure we're no longer refreshing. synchronized (underTest.lock) { Assert.assertFalse(underTest.isRefreshing); } // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test /* * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTimeInMillieconds(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new Object(); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMutateRowPredicate() { Predicate<MutateRowRequest> predicate = BigtableDataGrpcClient.IS_RETRYABLE_MUTATION; assertFalse(predicate.apply(null)); MutateRowRequest.Builder request = MutateRowRequest.newBuilder(); assertTrue(predicate.apply(request.build())); request.addMutations( Mutation.newBuilder().setSetCell(SetCell.newBuilder().setTimestampMicros(-1))); assertFalse(predicate.apply(request.build())); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testMutateRowPredicate() { Predicate<MutateRowRequest> defaultPredicate = BigtableDataGrpcClient.IS_RETRYABLE_MUTATION; createClient(true); Predicate<MutateRowRequest> allowNoTimestampsPredicate = predicates.get(BigtableServiceGrpc.METHOD_MUTATE_ROW.getFullMethodName()); assertFalse(defaultPredicate.apply(null)); assertTrue(allowNoTimestampsPredicate.apply(null)); MutateRowRequest noDataRequest = MutateRowRequest.getDefaultInstance(); assertTrue(defaultPredicate.apply(noDataRequest)); assertTrue(allowNoTimestampsPredicate.apply(noDataRequest)); MutateRowRequest requestWithCells = MutateRowRequest.newBuilder() .addMutations(Mutation.newBuilder().setSetCell(SetCell.newBuilder().setTimestampMicros(-1))) .build(); assertFalse(defaultPredicate.apply(requestWithCells)); assertTrue(allowNoTimestampsPredicate.apply(requestWithCells)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test /* * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTimeInMillieconds(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new Object(); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); // Check to make sure we're no longer refreshing. synchronized (underTest.lock) { Assert.assertFalse(underTest.isRefreshing); } // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing); } #location 58 #vulnerability type UNSAFE_GUARDED_BY_ACCESS
#fixed code @Test /* * Test that checks that concurrent requests to RefreshingOAuth2CredentialsInterceptor refresh * logic doesn't cause hanging behavior. Specifically, when an Expired condition occurs it * triggers a call to syncRefresh() which potentially waits for refresh that was initiated * from another thread either through syncRefresh() or asyncRefresh(). This test case simulates * that condition. */ public void testRefreshDoesntHang() throws Exception { // Assume that the user starts at this time... it's an arbitrarily big number which will // assure that subtracting HeaderCacheElement.TOKEN_STALENESS_MS and TOKEN_EXPIRES_MS will not // be negative. long start = HeaderCacheElement.TOKEN_STALENESS_MS * 10; setTimeInMillieconds(start); // RefreshingOAuth2CredentialsInterceptor will show that the access token is stale. final long expiration = start + HeaderCacheElement.TOKEN_EXPIRES_MS + 1; // Create a mechanism that will allow us to control when the accessToken is returned. // credentials.refreshAccessToken() will get called asynchronously and will wait until the // lock is notified before returning. That will allow us to set up multiple concurrent calls final Object lock = new Object(); Mockito.when(credentials.refreshAccessToken()).thenAnswer(new Answer<AccessToken>() { @Override public AccessToken answer(InvocationOnMock invocation) throws Throwable { synchronized (lock) { lock.wait(); } return new AccessToken("", new Date(expiration)); } }); // Force a synchronous refresh. This ought to wait until a refresh happening in another thread // completes. Callable<Void> syncRefreshCallable = new Callable<Void>() { @Override public Void call() throws Exception { underTest.syncRefresh(); return null; } }; underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); // At this point, the access token wasn't retrieved yet. The // RefreshingOAuth2CredentialsInterceptor considers null to be Expired. Assert.assertEquals(CacheState.Expired, underTest.headerCache.getCacheState()); syncCall(lock, syncRefreshCallable); // Check to make sure that the AccessToken was retrieved. Assert.assertEquals(CacheState.Stale, underTest.headerCache.getCacheState()); // Check to make sure we're no longer refreshing. Assert.assertFalse(underTest.isRefreshing()); // Kick off a couple of asynchronous refreshes. Kicking off more than one shouldn't be // necessary, but also should not be harmful, since there are likely to be multiple concurrent // requests that call asyncRefresh() when the token turns stale. underTest.asyncRefresh(); underTest.asyncRefresh(); underTest.asyncRefresh(); syncCall(lock, syncRefreshCallable); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncRefresh() throws IOException { initialize(HeaderCacheElement.TOKEN_STALENESS_MS + 1); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testSyncRefresh() throws IOException { initialize(HeaderCacheElement.TOKEN_STALENESS_MS + 1); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncRefresh() throws IOException { initialize(HeaderCacheElement.TOKEN_STALENESS_MS + 1); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testSyncRefresh() throws IOException { initialize(HeaderCacheElement.TOKEN_STALENESS_MS + 1); Assert.assertEquals(CacheState.Good, underTest.headerCache.getCacheState()); Assert.assertFalse(underTest.isRefreshing()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBatchBulkGets() throws Exception { final List<Get> gets = new ArrayList<>(10); final List<ApiFuture<FlatRow>> expected = new ArrayList<>(10); gets.add(new Get(Bytes.toBytes("key0"))); expected.add(ApiFutures.<FlatRow>immediateFuture(null)); for (int i = 1; i < 10; i++) { byte[] row_key = randomBytes(8); gets.add(new Get(row_key)); ByteString key = ByteStringer.wrap(row_key); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); expected.add( ApiFutures.immediateFuture( FlatRow.newBuilder() .withRowKey(key) .addCell("family", ByteString.EMPTY, System.nanoTime() / 1000, cellValue) .build())); } // Test 10 gets, but return only 9 to test the row not found case. when(mockBulkRead.add(any(Query.class))) .then( new Answer<ApiFuture<FlatRow>>() { final AtomicInteger counter = new AtomicInteger(); @Override public ApiFuture<FlatRow> answer(InvocationOnMock invocation) throws Throwable { return expected.get(counter.getAndIncrement()); } }); ByteString key = ByteStringer.wrap(randomBytes(8)); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); FlatRow row = FlatRow.newBuilder() .withRowKey(key) .addCell("family", ByteString.EMPTY, System.nanoTime() / 1000, cellValue) .build(); when(mockFuture.get()).thenReturn(row); BatchExecutor underTest = createExecutor(options); Result[] results = underTest.batch(gets); verify(mockBulkRead, times(10)).add(any(Query.class)); verify(mockBulkRead, times(1)).flush(); Assert.assertTrue(matchesRow(Result.EMPTY_RESULT).matches(results[0])); for (int i = 1; i < results.length; i++) { Assert.assertTrue( "Expected " + Bytes.toString(gets.get(i).getRow()) + " but was " + Bytes.toString(results[i].getRow()), Bytes.equals(results[i].getRow(), gets.get(i).getRow())); } } #location 42 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBatchBulkGets() throws Exception { final List<Get> gets = new ArrayList<>(10); final List<ApiFuture<FlatRow>> expected = new ArrayList<>(10); gets.add(new Get(Bytes.toBytes("key0"))); expected.add(ApiFutures.<FlatRow>immediateFuture(null)); for (int i = 1; i < 10; i++) { byte[] row_key = randomBytes(8); gets.add(new Get(row_key)); ByteString key = ByteStringer.wrap(row_key); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); expected.add( ApiFutures.immediateFuture( FlatRow.newBuilder() .withRowKey(key) .addCell("family", ByteString.EMPTY, System.nanoTime() / 1000, cellValue) .build())); } // Test 10 gets, but return only 9 to test the row not found case. when(mockBulkRead.add(any(Query.class))) .then( new Answer<ApiFuture<FlatRow>>() { final AtomicInteger counter = new AtomicInteger(); @Override public ApiFuture<FlatRow> answer(InvocationOnMock invocation) throws Throwable { return expected.get(counter.getAndIncrement()); } }); ByteString key = ByteStringer.wrap(randomBytes(8)); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); FlatRow row = FlatRow.newBuilder() .withRowKey(key) .addCell("family", ByteString.EMPTY, System.nanoTime() / 1000, cellValue) .build(); when(mockFuture.get()).thenReturn(row); Result[] results = createExecutor().batch(gets); verify(mockBulkRead, times(10)).add(any(Query.class)); verify(mockBulkRead, times(1)).flush(); Assert.assertTrue(matchesRow(Result.EMPTY_RESULT).matches(results[0])); for (int i = 1; i < results.length; i++) { Assert.assertTrue( "Expected " + Bytes.toString(gets.get(i).getRow()) + " but was " + Bytes.toString(results[i].getRow()), Bytes.equals(results[i].getRow(), gets.get(i).getRow())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void setMessageCompression(boolean enable) { call.setMessageCompression(enable); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void setMessageCompression(boolean enable) { throw new UnsupportedOperationException("setMessageCompression()"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void modifyTable(TableName tableName, TableDescriptor tableDescriptor) throws IOException { if (isTableAvailable(tableName)) { TableDescriptor currentTableDescriptor = getTableDescriptor(tableName); List<Modification> modifications = new ArrayList<>(); List<HColumnDescriptor> columnDescriptors = tableAdapter2x.toHColumnDescriptors(tableDescriptor); List<HColumnDescriptor> currentColumnDescriptors = tableAdapter2x.toHColumnDescriptors(currentTableDescriptor); modifications.addAll(tableModificationAdapter.buildModifications(columnDescriptors, currentColumnDescriptors)); modifyColumn(tableName, "modifyTable", "update", (Modification[]) modifications.toArray()); } else { throw new TableNotFoundException(tableName); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void modifyTable(TableName tableName, TableDescriptor tableDescriptor) throws IOException { super.modifyTable(tableName, new HTableDescriptor(tableDescriptor)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onClose(Status status, Metadata trailers) { synchronized (callLock) { call = null; } rpcTimerContext.close(); Status.Code code = status.getCode(); // OK if (code == Status.Code.OK) { if (onOK()) { operationTimerContext.close(); } return; } // CANCELLED if (code == Status.Code.CANCELLED) { // An explicit user cancellation is not considered a failure. operationTimerContext.close(); return; } // Non retry scenario if (!retryOptions.enableRetries() || !retryOptions.isRetryable(code) // Unauthenticated is special because the request never made it to // to the server, so all requests are retryable || !(isRequestRetryable() || code == Code.UNAUTHENTICATED)) { rpc.getRpcMetrics().markFailure(); operationTimerContext.close(); setException(status.asRuntimeException()); return; } // Attempt retry with backoff long nextBackOff = getNextBackoff(); failedCount += 1; // Backoffs timed out. if (nextBackOff == BackOff.STOP) { rpc.getRpcMetrics().markRetriesExhasted(); operationTimerContext.close(); String message = String.format("Exhausted retries after %d failures.", failedCount); StatusRuntimeException cause = status.asRuntimeException(); setException(new BigtableRetriesExhaustedException(message, cause)); return; } else { String channelId = ChannelPool.extractIdentifier(trailers); LOG.info("Retrying failed call. Failure #%d, got: %s on channel %s", status.getCause(), failedCount, status, channelId); } performRetry(nextBackOff); } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void onClose(Status status, Metadata trailers) { synchronized (callLock) { call = null; } rpcTimerContext.close(); // OK if (status.isOk()) { if (onOK(trailers)) { operationTimerContext.close(); } } else { onError(status, trailers); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testChannelsAreRoundRobinned() throws IOException { MockChannelFactory factory = new MockChannelFactory(); MethodDescriptor descriptor = mock(MethodDescriptor.class); MockitoAnnotations.initMocks(this); ChannelPool pool = new ChannelPool(null, factory); pool.ensureChannelCount(2); pool.newCall(descriptor, CallOptions.DEFAULT); verify(factory.channels.get(0), times(1)).newCall(same(descriptor), same(CallOptions.DEFAULT)); verify(factory.channels.get(1), times(0)).newCall(same(descriptor), same(CallOptions.DEFAULT)); pool.newCall(descriptor, CallOptions.DEFAULT); verify(factory.channels.get(0), times(1)).newCall(same(descriptor), same(CallOptions.DEFAULT)); verify(factory.channels.get(1), times(1)).newCall(same(descriptor), same(CallOptions.DEFAULT)); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testChannelsAreRoundRobinned() throws IOException { MockChannelFactory factory = new MockChannelFactory(); MethodDescriptor descriptor = mock(MethodDescriptor.class); MockitoAnnotations.initMocks(this); ChannelPool pool = new ChannelPool(null, factory); pool.ensureChannelCount(2); pool.newCall(descriptor, CallOptions.DEFAULT); verify(factory.channels.get(0), times(1)).newCall(same(descriptor), same(CallOptions.DEFAULT)); verify(factory.channels.get(1), times(0)).newCall(same(descriptor), same(CallOptions.DEFAULT)); pool.newCall(descriptor, CallOptions.DEFAULT); verify(factory.channels.get(0), times(1)).newCall(same(descriptor), same(CallOptions.DEFAULT)); verify(factory.channels.get(1), times(1)).newCall(same(descriptor), same(CallOptions.DEFAULT)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRefreshAfterFailure() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); final AccessToken accessToken = new AccessToken("hi", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will throw Exception & bypass retries .thenThrow(new IOException()) // Second call will succeed .thenReturn(accessToken); // First call HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Exception, firstResult.getCacheState()); // Now the second token should be available HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("hi")); // Make sure that the token was only requested twice: once for the first failure & second time for background recovery Mockito.verify(credentials, times(2)).refreshAccessToken(); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRefreshAfterFailure() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); final AccessToken accessToken = new AccessToken("hi", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will throw Exception & bypass retries .thenThrow(new IOException()) // Second call will succeed .thenReturn(accessToken); // First call HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Exception, firstResult.getCacheState()); // Now the second token should be available HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("hi")); // Make sure that the token was only requested twice: once for the first failure & second time for background recovery Mockito.verify(credentials, times(2)).refreshAccessToken(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{ ServerSocket serverSocket = new ServerSocket(0); final int availablePort = serverSocket.getLocalPort(); serverSocket.close(); //Creates non-ssl server. createServer(availablePort); BigtableOptions bigtableOptions = BigtableOptions.builder() .setDataHost("localhost") .setAdminHost("localhost") .setProjectId(TEST_PROJECT_ID) .setInstanceId(TEST_INSTANCE_ID) .setUserAgent(TEST_USER_AGENT) .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setPort(availablePort) .build(); xGoogApiPattern = Pattern.compile(".* cbt/.*"); new BigtableSession(bigtableOptions).getDataClient() .readFlatRows(ReadRowsRequest.getDefaultInstance()).next(); Assert.assertTrue(serverPasses.get()); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{ ServerSocket serverSocket = new ServerSocket(0); final int availablePort = serverSocket.getLocalPort(); serverSocket.close(); //Creates non-ssl server. createServer(availablePort); BigtableOptions bigtableOptions = BigtableOptions.builder() .setDataHost("localhost") .setAdminHost("localhost") .setProjectId(TEST_PROJECT_ID) .setInstanceId(TEST_INSTANCE_ID) .setUserAgent(TEST_USER_AGENT) .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setPort(availablePort) .build(); xGoogApiPattern = Pattern.compile(".* cbt/.*"); try (BigtableSession session = new BigtableSession(bigtableOptions)) { session.getDataClient() .readFlatRows(ReadRowsRequest.getDefaultInstance()).next(); Assert.assertTrue(serverPasses.get()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public void run() { try { // restart the clock. this.rowMerger = new RowMerger(rowObserver); adapter = new CallToStreamObserverAdapter(); synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } } catch (Exception e) { setException(e); } } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public void run() { try { // restart the clock. synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } } catch (Exception e) { setException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void retryOnTimeout(ScanTimeoutException rte) throws BigtableRetriesExhaustedException { LOG.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); // Cancel the existing rpc. cancel(TIMEOUT_CANCEL_MSG); rpcTimerContext.close(); failedCount++; // Can this request be retried int maxRetries = retryOptions.getMaxScanTimeoutRetries(); if (retryOptions.enableRetries() && ++timeoutRetryCount <= maxRetries) { rpc.getRpcMetrics().markRetry(); resetStatusBasedBackoff(); run(); } else { throw getExhaustedRetriesException(Status.ABORTED); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private void retryOnTimeout(ScanTimeoutException rte) throws BigtableRetriesExhaustedException { LOG.info("The client could not get a response in %d ms. Retrying the scan.", retryOptions.getReadPartialRowTimeoutMillis()); // Cancel the existing rpc. cancel(TIMEOUT_CANCEL_MSG); rpcTimerContext.close(); failedCount++; // Can this request be retried int maxRetries = retryOptions.getMaxScanTimeoutRetries(); if (retryOptions.enableRetries() && ++timeoutRetryCount <= maxRetries) { resetStatusBasedBackoff(); performRetry(0); } else { throw getExhaustedRetriesException(Status.ABORTED); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onClose(Status status, Metadata trailers) { try (Scope scope = TRACER.withSpan(operationSpan)) { synchronized (callLock) { call = NULL_CALL; } rpcTimerContext.close(); // OK if (status.isOk()) { if (onOK(trailers)) { finalizeStats(status); } } else { onError(status, trailers); } } catch (Exception e) { setException(e); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void onClose(Status status, Metadata trailers) { try (Scope scope = TRACER.withSpan(operationSpan)) { callWrapper.resetCall(); rpcTimerContext.close(); // OK if (status.isOk()) { if (onOK(trailers)) { finalizeStats(status); } } else { onError(status, trailers); } } catch (Exception e) { setException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Credentials getCredentials(CredentialOptions options) throws IOException, GeneralSecurityException { switch (options.getCredentialType()) { case DefaultCredentials: return getApplicationDefaultCredential(); case P12: P12CredentialOptions p12Options = (P12CredentialOptions) options; return getCredentialFromPrivateKeyServiceAccount( p12Options.getServiceAccount(), p12Options.getKeyFile()); case SuppliedCredentials: return ((UserSuppliedCredentialOptions) options).getCredential(); case SuppliedJson: JsonCredentialsOptions jsonCredentialsOptions = (JsonCredentialsOptions) options; synchronized (jsonCredentialsOptions) { if (jsonCredentialsOptions.getCachedCredentials() == null) { jsonCredentialsOptions.setCachedCredentails( getInputStreamCredential(jsonCredentialsOptions.getInputStream())); } return jsonCredentialsOptions.getCachedCredentials(); } case None: return null; default: throw new IllegalStateException( "Cannot process Credential type: " + options.getCredentialType()); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static Credentials getCredentials(CredentialOptions options) throws IOException, GeneralSecurityException { return patchCredentials(getCredentialsInner(options)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void awaitCompletion() throws InterruptedException { boolean performedWarning = false; lock.lock(); try { while (!isFlushed()) { flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS); long now = clock.nanoTime(); if (now >= noSuccessWarningDeadline) { logNoSuccessWarning(now); resetNoSuccessWarningDeadline(); performedWarning = true; } } if (performedWarning) { LOG.info("awaitCompletion() completed"); } } finally { lock.unlock(); } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void awaitCompletion() throws InterruptedException { boolean performedWarning = false; lock.lock(); try { while (!isFlushed()) { flushedCondition.await(finishWaitMillis, TimeUnit.MILLISECONDS); long now = clock.nanoTime(); if (now >= noSuccessWarningDeadlineNanos) { logNoSuccessWarning(now); resetNoSuccessWarningDeadline(); performedWarning = true; } } if (performedWarning) { LOG.info("awaitCompletion() completed"); } } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRefreshAfterStale() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); underTest.rateLimiter.setRate(100000); final AccessToken staleToken = new AccessToken("stale", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); AccessToken goodToken = new AccessToken("good", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 11)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will setup a stale token .thenReturn(staleToken) // Second call will give a good token .thenReturn(goodToken); // First call - setup HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, firstResult.getCacheState()); Assert.assertThat(firstResult.header, containsString("stale")); // Fast forward until token is stale setTimeInMillieconds(10); // Second call - return stale token, but schedule refresh HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Stale, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("stale")); // Wait for the refresh to finish final Future<?> waiter; synchronized (underTest.lock) { waiter = underTest.isRefreshing ? underTest.futureToken : Futures.immediateFuture(null); } waiter.get(); // Third call - now returns good token HeaderCacheElement thirdResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, thirdResult.getCacheState()); Assert.assertThat(thirdResult.header, containsString("good")); // Make sure that the token was only requested twice: once for the stale token & second time for the good token Mockito.verify(credentials, times(2)).refreshAccessToken(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testRefreshAfterStale() throws Exception { underTest = new RefreshingOAuth2CredentialsInterceptor(executorService, credentials); final AccessToken staleToken = new AccessToken("stale", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 1)); AccessToken goodToken = new AccessToken("good", new Date(HeaderCacheElement.TOKEN_STALENESS_MS + 11)); //noinspection unchecked Mockito.when(credentials.refreshAccessToken()) // First call will setup a stale token .thenReturn(staleToken) // Second call will give a good token .thenReturn(goodToken); // First call - setup HeaderCacheElement firstResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, firstResult.getCacheState()); Assert.assertThat(firstResult.header, containsString("stale")); // Fast forward until token is stale setTimeInMillieconds(10); // Second call - return stale token, but schedule refresh HeaderCacheElement secondResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Stale, secondResult.getCacheState()); Assert.assertThat(secondResult.header, containsString("stale")); // Wait for the refresh to finish underTest.syncRefresh(); // Third call - now returns good token HeaderCacheElement thirdResult = underTest.getHeaderSafe(); Assert.assertEquals(CacheState.Good, thirdResult.getCacheState()); Assert.assertThat(thirdResult.header, containsString("good")); // Make sure that the token was only requested twice: once for the stale token & second time for the good token Mockito.verify(credentials, times(2)).refreshAccessToken(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public void run() { try { // restart the clock. this.rowMerger = new RowMerger(rowObserver); adapter = new CallToStreamObserverAdapter(); synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } } catch (Exception e) { setException(e); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public void run() { try { // restart the clock. synchronized (callLock) { super.run(); // pre-fetch one more result, for performance reasons. adapter.request(1); if (rowObserver instanceof ClientResponseObserver) { ((ClientResponseObserver<ReadRowsRequest, FlatRow>) rowObserver).beforeStart(adapter); } lastResponseMs = clock.currentTimeMillis(); } } catch (Exception e) { setException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBatchBulkGets() throws Exception { final List<Get> gets = new ArrayList<>(10); final List<ApiFuture<FlatRow>> expected = new ArrayList<>(10); gets.add(new Get(Bytes.toBytes("key0"))); expected.add(ApiFutures.<FlatRow>immediateFuture(null)); for (int i = 1; i < 10; i++) { byte[] row_key = randomBytes(8); gets.add(new Get(row_key)); ByteString key = ByteStringer.wrap(row_key); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); expected.add( ApiFutures.immediateFuture( FlatRow.newBuilder() .withRowKey(key) .addCell("family", ByteString.EMPTY, System.nanoTime() / 1000, cellValue) .build())); } // Test 10 gets, but return only 9 to test the row not found case. when(mockBulkRead.add(any(Query.class))) .then( new Answer<ApiFuture<FlatRow>>() { final AtomicInteger counter = new AtomicInteger(); @Override public ApiFuture<FlatRow> answer(InvocationOnMock invocation) throws Throwable { return expected.get(counter.getAndIncrement()); } }); ByteString key = ByteStringer.wrap(randomBytes(8)); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); FlatRow row = FlatRow.newBuilder() .withRowKey(key) .addCell("family", ByteString.EMPTY, System.nanoTime() / 1000, cellValue) .build(); when(mockFuture.get()).thenReturn(row); Result[] results = createExecutor().batch(gets); verify(mockBulkRead, times(10)).add(any(Query.class)); verify(mockBulkRead, times(1)).flush(); Assert.assertTrue(matchesRow(Result.EMPTY_RESULT).matches(results[0])); for (int i = 1; i < results.length; i++) { Assert.assertTrue( "Expected " + Bytes.toString(gets.get(i).getRow()) + " but was " + Bytes.toString(results[i].getRow()), Bytes.equals(results[i].getRow(), gets.get(i).getRow())); } } #location 41 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBatchBulkGets() throws Exception { final List<Get> gets = new ArrayList<>(10); final List<ApiFuture<Result>> expected = new ArrayList<>(10); gets.add(new Get(Bytes.toBytes("key0"))); expected.add(ApiFutures.<Result>immediateFuture(null)); for (int i = 1; i < 10; i++) { byte[] row_key = randomBytes(8); gets.add(new Get(row_key)); ByteString key = ByteStringer.wrap(row_key); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); expected.add( ApiFutures.immediateFuture( Result.create( ImmutableList.<Cell>of( new RowCell( key.toByteArray(), Bytes.toBytes("family"), Bytes.toBytes(""), System.nanoTime() / 1000, cellValue.toByteArray()))))); } // Test 10 gets, but return only 9 to test the row not found case. when(mockBulkRead.add(any(Query.class))) .then( new Answer<ApiFuture<Result>>() { final AtomicInteger counter = new AtomicInteger(); @Override public ApiFuture<Result> answer(InvocationOnMock invocation) throws Throwable { return expected.get(counter.getAndIncrement()); } }); ByteString key = ByteStringer.wrap(randomBytes(8)); ByteString cellValue = ByteString.copyFrom(randomBytes(8)); Result row = Result.create( ImmutableList.<Cell>of( new RowCell( key.toByteArray(), Bytes.toBytes("family"), Bytes.toBytes(""), 1000L, cellValue.toByteArray()))); when(mockFuture.get()).thenReturn(row); Result[] results = createExecutor().batch(gets); verify(mockBulkRead, times(10)).add(any(Query.class)); verify(mockBulkRead, times(1)).flush(); assertTrue(matchesRow(Result.EMPTY_RESULT).matches(results[0])); for (int i = 1; i < results.length; i++) { assertTrue( "Expected " + Bytes.toString(gets.get(i).getRow()) + " but was " + Bytes.toString(results[i].getRow()), Bytes.equals(results[i].getRow(), gets.get(i).getRow())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPartialResults() throws Exception { when(mockBigtableApi.getDataClient()).thenReturn(mockDataClientWrapper); when(mockDataClientWrapper.createBulkRead(isA(String.class))).thenReturn(mockBulkRead); byte[] key1 = randomBytes(8); byte[] key2 = randomBytes(8); Result result = Result.create( ImmutableList.<org.apache.hadoop.hbase.Cell>of( new RowCell( key1, "cf".getBytes(), "".getBytes(), 10, "hi!".getBytes(), ImmutableList.<String>of()))); RuntimeException exception = new RuntimeException("Something bad happened"); when(mockBulkRead.add(any(Query.class))) .thenReturn(ApiFutures.immediateFuture(result)) .thenReturn(ApiFutures.<Result>immediateFailedFuture(exception)); List<Get> gets = Arrays.asList(new Get(key1), new Get(key2)); Object[] results = new Object[2]; try { createExecutor().batch(gets, results); } catch (RetriesExhaustedWithDetailsException ignored) { } Assert.assertTrue("first result is a result", results[0] instanceof Result); Assert.assertArrayEquals(key1, ((Result) results[0]).getRow()); Assert.assertEquals(exception, results[1]); } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPartialResults() throws Exception { when(mockBigtableApi.getDataClient()).thenReturn(mockDataClientWrapper); when(mockDataClientWrapper.createBulkRead(isA(String.class))).thenReturn(mockBulkRead); byte[] key1 = randomBytes(8); byte[] key2 = randomBytes(8); Result expected = Result.create( ImmutableList.<org.apache.hadoop.hbase.Cell>of( new RowCell( key1, Bytes.toBytes("cf"), Bytes.toBytes(""), 10, Bytes.toBytes("hi!"), ImmutableList.<String>of()))); RuntimeException exception = new RuntimeException("Something bad happened"); when(mockBulkRead.add(any(Query.class))) .thenReturn(ApiFutures.immediateFuture(expected)) .thenReturn(ApiFutures.<Result>immediateFailedFuture(exception)); List<Get> gets = Arrays.asList(new Get(key1), new Get(key2)); Object[] results = new Object[2]; try { createExecutor().batch(gets, results); } catch (RetriesExhaustedWithDetailsException ignored) { } assertTrue("first result is a result", results[0] instanceof Result); assertTrue(matchesRow(expected).matches(results[0])); Assert.assertEquals(exception, results[1]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onClose(Status status, Metadata trailers) { try (Scope scope = TRACER.withSpan(operationSpan)) { synchronized (callLock) { call = NULL_CALL; } rpcTimerContext.close(); // OK if (status.isOk()) { if (onOK(trailers)) { finalizeStats(status); } } else { onError(status, trailers); } } catch (Exception e) { setException(e); } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void onClose(Status status, Metadata trailers) { try (Scope scope = TRACER.withSpan(operationSpan)) { callWrapper.resetCall(); rpcTimerContext.close(); // OK if (status.isOk()) { if (onOK(trailers)) { finalizeStats(status); } } else { onError(status, trailers); } } catch (Exception e) { setException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{ ServerSocket serverSocket = new ServerSocket(0); final int availablePort = serverSocket.getLocalPort(); serverSocket.close(); //Creates non-ssl server. createServer(availablePort); BigtableOptions bigtableOptions = BigtableOptions.builder() .setDataHost("localhost") .setAdminHost("localhost") .setProjectId(TEST_PROJECT_ID) .setInstanceId(TEST_INSTANCE_ID) .setUserAgent(TEST_USER_AGENT) .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setPort(availablePort) .build(); xGoogApiPattern = Pattern.compile(".* cbt/.*"); new BigtableSession(bigtableOptions).getDataClient() .readFlatRows(ReadRowsRequest.getDefaultInstance()).next(); Assert.assertTrue(serverPasses.get()); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCBC_UserAgentUsingPlainTextNegotiation() throws Exception{ ServerSocket serverSocket = new ServerSocket(0); final int availablePort = serverSocket.getLocalPort(); serverSocket.close(); //Creates non-ssl server. createServer(availablePort); BigtableOptions bigtableOptions = BigtableOptions.builder() .setDataHost("localhost") .setAdminHost("localhost") .setProjectId(TEST_PROJECT_ID) .setInstanceId(TEST_INSTANCE_ID) .setUserAgent(TEST_USER_AGENT) .setUsePlaintextNegotiation(true) .setCredentialOptions(CredentialOptions.nullCredential()) .setPort(availablePort) .build(); xGoogApiPattern = Pattern.compile(".* cbt/.*"); try (BigtableSession session = new BigtableSession(bigtableOptions)) { session.getDataClient() .readFlatRows(ReadRowsRequest.getDefaultInstance()).next(); Assert.assertTrue(serverPasses.get()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Result[] batch(final List<? extends org.apache.hadoop.hbase.client.Row> actions) throws Exception { return createExecutor(options).batch(actions); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private Result[] batch(final List<? extends org.apache.hadoop.hbase.client.Row> actions) throws Exception { return createExecutor().batch(actions); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onClose(Status status, Metadata trailers) { synchronized (callLock) { call = null; } rpcTimerContext.close(); Status.Code code = status.getCode(); // OK if (code == Status.Code.OK) { if (onOK()) { operationTimerContext.close(); } return; } // CANCELLED if (code == Status.Code.CANCELLED) { // An explicit user cancellation is not considered a failure. operationTimerContext.close(); return; } // Non retry scenario if (!retryOptions.enableRetries() || !retryOptions.isRetryable(code) // Unauthenticated is special because the request never made it to // to the server, so all requests are retryable || !(isRequestRetryable() || code == Code.UNAUTHENTICATED)) { rpc.getRpcMetrics().markFailure(); operationTimerContext.close(); setException(status.asRuntimeException()); return; } // Attempt retry with backoff long nextBackOff = getNextBackoff(); failedCount += 1; // Backoffs timed out. if (nextBackOff == BackOff.STOP) { rpc.getRpcMetrics().markRetriesExhasted(); operationTimerContext.close(); String message = String.format("Exhausted retries after %d failures.", failedCount); StatusRuntimeException cause = status.asRuntimeException(); setException(new BigtableRetriesExhaustedException(message, cause)); return; } else { String channelId = ChannelPool.extractIdentifier(trailers); LOG.info("Retrying failed call. Failure #%d, got: %s on channel %s", status.getCause(), failedCount, status, channelId); } performRetry(nextBackOff); } #location 53 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void onClose(Status status, Metadata trailers) { synchronized (callLock) { call = null; } rpcTimerContext.close(); // OK if (status.isOk()) { if (onOK(trailers)) { operationTimerContext.close(); } } else { onError(status, trailers); } }
Below is the vulnerable code, please generate the patch based on the following information.