output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code @Test public void testSingleFrame() throws Exception { final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder(); final ByteBuf content = Unpooled.copiedBuffer("hello", UTF_8); final List<Object> out = Lists.newArrayList(); decoder.header(content.readableBytes(), false, out); decoder.content(content, out); decoder.finish(out); final Object expected = ZMTPMessage.fromUTF8(ALLOC, "hello"); assertThat(out, hasSize(1)); assertThat(out, contains(expected)); }
#vulnerable code @Test public void testSingleFrame() throws Exception { final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder(); final ByteBuf content = Unpooled.copiedBuffer("hello", UTF_8); final List<Object> out = Lists.newArrayList(); decoder.header(content.readableBytes(), false, out); decoder.content(content, out); decoder.finish(out); final Object expected = new ZMTPIncomingMessage(fromUTF8(ALLOC, "hello"), false, 5); assertThat(out, hasSize(1)); assertThat(out, contains(expected)); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testOneFrame() throws Exception { final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf); ByteBuf frame = writer.frame(11, false); assertThat(frame, is(sameInstance(buf))); final ByteBuf content = copiedBuffer("hello world", UTF_8); frame.writeBytes(content.duplicate()); final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder()); decoder.decode(null, buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(content))); }
#vulnerable code @Test public void testOneFrame() throws Exception { final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf); ByteBuf frame = writer.frame(11, false); assertThat(frame, is(sameInstance(buf))); final ByteBuf content = copiedBuffer("hello world", UTF_8); frame.writeBytes(content.duplicate()); final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder()); parser.parse(buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(content))); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReframe() throws Exception { final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder()); final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf); // Request a frame with margin in anticipation of a larger payload... // ... but write a smaller payload final ByteBuf content = copiedBuffer("hello world", UTF_8); writer.frame(content.readableBytes() * 2, true).writeBytes(content.duplicate()); // And rewrite the frame accordingly writer.reframe(content.readableBytes(), false); // Verify that the message can be parsed decoder.decode(null, buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(content))); // Write and verify another message final ByteBuf next = copiedBuffer("next", UTF_8); writer.frame(next.readableBytes(), false).writeBytes(next.duplicate()); out.clear(); decoder.decode(null, buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(next))); }
#vulnerable code @Test public void testReframe() throws Exception { final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder()); final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf); // Request a frame with margin in anticipation of a larger payload... // ... but write a smaller payload final ByteBuf content = copiedBuffer("hello world", UTF_8); writer.frame(content.readableBytes() * 2, true).writeBytes(content.duplicate()); // And rewrite the frame accordingly writer.reframe(content.readableBytes(), false); // Verify that the message can be parsed parser.parse(buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(content))); // Write and verify another message final ByteBuf next = copiedBuffer("next", UTF_8); writer.frame(next.readableBytes(), false).writeBytes(next.duplicate()); out.clear(); parser.parse(buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) singletonList(next))); } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTwoFrames() throws Exception { final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder(); final ByteBuf f0 = Unpooled.copiedBuffer("hello", UTF_8); final ByteBuf f1 = Unpooled.copiedBuffer("world", UTF_8); final List<Object> out = Lists.newArrayList(); decoder.header(f0.readableBytes(), true, out); decoder.content(f0, out); decoder.header(f1.readableBytes(), false, out); decoder.content(f1, out); decoder.finish(out); final Object expected = ZMTPMessage.fromUTF8(ALLOC, "hello", "world"); assertThat(out, hasSize(1)); assertThat(out, contains(expected)); }
#vulnerable code @Test public void testTwoFrames() throws Exception { final ZMTPMessageDecoder decoder = new ZMTPMessageDecoder(); final ByteBuf f0 = Unpooled.copiedBuffer("hello", UTF_8); final ByteBuf f1 = Unpooled.copiedBuffer("world", UTF_8); final List<Object> out = Lists.newArrayList(); decoder.header(f0.readableBytes(), true, out); decoder.content(f0, out); decoder.header(f1.readableBytes(), false, out); decoder.content(f1, out); decoder.finish(out); final Object expected = new ZMTPIncomingMessage(fromUTF8(ALLOC, "hello", "world"), false, 10); assertThat(out, hasSize(1)); assertThat(out, contains(expected)); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTwoFrames() throws Exception { final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf); final ByteBuf f0 = copiedBuffer("hello ", UTF_8); final ByteBuf f1 = copiedBuffer("hello ", UTF_8); writer.frame(f0.readableBytes(), true).writeBytes(f0.duplicate()); writer.frame(f1.readableBytes(), false).writeBytes(f1.duplicate()); final ZMTPFramingDecoder decoder = new ZMTPFramingDecoder(wireFormat(ZMTP10), new RawDecoder()); decoder.decode(null, buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) asList(f0, f1))); }
#vulnerable code @Test public void testTwoFrames() throws Exception { final ZMTPWriter writer = ZMTPWriter.create(ZMTP10); final ByteBuf buf = Unpooled.buffer(); writer.reset(buf); final ByteBuf f0 = copiedBuffer("hello ", UTF_8); final ByteBuf f1 = copiedBuffer("hello ", UTF_8); writer.frame(f0.readableBytes(), true).writeBytes(f0.duplicate()); writer.frame(f1.readableBytes(), false).writeBytes(f1.duplicate()); final ZMTPParser parser = ZMTPParser.create(ZMTP10, new RawDecoder()); parser.parse(buf, out); assertThat(out, hasSize(1)); assertThat(out, contains((Object) asList(f0, f1))); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final Cache buildCache(String name) throws CacheException { if (log.isDebugEnabled()) { log.debug("Loading a new EhCache cache named [" + name + "]"); } try { net.sf.ehcache.Cache cache = getCacheManager().getCache(name); if (cache == null) { if (log.isWarnEnabled()) { log.warn("Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults."); } if ( name.equals(DEFAULT_ACTIVE_SESSIONS_CACHE_NAME) ) { if ( log.isInfoEnabled() ) { log.info("Creating " + DEFAULT_ACTIVE_SESSIONS_CACHE_NAME + " cache with default JSecurity " + "session cache settings." ); } cache = buildDefaultActiveSessionsCache(); manager.addCache( cache ); } else { manager.addCache( name ); cache = manager.getCache( name ); } if (log.isDebugEnabled()) { log.debug("Started EHCache named [" + name + "]"); } } return new EhCache(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } }
#vulnerable code public final Cache buildCache(String name) throws CacheException { if (log.isDebugEnabled()) { log.debug("Loading a new EhCache cache named [" + name + "]"); } try { net.sf.ehcache.Cache cache = getCacheManager().getCache(name); if (cache == null) { if (log.isWarnEnabled()) { log.warn("Could not find a specific ehcache configuration for cache named [" + name + "]; using defaults."); } if ( name.equals(DEFAULT_ACTIVE_SESSIONS_CACHE_NAME) ) { if ( log.isInfoEnabled() ) { log.info("Creating " + DEFAULT_ACTIVE_SESSIONS_CACHE_NAME + " cache with default JSecurity " + "session cache settings." ); } cache = buildDefaultActiveSessionsCache(); manager.addCache( cache ); } else { manager.addCache( name ); cache = manager.getCache( name ); } cache.initialise(); if (log.isDebugEnabled()) { log.debug("Started EHCache named [" + name + "]"); } } return new EhCache(cache); } catch (net.sf.ehcache.CacheException e) { throw new CacheException(e); } } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void bindPrincipalsToSessionIfNecessary( HttpServletRequest request ) { SecurityContext ctx = (SecurityContext) ThreadContext.get( ThreadContext.SECURITY_CONTEXT_KEY ); if ( ctx != null ) { Session session = ThreadLocalSecurityContext.current().getSession(); if( session != null && session.getAttribute( PRINCIPALS_SESSION_KEY) == null ) { session.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() ); } else { HttpSession httpSession = request.getSession(); if( httpSession.getAttribute( PRINCIPALS_SESSION_KEY ) == null ) { httpSession.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() ); } } } }
#vulnerable code public static void bindPrincipalsToSessionIfNecessary( HttpServletRequest request ) { SecurityContext ctx = (SecurityContext) ThreadContext.get( ThreadContext.SECURITY_CONTEXT_KEY ); if ( ctx != null ) { Session session = ThreadLocalSecurityContext.current().getSession( false ); if( session != null && session.getAttribute( PRINCIPALS_SESSION_KEY) == null ) { session.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() ); } else { HttpSession httpSession = request.getSession(); if( httpSession.getAttribute( PRINCIPALS_SESSION_KEY ) == null ) { httpSession.setAttribute( PRINCIPALS_SESSION_KEY, ctx.getAllPrincipals() ); } } } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int onDoStartTag() throws JspException { if ( getSecurityContext() != null && getSecurityContext().isAuthenticated() ) { return TagSupport.EVAL_BODY_INCLUDE; } else { return TagSupport.SKIP_BODY; } }
#vulnerable code public int onDoStartTag() throws JspException { if ( getSecurityContext().isAuthenticated() ) { return TagSupport.EVAL_BODY_INCLUDE; } else { return TagSupport.SKIP_BODY; } } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void create( Session session ) { Serializable id = session.getSessionId(); if ( id == null ) { String msg = "session must be assigned an id. Please check assignId( Session s ) " + "implementation."; throw new IllegalStateException( msg ); } if ( activeSessions.containsKey( id ) || stoppedSessions.containsKey( id ) ) { String msg = "There is an existing session already created with session id [" + id + "]. Session Id's must be unique."; throw new IllegalArgumentException( msg ); } synchronized ( activeSessions ) { activeSessions.put( id, session ); } }
#vulnerable code public void create( Session session ) { assignId( session ); Serializable id = session.getSessionId(); if ( id == null ) { String msg = "session must be assigned an id. Please check assignId( Session s ) " + "implementation."; throw new IllegalStateException( msg ); } if ( activeSessions.containsKey( id ) || stoppedSessions.containsKey( id ) ) { String msg = "There is an existing session already created with session id [" + id + "]. Session Id's must be unique."; throw new IllegalArgumentException( msg ); } synchronized ( activeSessions ) { activeSessions.put( id, session ); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int onDoStartTag() throws JspException { String strValue = null; if( getSecurityContext() != null && getSecurityContext().isAuthenticated() ) { // Get the principal to print out Principal principal; if( type == null ) { principal = getSecurityContext().getPrincipal(); } else { principal = getSecurityContext().getPrincipalByType( type ); } // Get the string value of the principal if( principal != null ) { if( property == null ) { strValue = principal.toString(); } else { strValue = getPrincipalProperty( principal, property ); } } } // Print out the principal value if not null if( strValue != null ) { try { pageContext.getOut().write( strValue ); } catch (IOException e) { throw new JspTagException( "Error writing [" + strValue + "] to JSP.", e ); } } return SKIP_BODY; }
#vulnerable code public int onDoStartTag() throws JspException { String strValue = null; if( getSecurityContext().isAuthenticated() ) { // Get the principal to print out Principal principal; if( type == null ) { principal = getSecurityContext().getPrincipal(); } else { principal = getSecurityContext().getPrincipalByType( type ); } // Get the string value of the principal if( principal != null ) { if( property == null ) { strValue = principal.toString(); } else { strValue = getPrincipalProperty( principal, property ); } } } // Print out the principal value if not null if( strValue != null ) { try { pageContext.getOut().write( strValue ); } catch (IOException e) { throw new JspTagException( "Error writing [" + strValue + "] to JSP.", e ); } } return SKIP_BODY; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) { Session session = (Session) ThreadContext.get( ThreadContext.SESSION_KEY ); Serializable sessionId; if( session != null ) { sessionId = session.getSessionId(); } else { sessionId = UUID.fromString( System.getProperty( "jsecurity.session.id" ) ); } if( sessionId != null ) { return new SecureRemoteInvocation( methodInvocation, sessionId ); } else { return super.createRemoteInvocation( methodInvocation ); } }
#vulnerable code public RemoteInvocation createRemoteInvocation(MethodInvocation methodInvocation) { Session session = ThreadLocalSecurityContext.current().getSession( false ); Serializable sessionId; if( session != null ) { sessionId = session.getSessionId(); } else { sessionId = UUID.fromString( System.getProperty( "jsecurity.session.id" ) ); } if( sessionId != null ) { return new SecureRemoteInvocation( methodInvocation, sessionId ); } else { return super.createRemoteInvocation( methodInvocation ); } } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean showTagBody( Permission p ) { boolean permitted = getSecurityContext() != null && getSecurityContext().implies( p ); return !permitted; }
#vulnerable code protected boolean showTagBody( Permission p ) { boolean permitted = getSecurityContext().implies( p ); return !permitted; } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean executeLogin(ServletRequest request, ServletResponse response) { if (log.isDebugEnabled()) { log.debug("Attempting to authenticate Subject based on Http BASIC Authentication request..."); } String authorizationHeader = getAuthzHeader(request); if (authorizationHeader == null || authorizationHeader.length() == 0 ) { return false; } if (log.isDebugEnabled()) { log.debug("Attempting to execute login with headers [" + authorizationHeader + "]"); } String[] prinCred = getPrincipalsAndCredentials(authorizationHeader, request); if ( prinCred == null || prinCred.length < 2 ) { return false; } String username = prinCred[0]; String password = prinCred[1]; if (log.isDebugEnabled()) { log.debug("Processing login request for username [" + username + "]"); } AuthenticationToken token = createToken(username, password, request ); if ( token != null ) { return executeLogin(token, request, response ); } //always default to false. If we've made it to this point in the code, that //means the authentication attempt either never occured, or wasn't successful: return false; }
#vulnerable code protected boolean executeLogin(ServletRequest request, ServletResponse response) { if (log.isDebugEnabled()) { log.debug("Attempting to authenticate Subject based on Http BASIC Authentication request..."); } HttpServletRequest httpRequest = toHttp(request); String authorizationHeader = httpRequest.getHeader(AUTHORIZATION_HEADER); if (authorizationHeader != null && authorizationHeader.length() > 0) { if (log.isDebugEnabled()) { log.debug("Executing login with headers [" + authorizationHeader + "]"); } String[] authTokens = authorizationHeader.split(" "); if (authTokens[0].trim().equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) { String encodedCredentials = authTokens[1]; String decodedCredentials = Base64.decodeToString(encodedCredentials); String[] credentials = decodedCredentials.split(":"); if (credentials != null && credentials.length > 1) { if (log.isDebugEnabled()) { log.debug("Processing login request [" + credentials[0] + "]"); } Subject subject = getSubject(request, response); UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(credentials[0], credentials[1]); try { subject.login(usernamePasswordToken); if (log.isDebugEnabled()) { log.debug("Successfully logged in user [" + credentials[0] + "]"); } return true; } catch (AuthenticationException ae) { if (log.isDebugEnabled()) { log.debug("Unable to log in subject [" + credentials[0] + "]", ae); } } } } } //always default to false. If we've made it to this point in the code, that //means the authentication attempt either never occured, or wasn't successful: return false; } #location 30 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void send( AuthenticationEvent event ) { if ( listeners != null && !listeners.isEmpty() ) { for ( AuthenticationEventListener ael : listeners ) { ael.onEvent( event ); } } else { if ( log.isWarnEnabled() ) { String msg = "internal listeners collection is null. No " + "AuthenticationEventListeners will be notified of event [" + event + "]"; log.warn( msg ); } } }
#vulnerable code public void send( AuthenticationEvent event ) { if ( listeners != null && !listeners.isEmpty() ) { synchronized ( listeners ) { for ( AuthenticationEventListener ael : listeners ) { if ( event instanceof SuccessfulAuthenticationEvent) { ael.accountAuthenticated( event ); } else if ( event instanceof UnlockedAccountEvent) { ael.accountUnlocked( event ); } else if ( event instanceof LogoutEvent) { ael.accountLoggedOut( event ); } else if ( event instanceof FailedAuthenticationEvent) { FailedAuthenticationEvent failedEvent = (FailedAuthenticationEvent)event; AuthenticationException cause = failedEvent.getCause(); if ( cause != null && ( cause instanceof LockedAccountException ) ) { ael.accountLocked( event ); } else { ael.authenticationFailed( event ); } } else { String msg = "Received argument of type [" + event.getClass() + "]. This " + "implementation can only send event instances of types " + SuccessfulAuthenticationEvent.class.getName() + ", " + FailedAuthenticationEvent.class.getName() + ", " + UnlockedAccountEvent.class.getName() + ", or " + LogoutEvent.class.getName(); throw new IllegalArgumentException( msg ); } } } } else { if ( log.isWarnEnabled() ) { String msg = "internal listeners collection is null. No " + "AuthenticationEventListeners will be notified of event [" + event + "]"; log.warn( msg ); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings({"unchecked"}) public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); String[] rolesArray = (String[]) mappedValue; if (rolesArray == null || rolesArray.length == 0) { //no roles specified, so nothing to check - allow access. return true; } Set<String> roles = CollectionUtils.asSet(rolesArray); return subject.hasAllRoles(roles); }
#vulnerable code @SuppressWarnings({"unchecked"}) public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); Set<String> roles = (Set<String>) mappedValue; boolean hasRoles = true; if (roles != null && !roles.isEmpty()) { if (roles.size() == 1) { if (!subject.hasRole(roles.iterator().next())) { hasRoles = false; } } else { if (!subject.hasAllRoles(roles)) { hasRoles = false; } } } return hasRoles; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean showTagBody( Permission p ) { return getSecurityContext() != null && getSecurityContext().implies( p ); }
#vulnerable code protected boolean showTagBody( Permission p ) { return getSecurityContext().implies( p ); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void send( SessionEvent event ) { if ( listeners != null && !listeners.isEmpty() ) { for( SessionEventListener sel : listeners ) { sel.onEvent( event ); } } }
#vulnerable code public void send( SessionEvent event ) { synchronized( listeners ) { for( SessionEventListener sel : listeners ) { if ( event instanceof StartedSessionEvent) { sel.sessionStarted( event ); } else if ( event instanceof ExpiredSessionEvent) { sel.sessionExpired( event ); } else if ( event instanceof StoppedSessionEvent) { sel.sessionStopped( event ); } else { String msg = "Received argument of type [" + event.getClass() + "]. This " + "implementation can only send event instances of types " + StartedSessionEvent.class.getName() + ", " + ExpiredSessionEvent.class.getName() + ", or " + StoppedSessionEvent.class.getName(); throw new IllegalArgumentException( msg ); } } } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings({"unchecked"}) public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); String[] rolesArray = (String[]) mappedValue; if (rolesArray == null || rolesArray.length == 0) { //no roles specified, so nothing to check - allow access. return true; } Set<String> roles = CollectionUtils.asSet(rolesArray); return subject.hasAllRoles(roles); }
#vulnerable code @SuppressWarnings({"unchecked"}) public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException { Subject subject = getSubject(request, response); Set<String> roles = (Set<String>) mappedValue; boolean hasRoles = true; if (roles != null && !roles.isEmpty()) { if (roles.size() == 1) { if (!subject.hasRole(roles.iterator().next())) { hasRoles = false; } } else { if (!subject.hasAllRoles(roles)) { hasRoles = false; } } } return hasRoles; } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int onDoStartTag() throws JspException { if ( getSecurityContext() == null || !getSecurityContext().isAuthenticated() ) { return TagSupport.EVAL_BODY_INCLUDE; } else { return TagSupport.SKIP_BODY; } }
#vulnerable code public int onDoStartTag() throws JspException { if ( !getSecurityContext().isAuthenticated() ) { return TagSupport.EVAL_BODY_INCLUDE; } else { return TagSupport.SKIP_BODY; } } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean showTagBody( String roleName ) { return getSecurityContext() != null && getSecurityContext().hasRole( roleName ); }
#vulnerable code protected boolean showTagBody( String roleName ) { return getSecurityContext().hasRole( roleName ); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean bindInHttpSessionForSubsequentRequests( HttpServletRequest request, HttpServletResponse response, SecurityContext securityContext ) { HttpSession httpSession = request.getSession(); // Don't overwrite any previous credentials - i.e. SecurityContext swapping for a previously // initialized session is not allowed. // Only store principals if they exist in the security context Object currentPrincipal = httpSession.getAttribute(PRINCIPALS_SESSION_KEY); if ( currentPrincipal == null && !securityContext.getAllPrincipals().isEmpty() ) { httpSession.setAttribute( PRINCIPALS_SESSION_KEY, securityContext.getAllPrincipals() ); } // Only bind if the current value in the session is null or it doesn't equal the security context value Boolean currentAuthenticated = (Boolean) httpSession.getAttribute( AUTHENTICATED_SESSION_KEY ); if ( currentAuthenticated == null || !currentAuthenticated.equals( securityContext.isAuthenticated() ) ) { httpSession.setAttribute( AUTHENTICATED_SESSION_KEY, securityContext.isAuthenticated() ); } return true; }
#vulnerable code protected boolean bindInHttpSessionForSubsequentRequests( HttpServletRequest request, HttpServletResponse response, SecurityContext securityContext ) { HttpSession httpSession = request.getSession(); Object currentPrincipal = httpSession.getAttribute(PRINCIPALS_SESSION_KEY); if ( currentPrincipal == null && !securityContext.getAllPrincipals().isEmpty() ) { httpSession.setAttribute( PRINCIPALS_SESSION_KEY, securityContext.getAllPrincipals() ); } Boolean currentAuthenticated = (Boolean) httpSession.getAttribute( AUTHENTICATED_SESSION_KEY ); if ( !currentAuthenticated.equals( securityContext.isAuthenticated() ) ) { httpSession.setAttribute( AUTHENTICATED_SESSION_KEY, securityContext.getAllPrincipals() ); } return true; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean showTagBody( String roleName ) { boolean hasRole = getSecurityContext() != null && getSecurityContext().hasRole( roleName ); return !hasRole; }
#vulnerable code protected boolean showTagBody( String roleName ) { boolean hasRole = getSecurityContext().hasRole( roleName ); return !hasRole; } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings( "unchecked" ) private static List<Principal> getPrincipals(HttpServletRequest request) { List<Principal> principals = null; Session session = (Session) ThreadContext.get( ThreadContext.SESSION_KEY ); if( session != null ) { principals = (List<Principal>) session.getAttribute( PRINCIPALS_SESSION_KEY ); } else { HttpSession httpSession = request.getSession( false ); if( httpSession != null ) { principals = (List<Principal>) httpSession.getAttribute( PRINCIPALS_SESSION_KEY ); } } return principals; }
#vulnerable code @SuppressWarnings( "unchecked" ) private static List<Principal> getPrincipals(HttpServletRequest request) { List<Principal> principals = null; Session session = ThreadLocalSecurityContext.current().getSession( false ); if( session != null ) { principals = (List<Principal>) session.getAttribute( PRINCIPALS_SESSION_KEY ); } else { HttpSession httpSession = request.getSession( false ); if( httpSession != null ) { principals = (List<Principal>) httpSession.getAttribute( PRINCIPALS_SESSION_KEY ); } } return principals; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code DbAction.Insert<?> createInsert(String propertyName, Object value, @Nullable Object key) { DbAction.Insert<Object> insert = new DbAction.Insert<>(value, context.getPersistentPropertyPath(propertyName, DummyEntity.class), rootInsert); insert.getQualifiers().put(toPath(propertyName), key); return insert; }
#vulnerable code DbAction.Insert<?> createDeepInsert(String propertyName, Object value, Object key, @Nullable DbAction.Insert<?> parentInsert) { PersistentPropertyPath<RelationalPersistentProperty> propertyPath = toPath(parentInsert.getPropertyPath().toDotPath() + "." + propertyName); DbAction.Insert<Object> insert = new DbAction.Insert<>(value, propertyPath, parentInsert); insert.getQualifiers().put(propertyPath, key); return insert; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Class<?> getQualifierColumnType() { Assert.isTrue(isQualified(), "The qualifier column type is only defined for properties that are qualified"); if (isMap()) { return getTypeInformation().getRequiredComponentType().getType(); } // for lists and arrays return Integer.class; }
#vulnerable code @Override public Class<?> getQualifierColumnType() { Assert.isTrue(isQualified(), "The qualifier column type is only defined for properties that are qualified"); if (isMap()) { return getTypeInformation().getComponentType().getType(); } // for lists and arrays return Integer.class; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void test() { Flowable.just("hi there".getBytes()) .compose(Transformers.outputStream(new Function<OutputStream, OutputStream>() { @Override public OutputStream apply(OutputStream os) throws Exception { return new GZIPOutputStream(os); } }, 8192, 16)) .test(); }
#vulnerable code @Test public void test() throws IOException { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); Flowable.just("hi there".getBytes()) .compose(Transformers.outputStream(new Function<OutputStream, OutputStream>() { @Override public OutputStream apply(OutputStream os) throws Exception { return new GZIPOutputStream(os); } }, 8192, 16)).doOnNext(new Consumer<byte[]>() { @Override public void accept(byte[] b) throws Exception { bytes.write(b); } }).test() .assertComplete(); InputStream is = new GZIPInputStream(new ByteArrayInputStream(bytes.toByteArray())); assertEquals("hi there",read(is)); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void load() { Optional<String> region = loadRegion(); if (region.isPresent()) { this.region = region.get(); } else { this.region = DEFAULT_REGION; LOG.warn("Could not load region configuration. Please ensure AWS CLI is " + "configured via 'aws configure'. Will use default region of " + this.region); } }
#vulnerable code public void load() { String home = System.getProperty("user.home"); Properties awsConfigProperties = new Properties(); try { // todo: use default profile awsConfigProperties.load(new FileInputStream(home + "/.aws/config")); } catch (IOException e) { throw new RuntimeException("Could not load configuration. Please run 'aws configure'"); } String region = awsConfigProperties.getProperty("region"); if (region != null) { this.region = region; } else { LOG.warn("Could not load region configuration. Please ensure AWS CLI is configured via 'aws configure'. Will use default region of " + this.region); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code SegmentView getActiveSegmentView() { return segmentlist.get(segmentlist.size()-1); }
#vulnerable code EntryLocation getLocationForOffset(long offset) { EntryLocation ret = new EntryLocation(); SegmentView sv = this.getSegmentForOffset(offset); long reloff = offset - sv.startoff; //select the group using a simple modulo mapping function int gnum = (int)(reloff%sv.numgroups); ret.group = sv.groups[gnum]; ret.relativeOff = reloff/sv.numgroups + ret.group.localstartoff; log.info("location({}): seg.startOff={} gnum={} group-startOff={} relativeOff={} ", offset, sv.startoff, gnum, ret.group.localstartoff, ret.relativeOff); return ret; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } if (saveAs.exists()) { if (Utils.getConfigBoolean("file.overwrite", false)) { logger.info("[!] Deleting existing file" + prettySaveAs); saveAs.delete(); } else { logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs); observer.downloadProblem(url, "File already exists: " + prettySaveAs); return; } } int tries = 0; // Number of attempts to download do { tries += 1; InputStream bis = null; OutputStream fos = null; try { logger.info(" Downloading file: " + url + (tries > 0 ? " Retry #" + tries : "")); observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm()); // Setup HTTP request HttpURLConnection huc = (HttpURLConnection) this.url.openConnection(); huc.setConnectTimeout(TIMEOUT); huc.setRequestProperty("accept", "*/*"); huc.setRequestProperty("Referer", referrer); // Sic huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT); String cookie = ""; for (String key : cookies.keySet()) { if (!cookie.equals("")) { cookie += "; "; } cookie += key + "=" + cookies.get(key); } huc.setRequestProperty("Cookie", cookie); huc.connect(); int statusCode = huc.getResponseCode(); if (statusCode / 100 == 4) { // 4xx errors logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url); observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm()); return; // Not retriable, drop out. } if (statusCode / 100 == 5) { // 5xx errors observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm()); // Throw exception so download can be retried throw new IOException("Retriable status code " + statusCode); } if (huc.getContentLength() == 503 && url.getHost().endsWith("imgur.com")) { // Imgur image with 503 bytes is "404" logger.error("[!] Imgur image is 404 (503 bytes long): " + url); observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm()); return; } // Save file bis = new BufferedInputStream(huc.getInputStream()); fos = new FileOutputStream(saveAs); IOUtils.copy(bis, fos); break; // Download successful: break out of infinite loop } catch (HttpStatusException hse) { logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + url); if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) { observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm()); return; } } catch (IOException e) { logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage(), e); } finally { // Close any open streams try { if (bis != null) { bis.close(); } } catch (IOException e) { } try { if (fos != null) { fos.close(); } } catch (IOException e) { } } if (tries > this.retries) { logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url); observer.downloadErrored(url, "Failed to download " + url.toExternalForm()); return; } } while (true); observer.downloadCompleted(url, saveAs); logger.info("[+] Saved " + url + " as " + this.prettySaveAs); }
#vulnerable code public void run() { try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } if (saveAs.exists()) { if (Utils.getConfigBoolean("file.overwrite", false)) { logger.info("[!] Deleting existing file" + prettySaveAs); saveAs.delete(); } else { logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs); observer.downloadProblem(url, "File already exists: " + prettySaveAs); return; } } int tries = 0; // Number of attempts to download do { try { logger.info(" Downloading file: " + url + (tries > 0 ? " Retry #" + tries : "")); observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm()); tries += 1; Response response; response = Jsoup.connect(url.toExternalForm()) .ignoreContentType(true) .userAgent(AbstractRipper.USER_AGENT) .header("accept", "*/*") .timeout(TIMEOUT) .maxBodySize(MAX_BODY_SIZE) .cookies(cookies) .referrer(referrer) .execute(); if (response.statusCode() != 200) { logger.error("[!] Non-OK status code " + response.statusCode() + " while downloading from " + url); observer.downloadErrored(url, "Non-OK status code " + response.statusCode() + " while downloading " + url.toExternalForm()); return; } byte[] bytes = response.bodyAsBytes(); if (bytes.length == 503 && url.getHost().endsWith("imgur.com")) { // Imgur image with 503 bytes is "404" logger.error("[!] Imgur image is 404 (503 bytes long): " + url); observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm()); return; } FileOutputStream out = new FileOutputStream(saveAs); out.write(response.bodyAsBytes()); out.close(); break; // Download successful: break out of infinite loop } catch (HttpStatusException hse) { logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + url); observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm()); if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) { return; } } catch (IOException e) { logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage(), e); } if (tries > this.retries) { logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url); observer.downloadErrored(url, "Failed to download " + url.toExternalForm()); return; } } while (true); observer.downloadCompleted(url, saveAs); logger.info("[+] Saved " + url + " as " + this.prettySaveAs); } #location 51 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testTwitterAlbums() throws IOException { if (!DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); //contentURLs.add(new URL("https://twitter.com/danngamber01/media")); contentURLs.add(new URL("https://twitter.com/search?q=from%3Apurrbunny%20filter%3Aimages&src=typd")); for (URL url : contentURLs) { try { TwitterRipper ripper = new TwitterRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } }
#vulnerable code public void testTwitterAlbums() throws IOException { List<URL> contentURLs = new ArrayList<URL>(); //contentURLs.add(new URL("https://twitter.com/danngamber01/media")); contentURLs.add(new URL("https://twitter.com/search?q=from%3Apurrbunny%20filter%3Aimages&src=typd")); for (URL url : contentURLs) { try { TwitterRipper ripper = new TwitterRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testTumblrAlbums() throws IOException { if (!DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); contentURLs.add(new URL("http://wrouinr.tumblr.com/archive")); contentURLs.add(new URL("http://topinstagirls.tumblr.com/tagged/berlinskaya")); contentURLs.add(new URL("http://fittingroomgirls.tumblr.com/post/78268776776")); for (URL url : contentURLs) { try { TumblrRipper ripper = new TumblrRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } }
#vulnerable code public void testTumblrAlbums() throws IOException { if (false && !DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); contentURLs.add(new URL("http://wrouinr.tumblr.com/archive")); //contentURLs.add(new URL("http://topinstagirls.tumblr.com/tagged/berlinskaya")); //contentURLs.add(new URL("http://fittingroomgirls.tumblr.com/post/78268776776")); for (URL url : contentURLs) { try { TumblrRipper ripper = new TumblrRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static List<Constructor<?>> getRipperConstructors() throws Exception { List<Constructor<?>> constructors = new ArrayList<Constructor<?>>(); for (Class<?> clazz : getClassesForPackage("com.rarchives.ripme.ripper.rippers")) { if (AbstractRipper.class.isAssignableFrom(clazz)) { constructors.add( (Constructor<?>) clazz.getConstructor(URL.class) ); } } return constructors; }
#vulnerable code private static List<Constructor<?>> getRipperConstructors() throws Exception { List<Constructor<?>> constructors = new ArrayList<Constructor<?>>(); String rippersPackage = "com.rarchives.ripme.ripper.rippers"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> urls = cl.getResources(rippersPackage.replaceAll("\\.", "/")); if (!urls.hasMoreElements()) { return constructors; } URL classURL = urls.nextElement(); for (File f : new File(classURL.toURI()).listFiles()) { String className = f.getName(); if (!className.endsWith(".class") || className.contains("$") || className.endsWith("Test.class")) { // Ignore non-class or nested classes. continue; } className = className.substring(0, className.length() - 6); // Strip .class String fqname = rippersPackage + "." + className; Class<?> clazz = Class.forName(fqname); constructors.add( (Constructor<?>) clazz.getConstructor(URL.class)); } return constructors; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testXvideosRipper() throws IOException { if (!DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); contentURLs.add(new URL("http://www.xvideos.com/video1428195/stephanie_first_time_anal")); contentURLs.add(new URL("http://www.xvideos.com/video7136868/vid-20140205-wa0011")); for (URL url : contentURLs) { try { XvideosRipper ripper = new XvideosRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } }
#vulnerable code public void testXvideosRipper() throws IOException { if (false && !DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); contentURLs.add(new URL("http://www.xvideos.com/video1428195/stephanie_first_time_anal")); contentURLs.add(new URL("http://www.xvideos.com/video7136868/vid-20140205-wa0011")); for (URL url : contentURLs) { try { XvideosRipper ripper = new XvideosRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void downloadProblem(URL url, String message) { if (observer == null) { return; } synchronized(observer) { itemsPending.remove(url); itemsErrored.put(url, message); observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message)); observer.notifyAll(); } checkIfComplete(); }
#vulnerable code public void downloadProblem(URL url, String message) { if (observer == null) { return; } synchronized(observer) { itemsPending.remove(url); itemsErrored.put(url, message); observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message)); observer.notifyAll(); checkIfComplete(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testRedditAlbums() throws IOException { if (!DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); //contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc")); //contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc/top?t=all")); //contentURLs.add(new URL("http://www.reddit.com/u/gingerpuss")); contentURLs.add(new URL("http://www.reddit.com/r/UnrealGirls/comments/1ziuhl/in_class_veronique_popa/")); for (URL url : contentURLs) { try { RedditRipper ripper = new RedditRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } }
#vulnerable code public void testRedditAlbums() throws IOException { if (false && !DOWNLOAD_CONTENT) { return; } List<URL> contentURLs = new ArrayList<URL>(); //contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc")); //contentURLs.add(new URL("http://www.reddit.com/r/nsfw_oc/top?t=all")); //contentURLs.add(new URL("http://www.reddit.com/u/gingerpuss")); contentURLs.add(new URL("http://www.reddit.com/r/UnrealGirls/comments/1ziuhl/in_class_veronique_popa/")); for (URL url : contentURLs) { try { RedditRipper ripper = new RedditRipper(url); ripper.rip(); assert(ripper.getWorkingDir().listFiles().length > 1); deleteDir(ripper.getWorkingDir()); } catch (Exception e) { e.printStackTrace(); fail("Error while ripping URL " + url + ": " + e.getMessage()); } } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void login() throws IOException { try { String dACookies = Utils.getConfigString(utilsKey, null); this.cookies = dACookies != null ? deserialize(dACookies) : null; } catch (ClassNotFoundException e) { e.printStackTrace(); } if (this.cookies == null) { LOGGER.info("Log in now"); // Do login now // Load login page Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET) .referrer(referer).userAgent(userAgent).execute(); // Find tokens Document doc = res.parse(); Element form = doc.getElementById("login"); String token = form.select("input[name=\"validate_token\"]").first().attr("value"); String key = form.select("input[name=\"validate_key\"]").first().attr("value"); LOGGER.info("Token: " + token + " & Key: " + key); // Build Login Data HashMap<String, String> loginData = new HashMap<String, String>(); loginData.put("challenge", ""); loginData.put("username", username); loginData.put("password", password); loginData.put("remember_me", "1"); loginData.put("validate_token", token); loginData.put("validate_key", key); Map<String, String> cookies = res.cookies(); // Log in using data. Handle redirect res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent) .method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute(); this.cookies = res.cookies(); res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent) .method(Method.GET).cookies(cookies).followRedirects(false).execute(); // Store cookies updateCookie(res.cookies()); // Apply agegate this.cookies.put("agegate_state", "1"); // Write Cookie to file for other RipMe Instances or later use Utils.setConfigString(utilsKey, serialize(new HashMap<String, String>(this.cookies))); Utils.saveConfig(); // save now because of other instances that might work simultaneously } LOGGER.info("DA Cookies: " + this.cookies); }
#vulnerable code private void login() throws IOException { File f = new File("DACookie.toDelete"); if (!f.exists()) { f.createNewFile(); f.deleteOnExit(); // Load login page Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET) .referrer(referer).userAgent(userAgent).execute(); // Find tokens Document doc = res.parse(); Element form = doc.getElementById("login"); String token = form.select("input[name=\"validate_token\"]").first().attr("value"); String key = form.select("input[name=\"validate_key\"]").first().attr("value"); System.out.println( "------------------------------" + token + " & " + key + "------------------------------"); // Build Login Data HashMap<String, String> loginData = new HashMap<String, String>(); loginData.put("challenge", ""); loginData.put("username", username); loginData.put("password", password); loginData.put("remember_me", "1"); loginData.put("validate_token", token); loginData.put("validate_key", key); Map<String, String> cookies = res.cookies(); // Log in using data. Handle redirect res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent) .method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute(); this.cookies = res.cookies(); res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent) .method(Method.GET).cookies(cookies).followRedirects(false).execute(); // Store cookies updateCookie(res.cookies()); // Apply agegate this.cookies.put("agegate_state", "1"); // Write Cookie to file for other RipMe Instances try { FileOutputStream fileOut = new FileOutputStream(f); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(this.cookies); out.close(); fileOut.close(); } catch (IOException i) { i.printStackTrace(); } } else { // When cookie file already exists (from another RipMe instance) while (this.cookies == null) { try { Thread.sleep(2000); FileInputStream fileIn = new FileInputStream(f); ObjectInputStream in = new ObjectInputStream(fileIn); this.cookies = (Map<String, String>) in.readObject(); in.close(); fileIn.close(); } catch (IOException | ClassNotFoundException | InterruptedException i) { i.printStackTrace(); } } } System.out.println("------------------------------" + this.cookies + "------------------------------"); } #location 66 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<String>(); for (Element el : doc.select("a.image-container > img")) { String imageSource = el.attr("src"); // We remove the .md from images so we download the full size image // not the medium ones imageSource = imageSource.replace(".md", ""); result.add(imageSource); } return result; }
#vulnerable code @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<String>(); Document userpage_doc; // We check for the following string to see if this is a user page or not if (doc.toString().contains("content=\"gallery\"")) { for (Element elem : doc.select("a.image-container")) { String link = elem.attr("href"); logger.info("Grabbing album " + link); try { userpage_doc = Http.url(link).get(); } catch(IOException e){ logger.warn("Failed to log link in Jsoup"); userpage_doc = null; e.printStackTrace(); } for (Element element : userpage_doc.select("a.image-container > img")) { String imageSource = element.attr("src"); logger.info("Found image " + link); // We remove the .md from images so we download the full size image // not the medium ones imageSource = imageSource.replace(".md", ""); result.add(imageSource); } } } else { for (Element el : doc.select("a.image-container > img")) { String imageSource = el.attr("src"); // We remove the .md from images so we download the full size image // not the medium ones imageSource = imageSource.replace(".md", ""); result.add(imageSource); } } return result; } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { long fileSize = 0; int bytesTotal = 0; int bytesDownloaded = 0; if (saveAs.exists() && observer.tryResumeDownload()) { fileSize = saveAs.length(); } try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } if (saveAs.exists() && !observer.tryResumeDownload() || Utils.fuzzyExists(new File(saveAs.getParent()), saveAs.getName())) { if (Utils.getConfigBoolean("file.overwrite", false)) { logger.info("[!] Deleting existing file" + prettySaveAs); saveAs.delete(); } else { logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs); observer.downloadExists(url, saveAs); return; } } URL urlToDownload = this.url; boolean redirected = false; int tries = 0; // Number of attempts to download do { tries += 1; InputStream bis = null; OutputStream fos = null; try { logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : "")); observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm()); // Setup HTTP request HttpURLConnection huc; if (this.url.toString().startsWith("https")) { huc = (HttpsURLConnection) urlToDownload.openConnection(); } else { huc = (HttpURLConnection) urlToDownload.openConnection(); } huc.setInstanceFollowRedirects(true); huc.setConnectTimeout(TIMEOUT); huc.setRequestProperty("accept", "*/*"); if (!referrer.equals("")) { huc.setRequestProperty("Referer", referrer); // Sic } huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT); String cookie = ""; for (String key : cookies.keySet()) { if (!cookie.equals("")) { cookie += "; "; } cookie += key + "=" + cookies.get(key); } huc.setRequestProperty("Cookie", cookie); if (observer.tryResumeDownload()) { if (fileSize != 0) { huc.setRequestProperty("Range", "bytes=" + fileSize + "-"); } } logger.debug("Request properties: " + huc.getRequestProperties()); huc.connect(); int statusCode = huc.getResponseCode(); logger.debug("Status code: " + statusCode); if (statusCode != 206 && observer.tryResumeDownload() && saveAs.exists()) { // TODO find a better way to handle servers that don't support resuming downloads then just erroring out throw new IOException("Server doesn't support resuming downloads"); } if (statusCode / 100 == 3) { // 3xx Redirect if (!redirected) { // Don't increment retries on the first redirect tries--; redirected = true; } String location = huc.getHeaderField("Location"); urlToDownload = new URL(location); // Throw exception so download can be retried throw new IOException("Redirect status code " + statusCode + " - redirect to " + location); } if (statusCode / 100 == 4) { // 4xx errors logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url); observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm()); return; // Not retriable, drop out. } if (statusCode / 100 == 5) { // 5xx errors observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm()); // Throw exception so download can be retried throw new IOException("Retriable status code " + statusCode); } if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) { // Imgur image with 503 bytes is "404" logger.error("[!] Imgur image is 404 (503 bytes long): " + url); observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm()); return; } // If the ripper is using the bytes progress bar set bytesTotal to huc.getContentLength() if (observer.useByteProgessBar()) { bytesTotal = huc.getContentLength(); observer.setBytesTotal(bytesTotal); observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal); logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b"); } // Save file bis = new BufferedInputStream(huc.getInputStream()); // Check if we should get the file ext from the MIME type if (getFileExtFromMIME) { String fileExt = URLConnection.guessContentTypeFromStream(bis); if (fileExt != null) { fileExt = fileExt.replaceAll("image/", ""); saveAs = new File(saveAs.toString() + "." + fileExt); } else { logger.error("Was unable to get content type from stream"); // Try to get the file type from the magic number byte[] magicBytes = new byte[8]; bis.read(magicBytes,0, 5); bis.reset(); fileExt = Utils.getEXTFromMagic(magicBytes); if (fileExt != null) { saveAs = new File(saveAs.toString() + "." + fileExt); } else { logger.error("Was unable to get content type using magic number"); logger.error("Magic number was: " + Arrays.toString(magicBytes)); } } } // If we're resuming a download we append data to the existing file if (statusCode == 206) { fos = new FileOutputStream(saveAs, true); } else { fos = new FileOutputStream(saveAs); } byte[] data = new byte[1024 * 256]; int bytesRead; while ( (bytesRead = bis.read(data)) != -1) { try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } fos.write(data, 0, bytesRead); if (observer.useByteProgessBar()) { bytesDownloaded += bytesRead; observer.setBytesCompleted(bytesDownloaded); observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded); } } bis.close(); fos.close(); break; // Download successful: break out of infinite loop } catch (HttpStatusException hse) { logger.debug("HTTP status exception", hse); logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload); if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) { observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm()); return; } } catch (IOException e) { logger.debug("IOException", e); logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage()); } finally { // Close any open streams try { if (bis != null) { bis.close(); } } catch (IOException e) { } try { if (fos != null) { fos.close(); } } catch (IOException e) { } } if (tries > this.retries) { logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url); observer.downloadErrored(url, "Failed to download " + url.toExternalForm()); return; } } while (true); observer.downloadCompleted(url, saveAs); logger.info("[+] Saved " + url + " as " + this.prettySaveAs); }
#vulnerable code public void run() { long fileSize = 0; int bytesTotal = 0; int bytesDownloaded = 0; if (saveAs.exists() && observer.tryResumeDownload()) { fileSize = saveAs.length(); } try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } if (saveAs.exists() && !observer.tryResumeDownload()) { if (Utils.getConfigBoolean("file.overwrite", false)) { logger.info("[!] Deleting existing file" + prettySaveAs); saveAs.delete(); } else { logger.info("[!] Skipping " + url + " -- file already exists: " + prettySaveAs); observer.downloadExists(url, saveAs); return; } } URL urlToDownload = this.url; boolean redirected = false; int tries = 0; // Number of attempts to download do { tries += 1; InputStream bis = null; OutputStream fos = null; try { logger.info(" Downloading file: " + urlToDownload + (tries > 0 ? " Retry #" + tries : "")); observer.sendUpdate(STATUS.DOWNLOAD_STARTED, url.toExternalForm()); // Setup HTTP request HttpURLConnection huc; if (this.url.toString().startsWith("https")) { huc = (HttpsURLConnection) urlToDownload.openConnection(); } else { huc = (HttpURLConnection) urlToDownload.openConnection(); } huc.setInstanceFollowRedirects(true); huc.setConnectTimeout(TIMEOUT); huc.setRequestProperty("accept", "*/*"); if (!referrer.equals("")) { huc.setRequestProperty("Referer", referrer); // Sic } huc.setRequestProperty("User-agent", AbstractRipper.USER_AGENT); String cookie = ""; for (String key : cookies.keySet()) { if (!cookie.equals("")) { cookie += "; "; } cookie += key + "=" + cookies.get(key); } huc.setRequestProperty("Cookie", cookie); if (observer.tryResumeDownload()) { if (fileSize != 0) { huc.setRequestProperty("Range", "bytes=" + fileSize + "-"); } } logger.debug("Request properties: " + huc.getRequestProperties()); huc.connect(); int statusCode = huc.getResponseCode(); logger.debug("Status code: " + statusCode); if (statusCode != 206 && observer.tryResumeDownload() && saveAs.exists()) { // TODO find a better way to handle servers that don't support resuming downloads then just erroring out throw new IOException("Server doesn't support resuming downloads"); } if (statusCode / 100 == 3) { // 3xx Redirect if (!redirected) { // Don't increment retries on the first redirect tries--; redirected = true; } String location = huc.getHeaderField("Location"); urlToDownload = new URL(location); // Throw exception so download can be retried throw new IOException("Redirect status code " + statusCode + " - redirect to " + location); } if (statusCode / 100 == 4) { // 4xx errors logger.error("[!] Non-retriable status code " + statusCode + " while downloading from " + url); observer.downloadErrored(url, "Non-retriable status code " + statusCode + " while downloading " + url.toExternalForm()); return; // Not retriable, drop out. } if (statusCode / 100 == 5) { // 5xx errors observer.downloadErrored(url, "Retriable status code " + statusCode + " while downloading " + url.toExternalForm()); // Throw exception so download can be retried throw new IOException("Retriable status code " + statusCode); } if (huc.getContentLength() == 503 && urlToDownload.getHost().endsWith("imgur.com")) { // Imgur image with 503 bytes is "404" logger.error("[!] Imgur image is 404 (503 bytes long): " + url); observer.downloadErrored(url, "Imgur image is 404: " + url.toExternalForm()); return; } // If the ripper is using the bytes progress bar set bytesTotal to huc.getContentLength() if (observer.useByteProgessBar()) { bytesTotal = huc.getContentLength(); observer.setBytesTotal(bytesTotal); observer.sendUpdate(STATUS.TOTAL_BYTES, bytesTotal); logger.debug("Size of file at " + this.url + " = " + bytesTotal + "b"); } // Save file bis = new BufferedInputStream(huc.getInputStream()); // Check if we should get the file ext from the MIME type if (getFileExtFromMIME) { String fileExt = URLConnection.guessContentTypeFromStream(bis); if (fileExt != null) { fileExt = fileExt.replaceAll("image/", ""); saveAs = new File(saveAs.toString() + "." + fileExt); } else { logger.error("Was unable to get content type from stream"); // Try to get the file type from the magic number byte[] magicBytes = new byte[8]; bis.read(magicBytes,0, 5); bis.reset(); fileExt = Utils.getEXTFromMagic(magicBytes); if (fileExt != null) { saveAs = new File(saveAs.toString() + "." + fileExt); } else { logger.error("Was unable to get content type using magic number"); logger.error("Magic number was: " + Arrays.toString(magicBytes)); } } } // If we're resuming a download we append data to the existing file if (statusCode == 206) { fos = new FileOutputStream(saveAs, true); } else { fos = new FileOutputStream(saveAs); } byte[] data = new byte[1024 * 256]; int bytesRead; while ( (bytesRead = bis.read(data)) != -1) { try { observer.stopCheck(); } catch (IOException e) { observer.downloadErrored(url, "Download interrupted"); return; } fos.write(data, 0, bytesRead); if (observer.useByteProgessBar()) { bytesDownloaded += bytesRead; observer.setBytesCompleted(bytesDownloaded); observer.sendUpdate(STATUS.COMPLETED_BYTES, bytesDownloaded); } } bis.close(); fos.close(); break; // Download successful: break out of infinite loop } catch (HttpStatusException hse) { logger.debug("HTTP status exception", hse); logger.error("[!] HTTP status " + hse.getStatusCode() + " while downloading from " + urlToDownload); if (hse.getStatusCode() == 404 && Utils.getConfigBoolean("errors.skip404", false)) { observer.downloadErrored(url, "HTTP status code " + hse.getStatusCode() + " while downloading " + url.toExternalForm()); return; } } catch (IOException e) { logger.debug("IOException", e); logger.error("[!] Exception while downloading file: " + url + " - " + e.getMessage()); } finally { // Close any open streams try { if (bis != null) { bis.close(); } } catch (IOException e) { } try { if (fos != null) { fos.close(); } } catch (IOException e) { } } if (tries > this.retries) { logger.error("[!] Exceeded maximum retries (" + this.retries + ") for URL " + url); observer.downloadErrored(url, "Failed to download " + url.toExternalForm()); return; } } while (true); observer.downloadCompleted(url, saveAs); logger.info("[+] Saved " + url + " as " + this.prettySaveAs); } #location 108 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void downloadErrored(URL url, String reason) { if (observer == null) { return; } itemsPending.remove(url); itemsErrored.put(url, reason); observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_ERRORED, url + " : " + reason)); checkIfComplete(); }
#vulnerable code public void downloadErrored(URL url, String reason) { if (observer == null) { return; } synchronized(observer) { itemsPending.remove(url); itemsErrored.put(url, reason); observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_ERRORED, url + " : " + reason)); observer.notifyAll(); checkIfComplete(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test void testKeyCount() { ResourceBundle defaultBundle = Utils.getResourceBundle(null); HashMap<String, ArrayList<String>> dictionary = new HashMap<>(); for (String lang : Utils.getSupportedLanguages()) { ResourceBundle.clearCache(); if (lang.equals(DEFAULT_LANG)) continue; ResourceBundle selectedLang = Utils.getResourceBundle(lang); for (final Enumeration<String> keys = defaultBundle.getKeys(); keys.hasMoreElements();) { String element = keys.nextElement(); if (selectedLang.containsKey(element) && !selectedLang.getString(element).equals(defaultBundle.getString(element))) { if (dictionary.get(lang) == null) dictionary.put(lang, new ArrayList<>()); dictionary.get(lang).add(element); } } } dictionary.keySet().forEach(d -> { logger.warn(String.format("Keys missing in %s", d)); dictionary.get(d).forEach(v -> logger.warn(v)); logger.warn("\n"); }); }
#vulnerable code @Test void testKeyCount() { ((ConsoleAppender) Logger.getRootLogger().getAppender("stdout")).setThreshold(Level.DEBUG); File f = new File("E:\\Downloads\\_Isaaku\\dev\\ripme-1.7.86-jar-with-dependencies.jar"); File[] files = f.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { logger.info("name: " + name); return name.startsWith("LabelsBundle_"); } }); for (String s : getResourcesNames("\\**")) { logger.info(s); } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String[] getDescription(String url,Document page) { if (isThisATest()) { return null; } try { // Fetch the image page Response resp = Http.url(url) .referrer(this.url) .cookies(cookies) .response(); cookies.putAll(resp.cookies()); // Try to find the description Document documentz = resp.parse(); Element ele = documentz.select("div.dev-description").first(); if (ele == null) { throw new IOException("No description found"); } documentz.outputSettings(new Document.OutputSettings().prettyPrint(false)); ele.select("br").append("\\n"); ele.select("p").prepend("\\n\\n"); String fullSize = null; Element thumb = page.select("div.zones-container span.thumb[href=\"" + url + "\"]").get(0); if (!thumb.attr("data-super-full-img").isEmpty()) { fullSize = thumb.attr("data-super-full-img"); String[] split = fullSize.split("/"); fullSize = split[split.length - 1]; } else { String spanUrl = thumb.attr("href"); fullSize = jsonToImage(page,spanUrl.substring(spanUrl.lastIndexOf('-') + 1)); if (fullSize != null) { String[] split = fullSize.split("/"); fullSize = split[split.length - 1]; } } if (fullSize == null) { return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false))}; } fullSize = fullSize.substring(0, fullSize.lastIndexOf(".")); return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)),fullSize}; // TODO Make this not make a newline if someone just types \n into the description. } catch (IOException ioe) { logger.info("Failed to get description at " + url + ": '" + ioe.getMessage() + "'"); return null; } }
#vulnerable code @Override public String[] getDescription(String url,Document page) { if (isThisATest()) { return null; } try { // Fetch the image page Response resp = Http.url(url) .referrer(this.url) .cookies(cookies) .response(); cookies.putAll(resp.cookies()); // Try to find the description Elements els = resp.parse().select("div[class=dev-description]"); if (els.size() == 0) { throw new IOException("No description found"); } Document documentz = resp.parse(); Element ele = documentz.select("div[class=dev-description]").get(0); documentz.outputSettings(new Document.OutputSettings().prettyPrint(false)); ele.select("br").append("\\n"); ele.select("p").prepend("\\n\\n"); String fullSize = null; Element thumb = page.select("div.zones-container span.thumb[href=\"" + url + "\"]").get(0); if (!thumb.attr("data-super-full-img").isEmpty()) { fullSize = thumb.attr("data-super-full-img"); String[] split = fullSize.split("/"); fullSize = split[split.length - 1]; } else { String spanUrl = thumb.attr("href"); fullSize = jsonToImage(page,spanUrl.substring(spanUrl.lastIndexOf('-') + 1)); String[] split = fullSize.split("/"); fullSize = split[split.length - 1]; } if (fullSize == null) { return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false))}; } fullSize = fullSize.substring(0, fullSize.lastIndexOf(".")); return new String[] {Jsoup.clean(ele.html().replaceAll("\\\\n", System.getProperty("line.separator")), "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)),fullSize}; // TODO Make this not make a newline if someone just types \n into the description. } catch (IOException ioe) { logger.info("Failed to get description " + page + " : '" + ioe.getMessage() + "'"); return null; } } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void sendUpdate(STATUS status, Object message) { if (observer == null) { return; } observer.update(this, new RipStatusMessage(status, message)); }
#vulnerable code public void sendUpdate(STATUS status, Object message) { if (observer == null) { return; } synchronized (observer) { observer.update(this, new RipStatusMessage(status, message)); observer.notifyAll(); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void downloadCompleted(URL url, File saveAs) { if (observer == null) { return; } try { String path = Utils.removeCWD(saveAs); RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, path); itemsPending.remove(url); itemsCompleted.put(url, saveAs); observer.update(this, msg); checkIfComplete(); } catch (Exception e) { logger.error("Exception while updating observer: ", e); } }
#vulnerable code public void downloadCompleted(URL url, File saveAs) { if (observer == null) { return; } try { String path = Utils.removeCWD(saveAs); RipStatusMessage msg = new RipStatusMessage(STATUS.DOWNLOAD_COMPLETE, path); synchronized(observer) { itemsPending.remove(url); itemsCompleted.put(url, saveAs); observer.update(this, msg); observer.notifyAll(); checkIfComplete(); } } catch (Exception e) { logger.error("Exception while updating observer: ", e); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static File getJarDirectory() { return Utils.class.getResource("/rip.properties").toString().contains("jar:") ? new File(System.getProperty("java.class.path")).getParentFile() : new File(System.getProperty("user.dir")); }
#vulnerable code private static File getJarDirectory() { String[] classPath = System.getProperty("java.class.path").split(";"); return classPath.length > 1 ? new File(System.getProperty("user.dir")) : new File(classPath[0]).getParentFile(); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<>(); if (theme1.contains(getHost())) { Element elem = doc.select("div.comic-table > div#comic > a > img").first(); // If doc is the last page in the comic then elem.attr("src") returns null // because there is no link <a> to the next page if (elem == null) { elem = doc.select("div.comic-table > div#comic > img").first(); } // Check if this is a site where we can get the page number from the title if (url.toExternalForm().contains("buttsmithy.com")) { // Set the page title pageTitle = doc.select("meta[property=og:title]").attr("content"); pageTitle = pageTitle.replace(" ", ""); pageTitle = pageTitle.replace("P", "p"); } if (url.toExternalForm().contains("www.totempole666.com")) { String postDate = doc.select("span.post-date").first().text().replaceAll("/", "_"); String postTitle = doc.select("h2.post-title").first().text().replaceAll("#", ""); pageTitle = postDate + "_" + postTitle; } if (url.toExternalForm().contains("themonsterunderthebed.net")) { pageTitle = doc.select("title").first().text().replaceAll("#", ""); pageTitle = pageTitle.replace("“", ""); pageTitle = pageTitle.replace("”", ""); pageTitle = pageTitle.replace("The Monster Under the Bed", ""); pageTitle = pageTitle.replace("–", ""); pageTitle = pageTitle.replace(",", ""); pageTitle = pageTitle.replace(" ", ""); } result.add(elem.attr("src")); } // freeadultcomix gets it own if because it needs to add http://freeadultcomix.com to the start of each link // TODO review the above comment which no longer applies -- see if there's a refactoring we should do here. if (url.toExternalForm().contains("freeadultcomix.com")) { for (Element elem : doc.select("div.single-post > p > img.aligncenter")) { result.add(elem.attr("src")); } } if (url.toExternalForm().contains("comics-xxx.com")) { for (Element elem : doc.select("div.single-post > center > p > img")) { result.add(elem.attr("src")); } } if (url.toExternalForm().contains("shipinbottle.pepsaga.com")) { for (Element elem : doc.select("div#comic > div.comicpane > a > img")) { result.add(elem.attr("src")); } } if (url.toExternalForm().contains("8muses.download")) { for (Element elem : doc.select("div.popup-gallery > figure > a")) { result.add(elem.attr("href")); } } return result; }
#vulnerable code @Override public List<String> getURLsFromPage(Document doc) { List<String> result = new ArrayList<>(); if (getHost().contains("www.totempole666.com") || getHost().contains("buttsmithy.com") || getHost().contains("themonsterunderthebed.net") || getHost().contains("prismblush.com") || getHost().contains("www.konradokonski.com") || getHost().contains("thisis.delvecomic.com") || getHost().contains("tnbtu.com")) { Element elem = doc.select("div.comic-table > div#comic > a > img").first(); // If doc is the last page in the comic then elem.attr("src") returns null // because there is no link <a> to the next page if (elem == null) { elem = doc.select("div.comic-table > div#comic > img").first(); } // Check if this is a site where we can get the page number from the title if (url.toExternalForm().contains("buttsmithy.com")) { // Set the page title pageTitle = doc.select("meta[property=og:title]").attr("content"); pageTitle = pageTitle.replace(" ", ""); pageTitle = pageTitle.replace("P", "p"); } if (url.toExternalForm().contains("www.totempole666.com")) { String postDate = doc.select("span.post-date").first().text().replaceAll("/", "_"); String postTitle = doc.select("h2.post-title").first().text().replaceAll("#", ""); pageTitle = postDate + "_" + postTitle; } if (url.toExternalForm().contains("themonsterunderthebed.net")) { pageTitle = doc.select("title").first().text().replaceAll("#", ""); pageTitle = pageTitle.replace("“", ""); pageTitle = pageTitle.replace("”", ""); pageTitle = pageTitle.replace("The Monster Under the Bed", ""); pageTitle = pageTitle.replace("–", ""); pageTitle = pageTitle.replace(",", ""); pageTitle = pageTitle.replace(" ", ""); } result.add(elem.attr("src")); } // freeadultcomix gets it own if because it needs to add http://freeadultcomix.com to the start of each link // TODO review the above comment which no longer applies -- see if there's a refactoring we should do here. if (url.toExternalForm().contains("freeadultcomix.com")) { for (Element elem : doc.select("div.single-post > p > img.aligncenter")) { result.add(elem.attr("src")); } } if (url.toExternalForm().contains("comics-xxx.com")) { for (Element elem : doc.select("div.single-post > center > p > img")) { result.add(elem.attr("src")); } } if (url.toExternalForm().contains("shipinbottle.pepsaga.com")) { for (Element elem : doc.select("div#comic > div.comicpane > a > img")) { result.add(elem.attr("src")); } } if (url.toExternalForm().contains("8muses.download")) { for (Element elem : doc.select("div.popup-gallery > figure > a")) { result.add(elem.attr("href")); } } return result; } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void downloadProblem(URL url, String message) { if (observer == null) { return; } itemsPending.remove(url); itemsErrored.put(url, message); observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message)); checkIfComplete(); }
#vulnerable code public void downloadProblem(URL url, String message) { if (observer == null) { return; } synchronized(observer) { itemsPending.remove(url); itemsErrored.put(url, message); observer.update(this, new RipStatusMessage(STATUS.DOWNLOAD_WARN, url + " : " + message)); observer.notifyAll(); } checkIfComplete(); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void login() throws IOException { String customUsername = Utils.getConfigString("DeviantartCustomLoginUsername", this.username); String customPassword = Utils.getConfigString("DeviantartCustomLoginPassword", this.password); try { String dACookies = Utils.getConfigString(utilsKey, null); updateCookie(dACookies != null ? deserialize(dACookies) : null); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (getDACookie() == null || !checkLogin()) { LOGGER.info("Do Login now"); // Do login now // Load login page Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET) .referrer(referer).userAgent(userAgent).execute(); updateCookie(res.cookies()); // Find tokens Document doc = res.parse(); Element form = doc.getElementById("login"); String token = form.select("input[name=\"validate_token\"]").first().attr("value"); String key = form.select("input[name=\"validate_key\"]").first().attr("value"); LOGGER.info("Token: " + token + " & Key: " + key); // Build Login Data HashMap<String, String> loginData = new HashMap<String, String>(); loginData.put("challenge", ""); loginData.put("username", customUsername); loginData.put("password", customPassword); loginData.put("remember_me", "1"); loginData.put("validate_token", token); loginData.put("validate_key", key); Map<String, String> cookies = res.cookies(); // Log in using data. Handle redirect res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent) .method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute(); updateCookie(res.cookies()); res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent) .method(Method.GET).cookies(cookies).followRedirects(false).execute(); // Store cookies updateCookie(res.cookies()); // Write Cookie to file for other RipMe Instances or later use Utils.setConfigString(utilsKey, serialize(new HashMap<String, String>(getDACookie()))); Utils.saveConfig(); // save now because of other instances that might work simultaneously }else { LOGGER.info("No new Login needed"); } LOGGER.info("DA Cookies: " + getDACookie()); }
#vulnerable code private void login() throws IOException { try { String dACookies = Utils.getConfigString(utilsKey, null); updateCookie(dACookies != null ? deserialize(dACookies) : null); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (getDACookie() == null || !checkLogin()) { LOGGER.info("Do Login now"); // Do login now // Load login page Response res = Http.url("https://www.deviantart.com/users/login").connection().method(Method.GET) .referrer(referer).userAgent(userAgent).execute(); updateCookie(res.cookies()); // Find tokens Document doc = res.parse(); Element form = doc.getElementById("login"); String token = form.select("input[name=\"validate_token\"]").first().attr("value"); String key = form.select("input[name=\"validate_key\"]").first().attr("value"); LOGGER.info("Token: " + token + " & Key: " + key); // Build Login Data HashMap<String, String> loginData = new HashMap<String, String>(); loginData.put("challenge", ""); loginData.put("username", this.username); loginData.put("password", this.password); loginData.put("remember_me", "1"); loginData.put("validate_token", token); loginData.put("validate_key", key); Map<String, String> cookies = res.cookies(); // Log in using data. Handle redirect res = Http.url("https://www.deviantart.com/users/login").connection().referrer(referer).userAgent(userAgent) .method(Method.POST).data(loginData).cookies(cookies).followRedirects(false).execute(); updateCookie(res.cookies()); res = Http.url(res.header("location")).connection().referrer(referer).userAgent(userAgent) .method(Method.GET).cookies(cookies).followRedirects(false).execute(); // Store cookies updateCookie(res.cookies()); // Write Cookie to file for other RipMe Instances or later use Utils.setConfigString(utilsKey, serialize(new HashMap<String, String>(getDACookie()))); Utils.saveConfig(); // save now because of other instances that might work simultaneously }else { LOGGER.info("No new Login needed"); } LOGGER.info("DA Cookies: " + getDACookie()); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void replyToStatus(String content, String replyTo) throws ArchivedGroupException, ReplyStatusException { AbstractStatus abstractStatus = statusRepository.findStatusById(replyTo); if (abstractStatus != null && !abstractStatus.getType().equals(StatusType.STATUS) && !abstractStatus.getType().equals(StatusType.SHARE)) { log.debug("Can not reply to a status of this type"); throw new ReplyStatusException(); } if (abstractStatus != null && abstractStatus.getType().equals(StatusType.SHARE)) { log.debug("Replacing the share by the original status"); Share share = (Share) abstractStatus; AbstractStatus abstractRealStatus = statusRepository.findStatusById(share.getOriginalStatusId()); abstractStatus = abstractRealStatus; } Status status = (Status) abstractStatus; Group group = null; if (status.getGroupId() != null) { group = groupService.getGroupById(status.getDomain(), status.getGroupId()); if (group.isArchivedGroup()) { throw new ArchivedGroupException(); } } if (!status.getReplyTo().equals("")) { log.debug("Replacing the status by the status at the origin of the disucssion"); // Original status is also a reply, replying to the real original status instead AbstractStatus abstractRealOriginalStatus = statusRepository.findStatusById(status.getDiscussionId()); if (abstractRealOriginalStatus == null || !abstractRealOriginalStatus.getType().equals(StatusType.STATUS)) { throw new ReplyStatusException(); } Status realOriginalStatus = (Status) abstractRealOriginalStatus; Status replyStatus = createStatus( content, realOriginalStatus.getStatusPrivate(), group, realOriginalStatus.getStatusId(), status.getStatusId(), status.getUsername()); discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId()); } else { log.debug("Replying directly to the status at the origin of the disucssion"); // The original status of the discussion is the one we reply to Status replyStatus = createStatus(content, status.getStatusPrivate(), group, status.getStatusId(), status.getStatusId(), status.getUsername()); discussionRepository.addReplyToDiscussion(status.getStatusId(), replyStatus.getStatusId()); } }
#vulnerable code public void replyToStatus(String content, String replyTo) throws ArchivedGroupException, ReplyStatusException { AbstractStatus abstractOriginalStatus = statusRepository.findStatusById(replyTo); if (abstractOriginalStatus != null && !abstractOriginalStatus.getType().equals(StatusType.STATUS) && !abstractOriginalStatus.getType().equals(StatusType.SHARE)) { log.debug("Can not reply to a status of this type"); throw new ReplyStatusException(); } if (abstractOriginalStatus != null && abstractOriginalStatus.getType().equals(StatusType.SHARE)) { Share share = (Share) abstractOriginalStatus; AbstractStatus abstractRealOriginalStatus = statusRepository.findStatusById(share.getOriginalStatusId()); abstractOriginalStatus = abstractRealOriginalStatus; } Status originalStatus = (Status) abstractOriginalStatus; Group group = null; if (originalStatus.getGroupId() != null) { group = groupService.getGroupById(originalStatus.getDomain(), originalStatus.getGroupId()); if (group.isArchivedGroup()) { throw new ArchivedGroupException(); } } if (!originalStatus.getReplyTo().equals("")) { // Original status is also a reply, replying to the real original status instead AbstractStatus abstractRealOriginalStatus = statusRepository.findStatusById(originalStatus.getDiscussionId()); if (abstractRealOriginalStatus == null || !abstractRealOriginalStatus.getType().equals(StatusType.STATUS)) { throw new ReplyStatusException(); } Status realOriginalStatus = (Status) abstractRealOriginalStatus; Status replyStatus = createStatus( content, realOriginalStatus.getStatusPrivate(), group, realOriginalStatus.getStatusId(), originalStatus.getStatusId(), originalStatus.getUsername()); discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId()); } else { // The original status of the discussion is the one we reply to Status replyStatus = createStatus(content, originalStatus.getStatusPrivate(), group, replyTo, replyTo, originalStatus.getUsername()); discussionRepository.addReplyToDiscussion(originalStatus.getStatusId(), replyStatus.getStatusId()); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override @Cacheable("attachment-cache") public Attachment findAttachmentById(String attachmentId) { if (attachmentId == null) { return null; } if (log.isDebugEnabled()) { log.debug("Finding attachment : " + attachmentId); } Attachment attachment = this.findAttachmentMetadataById(attachmentId); if (attachment == null) { return null; } ColumnQuery<String, String, byte[]> queryAttachment = HFactory.createColumnQuery(keyspaceOperator, StringSerializer.get(), StringSerializer.get(), BytesArraySerializer.get()); HColumn<String, byte[]> columnAttachment = queryAttachment.setColumnFamily(ATTACHMENT_CF) .setKey(attachmentId) .setName(CONTENT) .execute() .get(); attachment.setContent(columnAttachment.getValue()); return attachment; }
#vulnerable code @Override @Cacheable("attachment-cache") public Attachment findAttachmentById(String attachmentId) { if (attachmentId == null) { return null; } if (log.isDebugEnabled()) { log.debug("Finding attachment : " + attachmentId); } Attachment attachment = this.findAttachmentMetadataById(attachmentId); ColumnQuery<String, String, byte[]> queryAttachment = HFactory.createColumnQuery(keyspaceOperator, StringSerializer.get(), StringSerializer.get(), BytesArraySerializer.get()); HColumn<String, byte[]> columnAttachment = queryAttachment.setColumnFamily(ATTACHMENT_CF) .setKey(attachmentId) .setName(CONTENT) .execute() .get(); attachment.setContent(columnAttachment.getValue()); return attachment; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @RequestMapping(value = "/rest/statuses/{statusId}", method = RequestMethod.PATCH) @ResponseBody public StatusDTO updateStatusV3(@RequestBody ActionStatus action, @PathVariable("statusId") String statusId) { try { StatusDTO status = timelineService.getStatus(statusId); if(action.isFavorite() != null && status.isFavorite() != action.isFavorite()){ if(action.isFavorite()){ timelineService.addFavoriteStatus(statusId); } else { timelineService.removeFavoriteStatus(statusId); } status.setFavorite(action.isFavorite()); } if(action.isShared() != null && action.isShared()){ timelineService.shareStatus(statusId); } if(action.isAnnounced() != null && action.isAnnounced()){ timelineService.announceStatus(statusId); } return status; } catch (Exception e) { if (log.isDebugEnabled()) { e.printStackTrace(); } return null; } }
#vulnerable code @RequestMapping(value = "/rest/statuses/{statusId}", method = RequestMethod.PATCH) @ResponseBody public StatusDTO updateStatusV3(@RequestBody ActionStatus action, @PathVariable("statusId") String statusId) { try { StatusDTO status = timelineService.getStatus(statusId); if(action.isFavorite() != null && status.isFavorite() != action.isFavorite()){ if(action.isFavorite()){ timelineService.addFavoriteStatus(statusId); } else { timelineService.removeFavoriteStatus(statusId); } status.setFavorite(action.isFavorite()); } if(action.isShared() != null && action.isShared()){ timelineService.shareStatus(statusId); } return status; } catch (Exception e) { if (log.isDebugEnabled()) { e.printStackTrace(); } return null; } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void replyToStatus(String content, String replyTo) throws ArchivedGroupException { Status originalStatus = statusRepository.findStatusById(replyTo); Group group = null; if (originalStatus.getGroupId() != null) { group = groupService.getGroupById(originalStatus.getDomain(), originalStatus.getGroupId()); if (group.isArchivedGroup()) { throw new ArchivedGroupException(); } } if (!originalStatus.getReplyTo().equals("")) { // Original status is also a reply, replying to the real original status instead Status realOriginalStatus = statusRepository.findStatusById(originalStatus.getDiscussionId()); Status replyStatus = createStatus( content, realOriginalStatus.getStatusPrivate(), group, realOriginalStatus.getStatusId(), originalStatus.getStatusId(), originalStatus.getUsername()); discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId()); } else { // The original status of the discussion is the one we reply to Status replyStatus = createStatus(content, originalStatus.getStatusPrivate(), group, replyTo, replyTo, originalStatus.getUsername()); discussionRepository.addReplyToDiscussion(originalStatus.getStatusId(), replyStatus.getStatusId()); } }
#vulnerable code public void replyToStatus(String content, String replyTo) throws ArchivedGroupException { Status originalStatus = statusRepository.findStatusById(replyTo); Group group = null; if (originalStatus.getGroupId() != null) { group = groupService.getGroupById(originalStatus.getDomain(), originalStatus.getGroupId()); } if (group.isArchivedGroup()) { throw new ArchivedGroupException(); } if (!originalStatus.getReplyTo().equals("")) { // Original status is also a reply, replying to the real original status instead Status realOriginalStatus = statusRepository.findStatusById(originalStatus.getDiscussionId()); Status replyStatus = createStatus( content, realOriginalStatus.getStatusPrivate(), group, realOriginalStatus.getStatusId(), originalStatus.getStatusId(), originalStatus.getUsername()); discussionRepository.addReplyToDiscussion(realOriginalStatus.getStatusId(), replyStatus.getStatusId()); } else { // The original status of the discussion is the one we reply to Status replyStatus = createStatus(content, originalStatus.getStatusPrivate(), group, replyTo, replyTo, originalStatus.getUsername()); discussionRepository.addReplyToDiscussion(originalStatus.getStatusId(), replyStatus.getStatusId()); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { _factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = _factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); }
#vulnerable code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = this.blockWhenExhausted; boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { _factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = _factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException { Map toDestroy = new HashMap(); final KeyedPoolableObjectFactory oldFactory = _factory; synchronized (this) { assertOpen(); if (0 < getNumActive()) { throw new IllegalStateException("Objects are already active"); } else { for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { Object key = it.next(); ObjectQueue pool = (ObjectQueue)_poolMap.get(key); if (pool != null) { // Copy objects to new list so pool.queue can be cleared // inside the sync List objects = new ArrayList(); objects.addAll(pool.queue); toDestroy.put(key, objects); it.remove(); _poolList.remove(key); _totalIdle = _totalIdle - pool.queue.size(); _totalInternalProcessing = _totalInternalProcessing + pool.queue.size(); pool.queue.clear(); } } _factory = factory; } } destroy(toDestroy, oldFactory); }
#vulnerable code public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException { Map toDestroy = new HashMap(); synchronized (this) { assertOpen(); if (0 < getNumActive()) { throw new IllegalStateException("Objects are already active"); } else { for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { Object key = it.next(); ObjectQueue pool = (ObjectQueue)_poolMap.get(key); if (pool != null) { // Copy objects to new list so pool.queue can be cleared // inside the sync List objects = new ArrayList(); objects.addAll(pool.queue); toDestroy.put(key, objects); it.remove(); _poolList.remove(key); _totalIdle = _totalIdle - pool.queue.size(); _totalInternalProcessing = _totalInternalProcessing + pool.queue.size(); pool.queue.clear(); } } _factory = factory; } } destroy(toDestroy); } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(); byte whenExhaustedAction; long maxWait; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution whenExhaustedAction = _whenExhaustedAction; maxWait = _maxWait; // Add this request to the queue _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated from the pool above if(latch._pair == null) { // check if we were allowed to create one if(latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if(null == latch._pair) { try { Object obj = _factory.makeObject(); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { _numInternalProcessing--; // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(latch._pair.value); if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized(this) { _numInternalProcessing--; _numActive++; } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { _numInternalProcessing--; latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
#vulnerable code public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(); synchronized (this) { _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated from the pool above if(latch._pair == null) { // check if we were allowed to create one if(latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(_maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if(null == latch._pair) { try { Object obj = _factory.makeObject(); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { _numInternalProcessing--; // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(latch._pair.value); if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized(this) { _numInternalProcessing--; _numActive++; } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { _numInternalProcessing--; latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } } #location 56 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object borrowObject(Object key) throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(key); byte whenExhaustedAction; long maxWait; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution whenExhaustedAction = _whenExhaustedAction; maxWait = _maxWait; // Add this request to the queue _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated if (null == latch._pair) { // Check to see if we were allowed to create one if (latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if (null == latch._pair) { try { Object obj = _factory.makeObject(key); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { latch._pool.decrementInternalProcessingCount(); // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(key, latch._pair.value); if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch._pool.incrementActiveCount(); } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(key, latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException( "Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
#vulnerable code public Object borrowObject(Object key) throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(key); synchronized (this) { _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated if (null == latch._pair) { // Check to see if we were allowed to create one if (latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(_maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if (null == latch._pair) { try { Object obj = _factory.makeObject(key); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { latch._pool.decrementInternalProcessingCount(); // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(key, latch._pair.value); if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch._pool.incrementActiveCount(); } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(key, latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException( "Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } } #location 55 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addObject(Object key) throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } Object obj = _factory.makeObject(key); try { assertOpen(); addObjectToPool(key, obj, false); } catch (IllegalStateException ex) { // Pool closed try { _factory.destroyObject(key, obj); } catch (Exception ex2) { // swallow } throw ex; } }
#vulnerable code public void addObject(Object key) throws Exception { assertOpen(); if (_factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } Object obj = _factory.makeObject(key); synchronized (this) { try { assertOpen(); addObjectToPool(key, obj, false); } catch (IllegalStateException ex) { // Pool closed try { _factory.destroyObject(key, obj); } catch (Exception ex2) { // swallow } throw ex; } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clear(Object key) { Map toDestroy = new HashMap(); final ObjectQueue pool; synchronized (this) { pool = (ObjectQueue)(_poolMap.remove(key)); if (pool == null) { return; } else { _poolList.remove(key); } // Copy objects to new list so pool.queue can be cleared inside // the sync List objects = new ArrayList(); objects.addAll(pool.queue); toDestroy.put(key, objects); _totalIdle = _totalIdle - pool.queue.size(); _totalInternalProcessing = _totalInternalProcessing + pool.queue.size(); pool.queue.clear(); } destroy(toDestroy, _factory); }
#vulnerable code public void clear(Object key) { Map toDestroy = new HashMap(); final ObjectQueue pool; synchronized (this) { pool = (ObjectQueue)(_poolMap.remove(key)); if (pool == null) { return; } else { _poolList.remove(key); } // Copy objects to new list so pool.queue can be cleared inside // the sync List objects = new ArrayList(); objects.addAll(pool.queue); toDestroy.put(key, objects); _totalIdle = _totalIdle - pool.queue.size(); _totalInternalProcessing = _totalInternalProcessing + pool.queue.size(); pool.queue.clear(); } destroy(toDestroy); } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object borrowObject(Object key) throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(key); byte whenExhaustedAction; long maxWait; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution whenExhaustedAction = _whenExhaustedAction; maxWait = _maxWait; // Add this request to the queue _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated if (null == latch._pair) { // Check to see if we were allowed to create one if (latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if (null == latch._pair) { try { Object obj = _factory.makeObject(key); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { latch._pool.decrementInternalProcessingCount(); // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(key, latch._pair.value); if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch._pool.incrementActiveCount(); } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(key, latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException( "Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
#vulnerable code public Object borrowObject(Object key) throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(key); synchronized (this) { _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated if (null == latch._pair) { // Check to see if we were allowed to create one if (latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(_maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("whenExhaustedAction " + _whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if (null == latch._pair) { try { Object obj = _factory.makeObject(key); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { latch._pool.decrementInternalProcessingCount(); // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(key, latch._pair.value); if (_testOnBorrow && !_factory.validateObject(key, latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch._pool.incrementActiveCount(); } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(key, latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { latch._pool.decrementInternalProcessingCount(); latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException( "Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clearOldest() { // Map of objects to destroy my key final Map toDestroy = new HashMap(); // build sorted map of idle objects final Map map = new TreeMap(); synchronized (this) { for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { final Object key = keyiter.next(); final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue; for (Iterator it = list.iterator(); it.hasNext();) { // each item into the map uses the objectimestamppair object // as the key. It then gets sorted based on the timstamp field // each value in the map is the parent list it belongs in. map.put(it.next(), key); } } // Now iterate created map and kill the first 15% plus one to account for zero Set setPairKeys = map.entrySet(); int itemsToRemove = ((int) (map.size() * 0.15)) + 1; Iterator iter = setPairKeys.iterator(); while (iter.hasNext() && itemsToRemove > 0) { Map.Entry entry = (Map.Entry) iter.next(); // kind of backwards on naming. In the map, each key is the objecttimestamppair // because it has the ordering with the timestamp value. Each value that the // key references is the key of the list it belongs to. Object key = entry.getValue(); ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); final CursorableLinkedList list = ((ObjectQueue)(_poolMap.get(key))).queue; list.remove(pairTimeStamp); if (toDestroy.containsKey(key)) { ((List)toDestroy.get(key)).add(pairTimeStamp); } else { List listForKey = new ArrayList(); listForKey.add(pairTimeStamp); toDestroy.put(key, listForKey); } // if that was the last object for that key, drop that pool if (list.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } _totalIdle--; _totalInternalProcessing++; itemsToRemove--; } } destroy(toDestroy, _factory); }
#vulnerable code public void clearOldest() { // Map of objects to destroy my key final Map toDestroy = new HashMap(); // build sorted map of idle objects final Map map = new TreeMap(); synchronized (this) { for (Iterator keyiter = _poolMap.keySet().iterator(); keyiter.hasNext();) { final Object key = keyiter.next(); final CursorableLinkedList list = ((ObjectQueue)_poolMap.get(key)).queue; for (Iterator it = list.iterator(); it.hasNext();) { // each item into the map uses the objectimestamppair object // as the key. It then gets sorted based on the timstamp field // each value in the map is the parent list it belongs in. map.put(it.next(), key); } } // Now iterate created map and kill the first 15% plus one to account for zero Set setPairKeys = map.entrySet(); int itemsToRemove = ((int) (map.size() * 0.15)) + 1; Iterator iter = setPairKeys.iterator(); while (iter.hasNext() && itemsToRemove > 0) { Map.Entry entry = (Map.Entry) iter.next(); // kind of backwards on naming. In the map, each key is the objecttimestamppair // because it has the ordering with the timestamp value. Each value that the // key references is the key of the list it belongs to. Object key = entry.getValue(); ObjectTimestampPair pairTimeStamp = (ObjectTimestampPair) entry.getKey(); final CursorableLinkedList list = ((ObjectQueue)(_poolMap.get(key))).queue; list.remove(pairTimeStamp); if (toDestroy.containsKey(key)) { ((List)toDestroy.get(key)).add(pairTimeStamp); } else { List listForKey = new ArrayList(); listForKey.add(pairTimeStamp); toDestroy.put(key, listForKey); } // if that was the last object for that key, drop that pool if (list.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } _totalIdle--; _totalInternalProcessing++; itemsToRemove--; } } destroy(toDestroy); } #location 53 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clear() { List toDestroy = new ArrayList(); synchronized(this) { toDestroy.addAll(_pool); _numInternalProcessing = _numInternalProcessing + _pool._size; _pool.clear(); } destroy(toDestroy, _factory); }
#vulnerable code public void clear() { List toDestroy = new ArrayList(); synchronized(this) { toDestroy.addAll(_pool); _numInternalProcessing = _numInternalProcessing + _pool._size; _pool.clear(); } destroy(toDestroy); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } synchronized (evictionLock) { boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } }
#vulnerable code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); }
#vulnerable code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { _factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = _factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { assertOpen(); if (_pool.size() == 0) { return; } PooledObject<T> underTest = null; for (int i = 0, m = getNumTests(); i < m; i++) { if (_evictionIterator == null || !_evictionIterator.hasNext()) { if (getLifo()) { _evictionIterator = _pool.descendingIterator(); } else { _evictionIterator = _pool.iterator(); } } if (!_evictionIterator.hasNext()) { // Pool exhausted, nothing to do here return; } else { try { underTest = _evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; _evictionIterator = null; continue; } } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (getMinEvictableIdleTimeMillis() > 0 && getMinEvictableIdleTimeMillis() < underTest.getIdleTimeMillis() || (getSoftMinEvictableIdleTimeMillis() > 0 && getSoftMinEvictableIdleTimeMillis() < underTest.getIdleTimeMillis() && getMinIdle() < _pool.size())) { destroy(underTest); } else { if (getTestWhileIdle()) { boolean active = false; try { _factory.activateObject(underTest.getObject()); active = true; } catch(Exception e) { destroy(underTest); } if(active) { if(!_factory.validateObject(underTest.getObject())) { destroy(underTest); } else { try { _factory.passivateObject(underTest.getObject()); } catch(Exception e) { destroy(underTest); } } } } if (!underTest.endEvictionTest()) { // TODO - May need to add code here once additional states // are used } } } return; }
#vulnerable code public void evict() throws Exception { assertOpen(); synchronized (this) { if(_pool.isEmpty()) { return; } if (null == _evictionCursor) { _evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0)); } } for (int i=0,m=getNumTests();i<m;i++) { final ObjectTimestampPair<T> pair; synchronized (this) { if ((_lifo && !_evictionCursor.hasPrevious()) || !_lifo && !_evictionCursor.hasNext()) { _evictionCursor.close(); _evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0); } pair = _lifo ? _evictionCursor.previous() : _evictionCursor.next(); _evictionCursor.remove(); _numInternalProcessing++; } boolean removeObject = false; final long idleTimeMilis = System.currentTimeMillis() - pair.getTstamp(); if ((getMinEvictableIdleTimeMillis() > 0) && (idleTimeMilis > getMinEvictableIdleTimeMillis())) { removeObject = true; } else if ((getSoftMinEvictableIdleTimeMillis() > 0) && (idleTimeMilis > getSoftMinEvictableIdleTimeMillis()) && ((getNumIdle() + 1)> getMinIdle())) { // +1 accounts for object we are processing removeObject = true; } if(getTestWhileIdle() && !removeObject) { boolean active = false; try { _factory.activateObject(pair.getValue()); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(pair.getValue())) { removeObject=true; } else { try { _factory.passivateObject(pair.getValue()); } catch(Exception e) { removeObject=true; } } } } if (removeObject) { try { _factory.destroyObject(pair.getValue()); } catch(Exception e) { // ignored } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _numInternalProcessing--; } } allocate(); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { Object key = null; boolean testWhileIdle; long minEvictableIdleTimeMillis; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution testWhileIdle = _testWhileIdle; minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis; // Initialize key to last key value if (_evictionKeyCursor != null && _evictionKeyCursor._lastReturned != null) { key = _evictionKeyCursor._lastReturned.value(); } } for (int i=0,m=getNumTests(); i<m; i++) { final ObjectTimestampPair pair; synchronized (this) { // make sure pool map is not empty; otherwise do nothing if (_poolMap == null || _poolMap.size() == 0) { continue; } // if we don't have a key cursor, then create one if (null == _evictionKeyCursor) { resetEvictionKeyCursor(); key = null; } // if we don't have an object cursor, create one if (null == _evictionCursor) { // if the _evictionKeyCursor has a next value, use this key if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Reset the key cursor and try again resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } if (_evictionCursor == null) { continue; // should never happen; do nothing } // If eviction cursor is exhausted, try to move // to the next key and reset if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Need to reset Key cursor resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } } if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { continue; // reset failed, do nothing } // if LIFO and the _evictionCursor has a previous object, // or FIFO and _evictionCursor has a next object, test it pair = _lifo ? (ObjectTimestampPair) _evictionCursor.previous() : (ObjectTimestampPair) _evictionCursor.next(); _evictionCursor.remove(); _totalIdle--; _totalInternalProcessing++; } boolean removeObject=false; if((minEvictableIdleTimeMillis > 0) && (System.currentTimeMillis() - pair.tstamp > minEvictableIdleTimeMillis)) { removeObject=true; } if(testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _factory.destroyObject(key, pair.value); } catch(Exception e) { // ignored } finally { // Do not remove the key from the _poolList or _poolmap, // even if the list stored in the _poolMap for this key is // empty when minIdle > 0. // // Otherwise if it was the last object for that key, // drop that pool if (_minIdle == 0) { synchronized (this) { ObjectQueue objectQueue = (ObjectQueue)_poolMap.get(key); if (objectQueue != null && objectQueue.queue.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } } } } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); _totalIdle++; if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _totalInternalProcessing--; } } }
#vulnerable code public void evict() throws Exception { // Initialize key to last key value Object key = null; synchronized (this) { if (_evictionKeyCursor != null && _evictionKeyCursor._lastReturned != null) { key = _evictionKeyCursor._lastReturned.value(); } } for (int i=0,m=getNumTests(); i<m; i++) { final ObjectTimestampPair pair; synchronized (this) { // make sure pool map is not empty; otherwise do nothing if (_poolMap == null || _poolMap.size() == 0) { continue; } // if we don't have a key cursor, then create one if (null == _evictionKeyCursor) { resetEvictionKeyCursor(); key = null; } // if we don't have an object cursor, create one if (null == _evictionCursor) { // if the _evictionKeyCursor has a next value, use this key if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Reset the key cursor and try again resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } if (_evictionCursor == null) { continue; // should never happen; do nothing } // If eviction cursor is exhausted, try to move // to the next key and reset if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Need to reset Key cursor resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } } if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { continue; // reset failed, do nothing } // if LIFO and the _evictionCursor has a previous object, // or FIFO and _evictionCursor has a next object, test it pair = _lifo ? (ObjectTimestampPair) _evictionCursor.previous() : (ObjectTimestampPair) _evictionCursor.next(); _evictionCursor.remove(); _totalIdle--; _totalInternalProcessing++; } boolean removeObject=false; if((_minEvictableIdleTimeMillis > 0) && (System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis)) { removeObject=true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _factory.destroyObject(key, pair.value); } catch(Exception e) { // ignored } finally { // Do not remove the key from the _poolList or _poolmap, // even if the list stored in the _poolMap for this key is // empty when minIdle > 0. // // Otherwise if it was the last object for that key, // drop that pool if (_minIdle == 0) { synchronized (this) { ObjectQueue objectQueue = (ObjectQueue)_poolMap.get(key); if (objectQueue != null && objectQueue.queue.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } } } } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); _totalIdle++; if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _totalInternalProcessing--; } } } #location 84 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } synchronized (evictionLock) { boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } }
#vulnerable code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } #location 42 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getActiveTimeMillis() { // Take copies to avoid threading issues long rTime = lastReturnTime; long bTime = lastBorrowTime; if (rTime > bTime) { return rTime - bTime; } else { return System.currentTimeMillis() - bTime; } }
#vulnerable code public long getActiveTimeMillis() { if (lastReturnTime > lastBorrowTime) { return lastReturnTime - lastBorrowTime; } else { return System.currentTimeMillis() - lastBorrowTime; } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setFactory(PoolableObjectFactory factory) throws IllegalStateException { List toDestroy = new ArrayList(); final PoolableObjectFactory oldFactory = _factory; synchronized (this) { assertOpen(); if(0 < getNumActive()) { throw new IllegalStateException("Objects are already active"); } else { toDestroy.addAll(_pool); _numInternalProcessing = _numInternalProcessing + _pool._size; _pool.clear(); } _factory = factory; } destroy(toDestroy, oldFactory); }
#vulnerable code public void setFactory(PoolableObjectFactory factory) throws IllegalStateException { List toDestroy = new ArrayList(); synchronized (this) { assertOpen(); if(0 < getNumActive()) { throw new IllegalStateException("Objects are already active"); } else { toDestroy.addAll(_pool); _numInternalProcessing = _numInternalProcessing + _pool._size; _pool.clear(); } _factory = factory; } destroy(toDestroy); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } updateStatsBorrow(p, waitTime); return p.getObject(); }
#vulnerable code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { assertOpen(); if (_pool.size() == 0) { return; } PooledObject<T> underTest = null; for (int i = 0, m = getNumTests(); i < m; i++) { if (_evictionIterator == null || !_evictionIterator.hasNext()) { if (getLifo()) { _evictionIterator = _pool.descendingIterator(); } else { _evictionIterator = _pool.iterator(); } } if (!_evictionIterator.hasNext()) { // Pool exhausted, nothing to do here return; } else { try { underTest = _evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; _evictionIterator = null; continue; } } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (getMinEvictableIdleTimeMillis() > 0 && getMinEvictableIdleTimeMillis() < underTest.getIdleTimeMillis() || (getSoftMinEvictableIdleTimeMillis() > 0 && getSoftMinEvictableIdleTimeMillis() < underTest.getIdleTimeMillis() && getMinIdle() < _pool.size())) { destroy(underTest); } else { if (getTestWhileIdle()) { boolean active = false; try { _factory.activateObject(underTest.getObject()); active = true; } catch(Exception e) { destroy(underTest); } if(active) { if(!_factory.validateObject(underTest.getObject())) { destroy(underTest); } else { try { _factory.passivateObject(underTest.getObject()); } catch(Exception e) { destroy(underTest); } } } } if (!underTest.endEvictionTest()) { // TODO - May need to add code here once additional states // are used } } } return; }
#vulnerable code public void evict() throws Exception { assertOpen(); synchronized (this) { if(_pool.isEmpty()) { return; } if (null == _evictionCursor) { _evictionCursor = (_pool.cursor(_lifo ? _pool.size() : 0)); } } for (int i=0,m=getNumTests();i<m;i++) { final ObjectTimestampPair<T> pair; synchronized (this) { if ((_lifo && !_evictionCursor.hasPrevious()) || !_lifo && !_evictionCursor.hasNext()) { _evictionCursor.close(); _evictionCursor = _pool.cursor(_lifo ? _pool.size() : 0); } pair = _lifo ? _evictionCursor.previous() : _evictionCursor.next(); _evictionCursor.remove(); _numInternalProcessing++; } boolean removeObject = false; final long idleTimeMilis = System.currentTimeMillis() - pair.getTstamp(); if ((getMinEvictableIdleTimeMillis() > 0) && (idleTimeMilis > getMinEvictableIdleTimeMillis())) { removeObject = true; } else if ((getSoftMinEvictableIdleTimeMillis() > 0) && (idleTimeMilis > getSoftMinEvictableIdleTimeMillis()) && ((getNumIdle() + 1)> getMinIdle())) { // +1 accounts for object we are processing removeObject = true; } if(getTestWhileIdle() && !removeObject) { boolean active = false; try { _factory.activateObject(pair.getValue()); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(pair.getValue())) { removeObject=true; } else { try { _factory.passivateObject(pair.getValue()); } catch(Exception e) { removeObject=true; } } } } if (removeObject) { try { _factory.destroyObject(pair.getValue()); } catch(Exception e) { // ignored } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _numInternalProcessing--; } } allocate(); } #location 62 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clear() { Map toDestroy = new HashMap(); synchronized (this) { for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { Object key = it.next(); ObjectQueue pool = (ObjectQueue)_poolMap.get(key); // Copy objects to new list so pool.queue can be cleared inside // the sync List objects = new ArrayList(); objects.addAll(pool.queue); toDestroy.put(key, objects); it.remove(); _poolList.remove(key); _totalIdle = _totalIdle - pool.queue.size(); _totalInternalProcessing = _totalInternalProcessing + pool.queue.size(); pool.queue.clear(); } } destroy(toDestroy, _factory); }
#vulnerable code public void clear() { Map toDestroy = new HashMap(); synchronized (this) { for (Iterator it = _poolMap.keySet().iterator(); it.hasNext();) { Object key = it.next(); ObjectQueue pool = (ObjectQueue)_poolMap.get(key); // Copy objects to new list so pool.queue can be cleared inside // the sync List objects = new ArrayList(); objects.addAll(pool.queue); toDestroy.put(key, objects); it.remove(); _poolList.remove(key); _totalIdle = _totalIdle - pool.queue.size(); _totalInternalProcessing = _totalInternalProcessing + pool.queue.size(); pool.queue.clear(); } } destroy(toDestroy); } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void printStackTrace(PrintWriter writer) { Exception borrowedBy = this.borrowedBy; if (borrowedBy != null) { borrowedBy.printStackTrace(writer); } Exception usedBy = this.usedBy; if (usedBy != null) { usedBy.printStackTrace(writer); } }
#vulnerable code @Override public void printStackTrace(PrintWriter writer) { if (borrowedBy != null) { borrowedBy.printStackTrace(writer); } if (usedBy != null) { usedBy.printStackTrace(writer); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } synchronized (evictionLock) { boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } }
#vulnerable code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { Object key = null; boolean testWhileIdle; long minEvictableIdleTimeMillis; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution testWhileIdle = _testWhileIdle; minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis; // Initialize key to last key value if (_evictionKeyCursor != null && _evictionKeyCursor._lastReturned != null) { key = _evictionKeyCursor._lastReturned.value(); } } for (int i=0,m=getNumTests(); i<m; i++) { final ObjectTimestampPair pair; synchronized (this) { // make sure pool map is not empty; otherwise do nothing if (_poolMap == null || _poolMap.size() == 0) { continue; } // if we don't have a key cursor, then create one if (null == _evictionKeyCursor) { resetEvictionKeyCursor(); key = null; } // if we don't have an object cursor, create one if (null == _evictionCursor) { // if the _evictionKeyCursor has a next value, use this key if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Reset the key cursor and try again resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } if (_evictionCursor == null) { continue; // should never happen; do nothing } // If eviction cursor is exhausted, try to move // to the next key and reset if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Need to reset Key cursor resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } } if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { continue; // reset failed, do nothing } // if LIFO and the _evictionCursor has a previous object, // or FIFO and _evictionCursor has a next object, test it pair = _lifo ? (ObjectTimestampPair) _evictionCursor.previous() : (ObjectTimestampPair) _evictionCursor.next(); _evictionCursor.remove(); _totalIdle--; _totalInternalProcessing++; } boolean removeObject=false; if((minEvictableIdleTimeMillis > 0) && (System.currentTimeMillis() - pair.tstamp > minEvictableIdleTimeMillis)) { removeObject=true; } if(testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _factory.destroyObject(key, pair.value); } catch(Exception e) { // ignored } finally { // Do not remove the key from the _poolList or _poolmap, // even if the list stored in the _poolMap for this key is // empty when minIdle > 0. // // Otherwise if it was the last object for that key, // drop that pool if (_minIdle == 0) { synchronized (this) { ObjectQueue objectQueue = (ObjectQueue)_poolMap.get(key); if (objectQueue != null && objectQueue.queue.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } } } } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); _totalIdle++; if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _totalInternalProcessing--; } } }
#vulnerable code public void evict() throws Exception { // Initialize key to last key value Object key = null; synchronized (this) { if (_evictionKeyCursor != null && _evictionKeyCursor._lastReturned != null) { key = _evictionKeyCursor._lastReturned.value(); } } for (int i=0,m=getNumTests(); i<m; i++) { final ObjectTimestampPair pair; synchronized (this) { // make sure pool map is not empty; otherwise do nothing if (_poolMap == null || _poolMap.size() == 0) { continue; } // if we don't have a key cursor, then create one if (null == _evictionKeyCursor) { resetEvictionKeyCursor(); key = null; } // if we don't have an object cursor, create one if (null == _evictionCursor) { // if the _evictionKeyCursor has a next value, use this key if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Reset the key cursor and try again resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } if (_evictionCursor == null) { continue; // should never happen; do nothing } // If eviction cursor is exhausted, try to move // to the next key and reset if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Need to reset Key cursor resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } } if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { continue; // reset failed, do nothing } // if LIFO and the _evictionCursor has a previous object, // or FIFO and _evictionCursor has a next object, test it pair = _lifo ? (ObjectTimestampPair) _evictionCursor.previous() : (ObjectTimestampPair) _evictionCursor.next(); _evictionCursor.remove(); _totalIdle--; _totalInternalProcessing++; } boolean removeObject=false; if((_minEvictableIdleTimeMillis > 0) && (System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis)) { removeObject=true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _factory.destroyObject(key, pair.value); } catch(Exception e) { // ignored } finally { // Do not remove the key from the _poolList or _poolmap, // even if the list stored in the _poolMap for this key is // empty when minIdle > 0. // // Otherwise if it was the last object for that key, // drop that pool if (_minIdle == 0) { synchronized (this) { ObjectQueue objectQueue = (ObjectQueue)_poolMap.get(key); if (objectQueue != null && objectQueue.queue.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } } } } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); _totalIdle++; if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _totalInternalProcessing--; } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void destroy(Map m, KeyedPoolableObjectFactory factory) { for (Iterator entries = m.entrySet().iterator(); entries.hasNext();) { Map.Entry entry = (Entry) entries.next(); Object key = entry.getKey(); Collection c = (Collection) entry.getValue(); for (Iterator it = c.iterator(); it.hasNext();) { try { factory.destroyObject( key,((ObjectTimestampPair)(it.next())).value); } catch(Exception e) { // ignore error, keep destroying the rest } finally { synchronized(this) { _totalInternalProcessing--; allocate(); } } } } }
#vulnerable code private void destroy(Map m, KeyedPoolableObjectFactory factory) { for (Iterator keys = m.keySet().iterator(); keys.hasNext();) { Object key = keys.next(); Collection c = (Collection) m.get(key); for (Iterator it = c.iterator(); it.hasNext();) { try { factory.destroyObject( key,((ObjectTimestampPair)(it.next())).value); } catch(Exception e) { // ignore error, keep destroying the rest } finally { synchronized(this) { _totalInternalProcessing--; allocate(); } } } } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { Object key = null; boolean testWhileIdle; long minEvictableIdleTimeMillis; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution testWhileIdle = _testWhileIdle; minEvictableIdleTimeMillis = _minEvictableIdleTimeMillis; // Initialize key to last key value if (_evictionKeyCursor != null && _evictionKeyCursor._lastReturned != null) { key = _evictionKeyCursor._lastReturned.value(); } } for (int i=0,m=getNumTests(); i<m; i++) { final ObjectTimestampPair pair; synchronized (this) { // make sure pool map is not empty; otherwise do nothing if (_poolMap == null || _poolMap.size() == 0) { continue; } // if we don't have a key cursor, then create one if (null == _evictionKeyCursor) { resetEvictionKeyCursor(); key = null; } // if we don't have an object cursor, create one if (null == _evictionCursor) { // if the _evictionKeyCursor has a next value, use this key if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Reset the key cursor and try again resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } if (_evictionCursor == null) { continue; // should never happen; do nothing } // If eviction cursor is exhausted, try to move // to the next key and reset if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Need to reset Key cursor resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } } if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { continue; // reset failed, do nothing } // if LIFO and the _evictionCursor has a previous object, // or FIFO and _evictionCursor has a next object, test it pair = _lifo ? (ObjectTimestampPair) _evictionCursor.previous() : (ObjectTimestampPair) _evictionCursor.next(); _evictionCursor.remove(); _totalIdle--; _totalInternalProcessing++; } boolean removeObject=false; if((minEvictableIdleTimeMillis > 0) && (System.currentTimeMillis() - pair.tstamp > minEvictableIdleTimeMillis)) { removeObject=true; } if(testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _factory.destroyObject(key, pair.value); } catch(Exception e) { // ignored } finally { // Do not remove the key from the _poolList or _poolmap, // even if the list stored in the _poolMap for this key is // empty when minIdle > 0. // // Otherwise if it was the last object for that key, // drop that pool if (_minIdle == 0) { synchronized (this) { ObjectQueue objectQueue = (ObjectQueue)_poolMap.get(key); if (objectQueue != null && objectQueue.queue.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } } } } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); _totalIdle++; if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _totalInternalProcessing--; } } }
#vulnerable code public void evict() throws Exception { // Initialize key to last key value Object key = null; synchronized (this) { if (_evictionKeyCursor != null && _evictionKeyCursor._lastReturned != null) { key = _evictionKeyCursor._lastReturned.value(); } } for (int i=0,m=getNumTests(); i<m; i++) { final ObjectTimestampPair pair; synchronized (this) { // make sure pool map is not empty; otherwise do nothing if (_poolMap == null || _poolMap.size() == 0) { continue; } // if we don't have a key cursor, then create one if (null == _evictionKeyCursor) { resetEvictionKeyCursor(); key = null; } // if we don't have an object cursor, create one if (null == _evictionCursor) { // if the _evictionKeyCursor has a next value, use this key if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Reset the key cursor and try again resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } if (_evictionCursor == null) { continue; // should never happen; do nothing } // If eviction cursor is exhausted, try to move // to the next key and reset if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } else { // Need to reset Key cursor resetEvictionKeyCursor(); if (_evictionKeyCursor != null) { if (_evictionKeyCursor.hasNext()) { key = _evictionKeyCursor.next(); resetEvictionObjectCursor(key); } } } } } if((_lifo && !_evictionCursor.hasPrevious()) || (!_lifo && !_evictionCursor.hasNext())) { continue; // reset failed, do nothing } // if LIFO and the _evictionCursor has a previous object, // or FIFO and _evictionCursor has a next object, test it pair = _lifo ? (ObjectTimestampPair) _evictionCursor.previous() : (ObjectTimestampPair) _evictionCursor.next(); _evictionCursor.remove(); _totalIdle--; _totalInternalProcessing++; } boolean removeObject=false; if((_minEvictableIdleTimeMillis > 0) && (System.currentTimeMillis() - pair.tstamp > _minEvictableIdleTimeMillis)) { removeObject=true; } if(_testWhileIdle && removeObject == false) { boolean active = false; try { _factory.activateObject(key,pair.value); active = true; } catch(Exception e) { removeObject=true; } if(active) { if(!_factory.validateObject(key,pair.value)) { removeObject=true; } else { try { _factory.passivateObject(key,pair.value); } catch(Exception e) { removeObject=true; } } } } if(removeObject) { try { _factory.destroyObject(key, pair.value); } catch(Exception e) { // ignored } finally { // Do not remove the key from the _poolList or _poolmap, // even if the list stored in the _poolMap for this key is // empty when minIdle > 0. // // Otherwise if it was the last object for that key, // drop that pool if (_minIdle == 0) { synchronized (this) { ObjectQueue objectQueue = (ObjectQueue)_poolMap.get(key); if (objectQueue != null && objectQueue.queue.isEmpty()) { _poolMap.remove(key); _poolList.remove(key); } } } } } synchronized (this) { if(!removeObject) { _evictionCursor.add(pair); _totalIdle++; if (_lifo) { // Skip over the element we just added back _evictionCursor.previous(); } } _totalInternalProcessing--; } } } #location 88 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int compareTo(PooledObject<T> other) { final long lastActiveDiff = this.getLastReturnTime() - other.getLastReturnTime(); if (lastActiveDiff == 0) { // make sure the natural ordering is consistent with equals // see java.lang.Comparable Javadocs return System.identityHashCode(this) - System.identityHashCode(other); } // handle int overflow return (int)Math.min(Math.max(lastActiveDiff, Integer.MIN_VALUE), Integer.MAX_VALUE); }
#vulnerable code public int compareTo(PooledObject<T> other) { final long lastActiveDiff = this.getLastActiveTime() - other.getLastActiveTime(); if (lastActiveDiff == 0) { // make sure the natural ordering is consistent with equals // see java.lang.Comparable Javadocs return System.identityHashCode(this) - System.identityHashCode(other); } // handle int overflow return (int)Math.min(Math.max(lastActiveDiff, Integer.MIN_VALUE), Integer.MAX_VALUE); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); }
#vulnerable code public T borrowObject(K key, long borrowMaxWait) throws Exception { assertOpen(); PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; long waitTime = 0; ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; if (blockWhenExhausted) { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null && objectDeque != null) { if (borrowMaxWait < 0) { p = objectDeque.getIdleObjects().takeFirst(); } else { waitTime = System.currentTimeMillis(); p = objectDeque.getIdleObjects().pollFirst( borrowMaxWait, TimeUnit.MILLISECONDS); waitTime = System.currentTimeMillis() - waitTime; } } if (p == null) { throw new NoSuchElementException( "Timeout waiting for idle object"); } if (!p.allocate()) { p = null; } } else { if (objectDeque != null) { p = objectDeque.getIdleObjects().pollFirst(); } if (p == null) { create = true; p = create(key); } if (p == null) { throw new NoSuchElementException("Pool exhausted"); } if (!p.allocate()) { p = null; } } if (p != null) { try { _factory.activateObject(key, p.getObject()); } catch (Exception e) { try { destroy(key, p, true); } catch (Exception e1) { // Ignore - activation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to activate object"); nsee.initCause(e); throw nsee; } } if (p != null && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = _factory.validateObject(key, p.getObject()); } catch (Throwable t) { PoolUtils.checkRethrow(t); } if (!validate) { try { destroy(key, p, true); destroyedByBorrowValidationCount.incrementAndGet(); } catch (Exception e) { // Ignore - validation failure is more important } p = null; if (create) { NoSuchElementException nsee = new NoSuchElementException( "Unable to validate object"); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } borrowedCount.incrementAndGet(); synchronized (idleTimes) { idleTimes.add(Long.valueOf(p.getIdleTimeMillis())); idleTimes.poll(); } synchronized (waitTimes) { waitTimes.add(Long.valueOf(waitTime)); waitTimes.poll(); } synchronized (maxBorrowWaitTimeMillisLock) { if (waitTime > maxBorrowWaitTimeMillis) { maxBorrowWaitTimeMillis = waitTime; } } return p.getObject(); } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(); byte whenExhaustedAction; long maxWait; synchronized (this) { // Get local copy of current config. Can't sync when used later as // it can result in a deadlock. Has the added advantage that config // is consistent for entire method execution whenExhaustedAction = _whenExhaustedAction; maxWait = _maxWait; // Add this request to the queue _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated from the pool above if(latch._pair == null) { // check if we were allowed to create one if(latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if(null == latch._pair) { try { Object obj = _factory.makeObject(); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { _numInternalProcessing--; // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(latch._pair.value); if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized(this) { _numInternalProcessing--; _numActive++; } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { _numInternalProcessing--; latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } }
#vulnerable code public Object borrowObject() throws Exception { long starttime = System.currentTimeMillis(); Latch latch = new Latch(); synchronized (this) { _allocationQueue.add(latch); allocate(); } for(;;) { synchronized (this) { assertOpen(); } // If no object was allocated from the pool above if(latch._pair == null) { // check if we were allowed to create one if(latch._mayCreate) { // allow new object to be created } else { // the pool is exhausted switch(_whenExhaustedAction) { case WHEN_EXHAUSTED_GROW: // allow new object to be created break; case WHEN_EXHAUSTED_FAIL: synchronized (this) { _allocationQueue.remove(latch); } throw new NoSuchElementException("Pool exhausted"); case WHEN_EXHAUSTED_BLOCK: try { synchronized (latch) { if(_maxWait <= 0) { latch.wait(); } else { // this code may be executed again after a notify then continue cycle // so, need to calculate the amount of time to wait final long elapsed = (System.currentTimeMillis() - starttime); final long waitTime = _maxWait - elapsed; if (waitTime > 0) { latch.wait(waitTime); } } } } catch(InterruptedException e) { Thread.currentThread().interrupt(); throw e; } if(_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) { throw new NoSuchElementException("Timeout waiting for idle object"); } else { continue; // keep looping } default: throw new IllegalArgumentException("WhenExhaustedAction property " + _whenExhaustedAction + " not recognized."); } } } boolean newlyCreated = false; if(null == latch._pair) { try { Object obj = _factory.makeObject(); latch._pair = new ObjectTimestampPair(obj); newlyCreated = true; } finally { if (!newlyCreated) { // object cannot be created synchronized (this) { _numInternalProcessing--; // No need to reset latch - about to throw exception allocate(); } } } } // activate & validate the object try { _factory.activateObject(latch._pair.value); if(_testOnBorrow && !_factory.validateObject(latch._pair.value)) { throw new Exception("ValidateObject failed"); } synchronized(this) { _numInternalProcessing--; _numActive++; } return latch._pair.value; } catch (Throwable e) { // object cannot be activated or is invalid try { _factory.destroyObject(latch._pair.value); } catch (Throwable e2) { // cannot destroy broken object } synchronized (this) { _numInternalProcessing--; latch.reset(); _allocationQueue.add(0, latch); allocate(); } if(newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + e.getMessage()); } else { continue; // keep looping } } } } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } synchronized (evictionLock) { boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } }
#vulnerable code public void evict() throws Exception { assertOpen(); if (getNumIdle() == 0) { return; } boolean testWhileIdle = getTestWhileIdle(); long idleEvictTime = Long.MAX_VALUE; if (getMinEvictableIdleTimeMillis() > 0) { idleEvictTime = getMinEvictableIdleTimeMillis(); } PooledObject<T> underTest = null; LinkedBlockingDeque<PooledObject<T>> idleObjects = null; for (int i = 0, m = getNumTests(); i < m; i++) { if(evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { List<K> keyCopy = new ArrayList<K>(); keyCopy.addAll(poolKeyList); evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } idleObjects = objectDeque.getIdleObjects(); if (getLifo()) { evictionIterator = idleObjects.descendingIterator(); } else { evictionIterator = idleObjects.iterator(); } if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } try { underTest = evictionIterator.next(); } catch (NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } if (idleEvictTime < underTest.getIdleTimeMillis()) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest.getObject()); active = true; } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } if (active) { if (!factory.validateObject(evictionKey, underTest.getObject())) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } else { try { factory.passivateObject(evictionKey, underTest.getObject()); } catch (Exception e) { destroy(evictionKey, underTest, true); destroyedByEvictorCount.incrementAndGet(); } } } } if (!underTest.endEvictionTest(idleObjects)) { // TODO - May need to add code here once additional states // are used } } } } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) { Elements elementUtils = processingEnv.getElementUtils(); Types typeUtils = processingEnv.getTypeUtils(); Filer filer = processingEnv.getFiler(); // // Processor options // boolean isLibrary = false; String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY); if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) { isLibrary = true; } String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS); if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) { supportAnnotations = false; } String additionalBuilderAnnotations[] = {}; String builderAnnotationsStr = processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS); if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) { additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter } List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>(); JavaWriter jw = null; // REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set Set<TypeElement> fragmentClasses = new HashSet<TypeElement>(); Element[] origHelper = null; // Search for @Arg fields for (Element element : env.getElementsAnnotatedWith(Arg.class)) { try { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Check if its a fragment if (!isFragmentClass(enclosingElement, TYPE_FRAGMENT, TYPE_SUPPORT_FRAGMENT)) { throw new ProcessingException(element, "@Arg can only be used on fragment fields (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers().contains(Modifier.FINAL)) { throw new ProcessingException(element, "@Arg fields must not be final (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers() .contains(Modifier.STATIC)) { throw new ProcessingException(element, "@Arg fields must not be static (%s.%s)", enclosingElement.getQualifiedName(), element); } // Skip abstract classes if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) { fragmentClasses.add(enclosingElement); } } catch (ProcessingException e) { processingExceptions.add(e); } } // Search for "just" @FragmentWithArgs for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) { try { scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element); } catch (ProcessingException e) { processingExceptions.add(e); } } // Store the key - value for the generated FragmentArtMap class Map<String, String> autoMapping = new HashMap<String, String>(); for (TypeElement fragmentClass : fragmentClasses) { JavaFileObject jfo = null; try { AnnotatedFragment fragment = collectArgumentsForType(fragmentClass); String builder = fragment.getSimpleName() + "Builder"; List<Element> originating = new ArrayList<Element>(10); originating.add(fragmentClass); TypeMirror superClass = fragmentClass.getSuperclass(); while (superClass.getKind() != TypeKind.NONE) { TypeElement element = (TypeElement) typeUtils.asElement(superClass); if (element.getQualifiedName().toString().startsWith("android.")) { break; } originating.add(element); superClass = element.getSuperclass(); } String qualifiedFragmentName = fragment.getQualifiedName(); String qualifiedBuilderName = qualifiedFragmentName + "Builder"; Element[] orig = originating.toArray(new Element[originating.size()]); origHelper = orig; jfo = filer.createSourceFile(qualifiedBuilderName, orig); Writer writer = jfo.openWriter(); jw = new JavaWriter(writer); writePackage(jw, fragmentClass); jw.emitImports("android.os.Bundle"); if (supportAnnotations) { jw.emitImports("android.support.annotation.NonNull"); if (!fragment.getOptionalFields().isEmpty()) { jw.emitImports("android.support.annotation.Nullable"); } } jw.emitEmptyLine(); // Additional builder annotations for (String builderAnnotation : additionalBuilderAnnotations) { jw.emitAnnotation(builderAnnotation); } jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL)); if (!fragment.getBundlerVariableMap().isEmpty()) { jw.emitEmptyLine(); for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) { jw.emitField(e.getKey(), e.getValue(), EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC), "new " + e.getKey() + "()"); } } jw.emitEmptyLine(); jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL), "new Bundle()"); jw.emitEmptyLine(); Set<ArgumentAnnotatedField> required = fragment.getRequiredFields(); String[] args = new String[required.size() * 2]; int index = 0; for (ArgumentAnnotatedField arg : required) { boolean annotate = supportAnnotations && !arg.isPrimitive(); args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType(); args[index++] = arg.getVariableName(); } jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args); for (ArgumentAnnotatedField arg : required) { writePutArguments(jw, arg.getVariableName(), "mArguments", arg); } jw.endMethod(); if (!required.isEmpty()) { jw.emitEmptyLine(); writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args); } Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields(); for (ArgumentAnnotatedField arg : optionalArguments) { writeBuilderMethod(builder, jw, arg); } jw.emitEmptyLine(); writeBuildBundleMethod(jw); jw.emitEmptyLine(); writeInjectMethod(jw, fragmentClass, fragment); jw.emitEmptyLine(); writeBuildMethod(jw, fragmentClass); jw.endType(); autoMapping.put(qualifiedFragmentName, qualifiedBuilderName); } catch (IOException e) { processingExceptions.add( new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s", fragmentClass, e.getMessage())); } catch (ProcessingException e) { processingExceptions.add(e); if (jfo != null) { jfo.delete(); } } finally { if (jw != null) { try { jw.close(); } catch (IOException e1) { processingExceptions.add(new ProcessingException(fragmentClass, "Unable to close javawriter while generating builder for type %s: %s", fragmentClass, e1.getMessage())); } } } } // Write the automapping class if (origHelper != null && !isLibrary) { try { writeAutoMapping(autoMapping, origHelper); } catch (ProcessingException e) { processingExceptions.add(e); } } // Print errors for (ProcessingException e : processingExceptions) { error(e); } return true; }
#vulnerable code @Override public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) { Elements elementUtils = processingEnv.getElementUtils(); Types typeUtils = processingEnv.getTypeUtils(); Filer filer = processingEnv.getFiler(); // // Processor options // boolean isLibrary = false; String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY); if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) { isLibrary = true; } String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS); if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) { supportAnnotations = false; } String additionalBuilderAnnotations[] = {}; String builderAnnotationsStr = processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS); if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) { additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter } List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>(); JavaWriter jw = null; // REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set Set<TypeElement> fragmentClasses = new HashSet<TypeElement>(); Element[] origHelper = null; // Search for @Arg fields for (Element element : env.getElementsAnnotatedWith(Arg.class)) { try { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Check if its a fragment if (!isFragmentClass(enclosingElement, TYPE_FRAGMENT, TYPE_SUPPORT_FRAGMENT)) { throw new ProcessingException(element, "@Arg can only be used on fragment fields (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers().contains(Modifier.FINAL)) { throw new ProcessingException(element, "@Arg fields must not be final (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers() .contains(Modifier.STATIC)) { throw new ProcessingException(element, "@Arg fields must not be static (%s.%s)", enclosingElement.getQualifiedName(), element); } // Skip abstract classes if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) { fragmentClasses.add(enclosingElement); } } catch (ProcessingException e) { processingExceptions.add(e); } } // Search for "just" @InheritedFragmentArgs --> DEPRECATED for (Element element : env.getElementsAnnotatedWith(FragmentArgsInherited.class)) { try { scanForAnnotatedFragmentClasses(env, FragmentArgsInherited.class, fragmentClasses, element); } catch (ProcessingException e) { processingExceptions.add(e); } } // Search for "just" @FragmentWithArgs for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) { try { scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element); } catch (ProcessingException e) { processingExceptions.add(e); } } // Store the key - value for the generated FragmentArtMap class Map<String, String> autoMapping = new HashMap<String, String>(); for (TypeElement fragmentClass : fragmentClasses) { JavaFileObject jfo = null; try { AnnotatedFragment fragment = collectArgumentsForType(fragmentClass); String builder = fragment.getSimpleName() + "Builder"; List<Element> originating = new ArrayList<Element>(10); originating.add(fragmentClass); TypeMirror superClass = fragmentClass.getSuperclass(); while (superClass.getKind() != TypeKind.NONE) { TypeElement element = (TypeElement) typeUtils.asElement(superClass); if (element.getQualifiedName().toString().startsWith("android.")) { break; } originating.add(element); superClass = element.getSuperclass(); } String qualifiedFragmentName = fragment.getQualifiedName(); String qualifiedBuilderName = qualifiedFragmentName + "Builder"; Element[] orig = originating.toArray(new Element[originating.size()]); origHelper = orig; jfo = filer.createSourceFile(qualifiedBuilderName, orig); Writer writer = jfo.openWriter(); jw = new JavaWriter(writer); writePackage(jw, fragmentClass); jw.emitImports("android.os.Bundle"); if (supportAnnotations) { jw.emitImports("android.support.annotation.NonNull"); if (!fragment.getOptionalFields().isEmpty()) { jw.emitImports("android.support.annotation.Nullable"); } } jw.emitEmptyLine(); // Additional builder annotations for (String builderAnnotation : additionalBuilderAnnotations) { jw.emitAnnotation(builderAnnotation); } jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL)); if (!fragment.getBundlerVariableMap().isEmpty()) { jw.emitEmptyLine(); for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) { jw.emitField(e.getKey(), e.getValue(), EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC), "new " + e.getKey() + "()"); } } jw.emitEmptyLine(); jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL), "new Bundle()"); jw.emitEmptyLine(); Set<ArgumentAnnotatedField> required = fragment.getRequiredFields(); String[] args = new String[required.size() * 2]; int index = 0; for (ArgumentAnnotatedField arg : required) { boolean annotate = supportAnnotations && !arg.isPrimitive(); args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType(); args[index++] = arg.getVariableName(); } jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args); for (ArgumentAnnotatedField arg : required) { writePutArguments(jw, arg.getVariableName(), "mArguments", arg); } jw.endMethod(); if (!required.isEmpty()) { jw.emitEmptyLine(); writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args); } Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields(); for (ArgumentAnnotatedField arg : optionalArguments) { writeBuilderMethod(builder, jw, arg); } jw.emitEmptyLine(); writeBuildBundleMethod(jw); jw.emitEmptyLine(); writeInjectMethod(jw, fragmentClass, fragment); jw.emitEmptyLine(); writeBuildMethod(jw, fragmentClass); jw.endType(); autoMapping.put(qualifiedFragmentName, qualifiedBuilderName); } catch (IOException e) { processingExceptions.add( new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s", fragmentClass, e.getMessage())); } catch (ProcessingException e) { processingExceptions.add(e); if (jfo != null) { jfo.delete(); } } finally { if (jw != null) { try { jw.close(); } catch (IOException e1) { processingExceptions.add(new ProcessingException(fragmentClass, "Unable to close javawriter while generating builder for type %s: %s", fragmentClass, e1.getMessage())); } } } } // Write the automapping class if (origHelper != null && !isLibrary) { try { writeAutoMapping(autoMapping, origHelper); } catch (ProcessingException e) { processingExceptions.add(e); } } // Print errors for (ProcessingException e : processingExceptions) { error(e); } return true; } #location 76 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) { Types typeUtils = processingEnv.getTypeUtils(); Filer filer = processingEnv.getFiler(); // // Processor options // boolean isLibrary = false; String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY); if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) { isLibrary = true; } String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS); if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) { supportAnnotations = false; } String additionalBuilderAnnotations[] = {}; String builderAnnotationsStr = processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS); if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) { additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter } String fragmentArgsLogWarnings = processingEnv.getOptions().get(OPTION_LOG_WARNINGS); if(fragmentArgsLogWarnings != null && fragmentArgsLogWarnings.equalsIgnoreCase("false")) { logWarnings = false; } String nonNullAnnotationImport = ""; String nullableAnnotationImport = ""; if(supportAnnotations) { if (isClassAvailable("android.support.annotation.NonNull")) { nonNullAnnotationImport = "android.support.annotation.NonNull"; nullableAnnotationImport = "android.support.annotation.Nullable"; } else if (isClassAvailable("androidx.annotation.NonNull")) { nonNullAnnotationImport = "androidx.annotation.NonNull"; nullableAnnotationImport = "androidx.annotation.Nullable"; } else { supportAnnotations = false; warn(null, "Support annotations have been disabled because neither " + "'android.support.annotation.NonNull' nor " + "'androidx.annotation.NonNull' could be found during processing" ); } } List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>(); JavaWriter jw = null; // REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set Set<TypeElement> fragmentClasses = new HashSet<TypeElement>(); Element[] origHelper = null; // Search for @Arg fields for (Element element : env.getElementsAnnotatedWith(Arg.class)) { try { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Check if its a fragment if (!isFragmentClass(enclosingElement)) { throw new ProcessingException(element, "@Arg can only be used on fragment fields (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers().contains(Modifier.FINAL)) { throw new ProcessingException(element, "@Arg fields must not be final (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers() .contains(Modifier.STATIC)) { throw new ProcessingException(element, "@Arg fields must not be static (%s.%s)", enclosingElement.getQualifiedName(), element); } // Skip abstract classes if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) { fragmentClasses.add(enclosingElement); } } catch (ProcessingException e) { processingExceptions.add(e); } } // Search for "just" @FragmentWithArgs for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) { try { scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element); } catch (ProcessingException e) { processingExceptions.add(e); } } // Store the key - value for the generated FragmentArtMap class Map<String, String> autoMapping = new HashMap<String, String>(); for (TypeElement fragmentClass : fragmentClasses) { JavaFileObject jfo = null; try { AnnotatedFragment fragment = collectArgumentsForType(fragmentClass); String builder = fragment.getSimpleName() + "Builder"; List<Element> originating = new ArrayList<Element>(10); originating.add(fragmentClass); TypeMirror superClass = fragmentClass.getSuperclass(); while (superClass.getKind() != TypeKind.NONE) { TypeElement element = (TypeElement) typeUtils.asElement(superClass); if (element.getQualifiedName().toString().startsWith("android.")) { break; } originating.add(element); superClass = element.getSuperclass(); } String qualifiedFragmentName = fragment.getQualifiedName(); String qualifiedBuilderName = qualifiedFragmentName + "Builder"; Element[] orig = originating.toArray(new Element[originating.size()]); origHelper = orig; jfo = filer.createSourceFile(qualifiedBuilderName, orig); Writer writer = jfo.openWriter(); jw = new JavaWriter(writer); writePackage(jw, fragmentClass); jw.emitImports("android.os.Bundle"); if (supportAnnotations) { jw.emitImports(nonNullAnnotationImport); if (!fragment.getOptionalFields().isEmpty()) { jw.emitImports(nullableAnnotationImport); } } jw.emitEmptyLine(); // Additional builder annotations for (String builderAnnotation : additionalBuilderAnnotations) { jw.emitAnnotation(builderAnnotation); } jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL)); if (!fragment.getBundlerVariableMap().isEmpty()) { jw.emitEmptyLine(); for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) { jw.emitField(e.getKey(), e.getValue(), EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC), "new " + e.getKey() + "()"); } } jw.emitEmptyLine(); jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL), "new Bundle()"); jw.emitEmptyLine(); Set<ArgumentAnnotatedField> required = fragment.getRequiredFields(); String[] args = new String[required.size() * 2]; int index = 0; for (ArgumentAnnotatedField arg : required) { boolean annotate = supportAnnotations && !arg.isPrimitive(); args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType(); args[index++] = arg.getVariableName(); } jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args); for (ArgumentAnnotatedField arg : required) { writePutArguments(jw, arg.getVariableName(), "mArguments", arg); } jw.endMethod(); if (!required.isEmpty()) { jw.emitEmptyLine(); writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args); } Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields(); for (ArgumentAnnotatedField arg : optionalArguments) { writeBuilderMethod(builder, jw, arg); } jw.emitEmptyLine(); writeBuildBundleMethod(jw); jw.emitEmptyLine(); writeInjectMethod(jw, fragmentClass, fragment); jw.emitEmptyLine(); writeBuildMethod(jw, fragmentClass); jw.endType(); autoMapping.put(qualifiedFragmentName, qualifiedBuilderName); } catch (IOException e) { processingExceptions.add( new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s", fragmentClass, e.getMessage())); } catch (ProcessingException e) { processingExceptions.add(e); if (jfo != null) { jfo.delete(); } } finally { if (jw != null) { try { jw.close(); } catch (IOException e1) { processingExceptions.add(new ProcessingException(fragmentClass, "Unable to close javawriter while generating builder for type %s: %s", fragmentClass, e1.getMessage())); } } } } // Write the automapping class if (origHelper != null && !isLibrary) { try { writeAutoMapping(autoMapping, origHelper); } catch (ProcessingException e) { processingExceptions.add(e); } } // Print errors for (ProcessingException e : processingExceptions) { error(e); } return true; }
#vulnerable code @Override public boolean process(Set<? extends TypeElement> type, RoundEnvironment env) { Types typeUtils = processingEnv.getTypeUtils(); Filer filer = processingEnv.getFiler(); // // Processor options // boolean isLibrary = false; String fragmentArgsLib = processingEnv.getOptions().get(OPTION_IS_LIBRARY); if (fragmentArgsLib != null && fragmentArgsLib.equalsIgnoreCase("true")) { isLibrary = true; } String supportAnnotationsStr = processingEnv.getOptions().get(OPTION_SUPPORT_ANNOTATIONS); if (supportAnnotationsStr != null && supportAnnotationsStr.equalsIgnoreCase("false")) { supportAnnotations = false; } String additionalBuilderAnnotations[] = {}; String builderAnnotationsStr = processingEnv.getOptions().get(OPTION_ADDITIONAL_BUILDER_ANNOTATIONS); if (builderAnnotationsStr != null && builderAnnotationsStr.length() > 0) { additionalBuilderAnnotations = builderAnnotationsStr.split(" "); // White space is delimiter } String fragmentArgsLogWarnings = processingEnv.getOptions().get(OPTION_LOG_WARNINGS); if(fragmentArgsLogWarnings != null && fragmentArgsLogWarnings.equalsIgnoreCase("false")) { logWarnings = false; } List<ProcessingException> processingExceptions = new ArrayList<ProcessingException>(); JavaWriter jw = null; // REMEMBER: It's a SET! it uses .equals() .hashCode() to determine if element already in set Set<TypeElement> fragmentClasses = new HashSet<TypeElement>(); Element[] origHelper = null; // Search for @Arg fields for (Element element : env.getElementsAnnotatedWith(Arg.class)) { try { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Check if its a fragment if (!isFragmentClass(enclosingElement, TYPE_FRAGMENT, TYPE_SUPPORT_FRAGMENT)) { throw new ProcessingException(element, "@Arg can only be used on fragment fields (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers().contains(Modifier.FINAL)) { throw new ProcessingException(element, "@Arg fields must not be final (%s.%s)", enclosingElement.getQualifiedName(), element); } if (element.getModifiers() .contains(Modifier.STATIC)) { throw new ProcessingException(element, "@Arg fields must not be static (%s.%s)", enclosingElement.getQualifiedName(), element); } // Skip abstract classes if (!enclosingElement.getModifiers().contains(Modifier.ABSTRACT)) { fragmentClasses.add(enclosingElement); } } catch (ProcessingException e) { processingExceptions.add(e); } } // Search for "just" @FragmentWithArgs for (Element element : env.getElementsAnnotatedWith(FragmentWithArgs.class)) { try { scanForAnnotatedFragmentClasses(env, FragmentWithArgs.class, fragmentClasses, element); } catch (ProcessingException e) { processingExceptions.add(e); } } // Store the key - value for the generated FragmentArtMap class Map<String, String> autoMapping = new HashMap<String, String>(); for (TypeElement fragmentClass : fragmentClasses) { JavaFileObject jfo = null; try { AnnotatedFragment fragment = collectArgumentsForType(fragmentClass); String builder = fragment.getSimpleName() + "Builder"; List<Element> originating = new ArrayList<Element>(10); originating.add(fragmentClass); TypeMirror superClass = fragmentClass.getSuperclass(); while (superClass.getKind() != TypeKind.NONE) { TypeElement element = (TypeElement) typeUtils.asElement(superClass); if (element.getQualifiedName().toString().startsWith("android.")) { break; } originating.add(element); superClass = element.getSuperclass(); } String qualifiedFragmentName = fragment.getQualifiedName(); String qualifiedBuilderName = qualifiedFragmentName + "Builder"; Element[] orig = originating.toArray(new Element[originating.size()]); origHelper = orig; jfo = filer.createSourceFile(qualifiedBuilderName, orig); Writer writer = jfo.openWriter(); jw = new JavaWriter(writer); writePackage(jw, fragmentClass); jw.emitImports("android.os.Bundle"); if (supportAnnotations) { jw.emitImports("android.support.annotation.NonNull"); if (!fragment.getOptionalFields().isEmpty()) { jw.emitImports("android.support.annotation.Nullable"); } } jw.emitEmptyLine(); // Additional builder annotations for (String builderAnnotation : additionalBuilderAnnotations) { jw.emitAnnotation(builderAnnotation); } jw.beginType(builder, "class", EnumSet.of(Modifier.PUBLIC, Modifier.FINAL)); if (!fragment.getBundlerVariableMap().isEmpty()) { jw.emitEmptyLine(); for (Map.Entry<String, String> e : fragment.getBundlerVariableMap().entrySet()) { jw.emitField(e.getKey(), e.getValue(), EnumSet.of(Modifier.PRIVATE, Modifier.FINAL, Modifier.STATIC), "new " + e.getKey() + "()"); } } jw.emitEmptyLine(); jw.emitField("Bundle", "mArguments", EnumSet.of(Modifier.PRIVATE, Modifier.FINAL), "new Bundle()"); jw.emitEmptyLine(); Set<ArgumentAnnotatedField> required = fragment.getRequiredFields(); String[] args = new String[required.size() * 2]; int index = 0; for (ArgumentAnnotatedField arg : required) { boolean annotate = supportAnnotations && !arg.isPrimitive(); args[index++] = annotate ? "@NonNull " + arg.getType() : arg.getType(); args[index++] = arg.getVariableName(); } jw.beginMethod(null, builder, EnumSet.of(Modifier.PUBLIC), args); for (ArgumentAnnotatedField arg : required) { writePutArguments(jw, arg.getVariableName(), "mArguments", arg); } jw.endMethod(); if (!required.isEmpty()) { jw.emitEmptyLine(); writeNewFragmentWithRequiredMethod(builder, fragmentClass, jw, args); } Set<ArgumentAnnotatedField> optionalArguments = fragment.getOptionalFields(); for (ArgumentAnnotatedField arg : optionalArguments) { writeBuilderMethod(builder, jw, arg); } jw.emitEmptyLine(); writeBuildBundleMethod(jw); jw.emitEmptyLine(); writeInjectMethod(jw, fragmentClass, fragment); jw.emitEmptyLine(); writeBuildMethod(jw, fragmentClass); jw.endType(); autoMapping.put(qualifiedFragmentName, qualifiedBuilderName); } catch (IOException e) { processingExceptions.add( new ProcessingException(fragmentClass, "Unable to write builder for type %s: %s", fragmentClass, e.getMessage())); } catch (ProcessingException e) { processingExceptions.add(e); if (jfo != null) { jfo.delete(); } } finally { if (jw != null) { try { jw.close(); } catch (IOException e1) { processingExceptions.add(new ProcessingException(fragmentClass, "Unable to close javawriter while generating builder for type %s: %s", fragmentClass, e1.getMessage())); } } } } // Write the automapping class if (origHelper != null && !isLibrary) { try { writeAutoMapping(autoMapping, origHelper); } catch (ProcessingException e) { processingExceptions.add(e); } } // Print errors for (ProcessingException e : processingExceptions) { error(e); } return true; } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMissingSlotMillis() throws IOException { final String JOB_HISTORY_FILE_NAME = "src/test/resources/job_1329348432999_0003-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist"; File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME); byte[] contents = Files.toByteArray(jobHistoryfile); final String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; Configuration jobConf = new Configuration(); jobConf.addResource(new Path(JOB_CONF_FILE_NAME)); JobHistoryFileParserHadoop2 historyFileParser = new JobHistoryFileParserHadoop2(jobConf); assertNotNull(historyFileParser); JobKey jobKey = new JobKey("cluster1", "user", "Sleep", 1, "job_1329348432655_0001"); historyFileParser.parse(contents, jobKey); // this history file has only map slot millis no reduce millis Long mapMbMillis = historyFileParser.getMapMbMillis(); assertNotNull(mapMbMillis); assertEquals(mapMbMillis, new Long(178169856L)); Long reduceMbMillis = historyFileParser.getReduceMbMillis(); assertNotNull(reduceMbMillis); assertEquals(reduceMbMillis, Constants.NOTFOUND_VALUE); Long mbMillis = historyFileParser.getMegaByteMillis(); assertNotNull(mbMillis); Long expValue = 188559872L; assertEquals(expValue, mbMillis); }
#vulnerable code @Test public void testMissingSlotMillis() throws IOException { final String JOB_HISTORY_FILE_NAME = "src/test/resources/job_1329348432999_0003-1329348443227-user-Sleep+job-1329348468601-10-1-SUCCEEDED-default.jhist"; File jobHistoryfile = new File(JOB_HISTORY_FILE_NAME); byte[] contents = Files.toByteArray(jobHistoryfile); final String JOB_CONF_FILE_NAME = "src/test/resources/job_1329348432655_0001_conf.xml"; Configuration jobConf = new Configuration(); jobConf.addResource(new Path(JOB_CONF_FILE_NAME)); JobHistoryFileParser historyFileParser = JobHistoryFileParserFactory.createJobHistoryFileParser(contents, jobConf); assertNotNull(historyFileParser); // confirm that we get back an object that can parse hadoop 2.0 files assertTrue(historyFileParser instanceof JobHistoryFileParserHadoop2); JobKey jobKey = new JobKey("cluster1", "user", "Sleep", 1, "job_1329348432655_0001"); historyFileParser.parse(contents, jobKey); // this history file has only map slot millis no reduce millis Long mbMillis = historyFileParser.getMegaByteMillis(); assertNotNull(mbMillis); Long expValue = 10402816L; assertEquals(expValue, mbMillis); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowQueueReadWrite() throws Exception { FlowQueueService service = new FlowQueueService(UTIL.getConfiguration()); // add a couple of test flows Flow flow1 = createFlow(service, TEST_USER, 1); FlowQueueKey key1 = flow1.getQueueKey(); Flow flow2 = createFlow(service, TEST_USER, 2); FlowQueueKey key2 = flow2.getQueueKey(); // read back one flow Flow flow1Retrieved = service.getFlowFromQueue(key1.getCluster(), key1.getTimestamp(), key1.getFlowId()); assertNotNull(flow1Retrieved); assertFlowEquals(key1, flow1, flow1Retrieved); // try reading both flows back List<Flow> running = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.RUNNING, 10); assertNotNull(running); assertEquals(2, running.size()); // results should be in reverse order by timestamp Flow result1 = running.get(1); assertFlowEquals(key1, flow1, result1); Flow result2 = running.get(0); assertFlowEquals(key2, flow2, result2); // move both flows to successful status FlowQueueKey newKey1 = new FlowQueueKey(key1.getCluster(), Flow.Status.SUCCEEDED, key1.getTimestamp(), key1.getFlowId()); service.moveFlow(key1, newKey1); FlowQueueKey newKey2 = new FlowQueueKey(key2.getCluster(), Flow.Status.SUCCEEDED, key2.getTimestamp(), key2.getFlowId()); service.moveFlow(key2, newKey2); List<Flow> succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10); assertNotNull(succeeded); assertEquals(2, succeeded.size()); // results should still be in reverse order by timestamp result1 = succeeded.get(1); assertFlowEquals(newKey1, flow1, result1); result2 = succeeded.get(0); assertFlowEquals(newKey2, flow2, result2); // add flows from a second user Flow flow3 = createFlow(service, TEST_USER2, 3); FlowQueueKey key3 = flow3.getQueueKey(); // 3rd should be the only one running running = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.RUNNING, 10); assertNotNull(running); assertEquals(1, running.size()); assertFlowEquals(key3, flow3, running.get(0)); // move flow3 to succeeded FlowQueueKey newKey3 = new FlowQueueKey(key3.getCluster(), Flow.Status.SUCCEEDED, key3.getTimestamp(), key3.getFlowId()); service.moveFlow(key3, newKey3); succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10); assertNotNull(succeeded); assertEquals(3, succeeded.size()); Flow result3 = succeeded.get(0); assertFlowEquals(newKey3, flow3, result3); // test filtering by user name succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10, TEST_USER2, null); assertNotNull(succeeded); assertEquals(1, succeeded.size()); assertFlowEquals(newKey3, flow3, succeeded.get(0)); // test pagination PaginatedResult<Flow> page1 = service.getPaginatedFlowsForStatus( TEST_CLUSTER, Flow.Status.SUCCEEDED, 1, null, null); List<Flow> pageValues = page1.getValues(); assertNotNull(pageValues); assertNotNull(page1.getNextStartRow()); assertEquals(1, pageValues.size()); assertFlowEquals(newKey3, flow3, pageValues.get(0)); // page 2 PaginatedResult<Flow> page2 = service.getPaginatedFlowsForStatus( TEST_CLUSTER, Flow.Status.SUCCEEDED, 1, null, page1.getNextStartRow()); pageValues = page2.getValues(); assertNotNull(pageValues); assertNotNull(page2.getNextStartRow()); assertEquals(1, pageValues.size()); assertFlowEquals(newKey2, flow2, pageValues.get(0)); // page 3 PaginatedResult<Flow> page3 = service.getPaginatedFlowsForStatus( TEST_CLUSTER, Flow.Status.SUCCEEDED, 1, null, page2.getNextStartRow()); pageValues = page3.getValues(); assertNotNull(pageValues); assertNull(page3.getNextStartRow()); assertEquals(1, pageValues.size()); assertFlowEquals(newKey1, flow1, pageValues.get(0)); }
#vulnerable code @Test public void testFlowQueueReadWrite() throws Exception { FlowQueueService service = new FlowQueueService(UTIL.getConfiguration()); // add a couple of test flows FlowQueueKey key1 = new FlowQueueKey(TEST_CLUSTER, Flow.Status.RUNNING, System.currentTimeMillis(), "flow1"); Flow flow1 = new Flow(null); flow1.setJobGraphJSON("{}"); flow1.setFlowName("flow1"); flow1.setUserName(TEST_USER); flow1.setProgress(10); service.updateFlow(key1, flow1); FlowQueueKey key2 = new FlowQueueKey(TEST_CLUSTER, Flow.Status.RUNNING, System.currentTimeMillis(), "flow2"); Flow flow2 = new Flow(null); flow2.setJobGraphJSON("{}"); flow2.setFlowName("flow2"); flow2.setUserName(TEST_USER); flow2.setProgress(20); service.updateFlow(key2, flow2); // read back one flow Flow flow1Retrieved = service.getFlowFromQueue(key1.getCluster(), key1.getTimestamp(), key1.getFlowId()); assertNotNull(flow1Retrieved); assertFlowEquals(key1, flow1, flow1Retrieved); // try reading both flows back List<Flow> running = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.RUNNING, 10); assertNotNull(running); assertEquals(2, running.size()); // results should be in reverse order by timestamp Flow result1 = running.get(1); assertFlowEquals(key1, flow1, result1); Flow result2 = running.get(0); assertFlowEquals(key2, flow2, result2); // move both flows to successful status FlowQueueKey newKey1 = new FlowQueueKey(key1.getCluster(), Flow.Status.SUCCEEDED, key1.getTimestamp(), key1.getFlowId()); service.moveFlow(key1, newKey1); FlowQueueKey newKey2 = new FlowQueueKey(key2.getCluster(), Flow.Status.SUCCEEDED, key2.getTimestamp(), key2.getFlowId()); service.moveFlow(key2, newKey2); List<Flow> succeeded = service.getFlowsForStatus(TEST_CLUSTER, Flow.Status.SUCCEEDED, 10); assertNotNull(succeeded); assertEquals(2, succeeded.size()); // results should still be in reverse order by timestamp result1 = succeeded.get(1); assertFlowEquals(newKey1, flow1, result1); result2 = succeeded.get(0); assertFlowEquals(newKey2, flow2, result2); } #location 49 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } String cluster = null; if (jobtracker != null) { // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization cluster = Cluster.getIdentifier(jobtracker); } return cluster; }
#vulnerable code public static String getCluster(Configuration jobConf) { String jobtracker = jobConf.get(JOBTRACKER_KEY); if (jobtracker == null) { jobtracker = jobConf.get(RESOURCE_MANAGER_KEY); } // strip any port number int portIdx = jobtracker.indexOf(':'); if (portIdx > -1) { jobtracker = jobtracker.substring(0, portIdx); } // An ExceptionInInitializerError may be thrown to indicate that an exception occurred during // evaluation of Cluster class' static initialization String cluster = Cluster.getIdentifier(jobtracker); return cluster != null ? cluster: null; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int getQSize() { int res = 0; final Actor actors[] = this.actors; for (int i = 0; i < actors.length; i++) { Actor a = actors[i]; res+=a.__mailbox.size(); res+=a.__cbQueue.size(); } return res; }
#vulnerable code public int getQSize() { int res = 0; for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; res+=queue.size(); } for (int i = 0; i < queues.length; i++) { Queue queue = cbQueues[i]; res+=queue.size(); } return res; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void rebalance(DispatcherThread dispatcherThread) { synchronized (balanceLock) { long load = dispatcherThread.getLoadNanos(); DispatcherThread minLoadThread = createNewThreadIfPossible(); if (minLoadThread != null) { // split dispatcherThread.splitTo(minLoadThread); minLoadThread.start(); return; } minLoadThread = findMinLoadThread(2 * load / 3, null); if (minLoadThread == null || minLoadThread == dispatcherThread) { // does not pay off. stay on current // System.out.println("no rebalance possible"); return; } // move cheapest actor synchronized (dispatcherThread.queueList) { ArrayList<Actor> qList = new ArrayList<>(dispatcherThread.queueList); long otherLoad = minLoadThread.getLoadNanos(); for (int i = 0; i < qList.size(); i++) { Actor actor = qList.get(i); if (otherLoad + actor.__nanos < load - actor.__nanos) { otherLoad += actor.__nanos; load -= actor.__nanos; System.out.println("move for idle " + actor.__nanos + " myload " + load + " otherlOad " + otherLoad); dispatcherThread.removeActor(actor); minLoadThread.addActor(actor); dispatcherThread.applyQueueList(); } } } } }
#vulnerable code @Override public void rebalance(DispatcherThread dispatcherThread) { int load = dispatcherThread.getLoad(); DispatcherThread minLoadThread = createNewThreadIfPossible(); if ( minLoadThread != null ) { // split dispatcherThread.splitTo(minLoadThread); minLoadThread.start(); return; } minLoadThread = findMinLoadThread(load / 4); if ( minLoadThread == null ) { // does not pay off. stay on current // System.out.println("no rebalance possible"); return; } // move cheapest actor up to half load synchronized (dispatcherThread.queueList) { long minNanos = Long.MAX_VALUE; Actor minActor = null; for (int i = 0; i < dispatcherThread.queueList.size(); i++) { Actor actor = dispatcherThread.queueList.get(i); if (actor.__nanos < minNanos) { minNanos = actor.__nanos; minActor = actor; } } if (minActor != null) { // System.out.println("move "+minActor+" from "+dispatcherThread+" to "+minLoadThread); dispatcherThread.removeActor(minActor); minLoadThread.addActor(minActor); dispatcherThread.applyQueueList(); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); }
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; } } scheduler.threadStopped(this); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int getQSize() { int res = 0; final Actor actors[] = this.actors; for (int i = 0; i < actors.length; i++) { Actor a = actors[i]; res+=a.__mailbox.size(); res+=a.__cbQueue.size(); } return res; }
#vulnerable code public int getQSize() { int res = 0; for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; res+=queue.size(); } for (int i = 0; i < queues.length; i++) { Queue queue = cbQueues[i]; res+=queue.size(); } return res; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { removeActor((Actor) poll.getTarget()); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int getLoad() { int res = 0; final Actor actors[] = this.actors; for (int i = 0; i < actors.length; i++) { MpscConcurrentQueue queue = (MpscConcurrentQueue) actors[i].__mailbox; int load = queue.size() * 100 / queue.getCapacity(); if ( load > res ) res = load; } return res; }
#vulnerable code public int getLoad() { int res = 0; for (int i = 0; i < queues.length; i++) { MpscConcurrentQueue queue = (MpscConcurrentQueue) queues[i]; int load = queue.size() * 100 / queue.getCapacity(); if ( load > res ) res = load; } return res; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isEmpty() { for (int i = 0; i < actors.length; i++) { Actor act = actors[i]; if ( ! act.__mailbox.isEmpty() || ! act.__cbQueue.isEmpty() ) return false; } return true; }
#vulnerable code public boolean isEmpty() { for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; if ( ! queue.isEmpty() ) return false; } for (int i = 0; i < cbQueues.length; i++) { Queue queue = cbQueues[i]; if ( ! queue.isEmpty() ) return false; } return true; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { int emptyCount = 0; int scheduleNewActorCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; scheduleNewActorCount++; if ( scheduleNewActorCount > 500 ) { scheduleNewActorCount = 0; schedulePendingAdds(); } } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) ) { scheduleNewActorCount = 0; schedulePendingAdds(); if ( System.currentTimeMillis()-created > 3000 ) { if ( actors.length == 0 && toAdd.peek() == null ) { shutDown(); } else { scheduler.tryStopThread(this); } } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( actors.length > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); scheduler.tryStopThread(this); i = 0; } } System.out.println("thread died"); }
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean isEmpty() { for (int i = 0; i < actors.length; i++) { Actor act = actors[i]; if ( ! act.__mailbox.isEmpty() || ! act.__cbQueue.isEmpty() ) return false; } return true; }
#vulnerable code public boolean isEmpty() { for (int i = 0; i < queues.length; i++) { Queue queue = queues[i]; if ( ! queue.isEmpty() ) return false; } for (int i = 0; i < cbQueues.length; i++) { Queue queue = cbQueues[i]; if ( ! queue.isEmpty() ) return false; } return true; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(actors); // first callback actors if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActorImmediate(actor); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { int emptyCount = 0; int scheduleNewActorCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; scheduleNewActorCount++; if ( scheduleNewActorCount > 500 ) { scheduleNewActorCount = 0; schedulePendingAdds(); } } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) ) { scheduleNewActorCount = 0; schedulePendingAdds(); if ( System.currentTimeMillis()-created > 3000 ) { if ( actors.length == 0 && toAdd.peek() == null ) { shutDown(); } else { scheduler.tryStopThread(this); } } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( actors.length > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); scheduler.tryStopThread(this); i = 0; } } System.out.println("thread died"); }
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean pollQs() { CallEntry poll = pollQueues(actors); // first callback actors if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActorImmediate(actor); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; }
#vulnerable code public boolean pollQs() { CallEntry poll = pollQueues(cbQueues, queues); // first callback queues if (poll != null) { try { Actor.sender.set(poll.getTargetActor()); Object invoke = null; profileCounter++; if ( profileCounter > nextProfile && queueList.size() > 1 && poll.getTarget() instanceof Actor ) { profileCounter = 0; invoke = profiledCall(poll); } else { invoke = poll.getMethod().invoke(poll.getTarget(), poll.getArgs()); } if (poll.getFutureCB() != null) { final Future futureCB = poll.getFutureCB(); // the future of caller side final Promise invokeResult = (Promise) invoke; // the future returned sync from call invokeResult.then( new Callback() { @Override public void receiveResult(Object result, Object error) { futureCB.receiveResult(result, error ); } } ); } return true; } catch ( Exception e) { if ( e instanceof InvocationTargetException && ((InvocationTargetException) e).getTargetException() == ActorStoppedException.Instance ) { Actor actor = (Actor) poll.getTarget(); actor.__stopped = true; removeActor(actor); applyQueueList(); return true; } if (poll.getFutureCB() != null) poll.getFutureCB().receiveResult(null, e); if (e.getCause() != null) e.getCause().printStackTrace(); else e.printStackTrace(); } } return false; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; if ( scheduler.getBackoffStrategy().isSleeping(emptyCount) && System.currentTimeMillis()-created > 3000 ) { if ( queueList.size() == 0 ) { shutDown = true; } else { scheduler.tryStopThread(this); } } } } scheduler.threadStopped(this); for ( int i = 0; i < 100; i++ ) { LockSupport.parkNanos(1000*1000*5); if ( queueList.size() > 0 ) { System.out.println("Severe: zombie dispatcher thread detected"); run(); // for now keep things going .. break; } } System.out.println("thread died"); }
#vulnerable code public void run() { int emptyCount = 0; boolean isShutDown = false; while( ! isShutDown ) { if ( pollQs() ) { emptyCount = 0; } else { emptyCount++; scheduler.yield(emptyCount); if (shutDown) // access volatile only when idle isShutDown = true; } } scheduler.threadStopped(this); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Collection<?> getSortableContainerPropertyIds() { if (backingList instanceof SortableLazyList) { // Assume SortableLazyList can sort by any Comparable property } else if (backingList instanceof LazyList) { // When using LazyList, don't support sorting by default // as the sorting should most probably be done at backend call level return Collections.emptySet(); } final ArrayList<String> props = new ArrayList<String>(); for (Object a : getContainerPropertyIds()) { String propName = a.toString(); Class<?> propType = getType(propName); if (propType != null && (propType.isPrimitive() || Comparable.class.isAssignableFrom(propType))) { props.add(propName); } } return props; }
#vulnerable code @Override public Collection<?> getSortableContainerPropertyIds() { if (backingList instanceof SortableLazyList) { // Assume SortableLazyList can sort by any Comparable property } else if (backingList instanceof LazyList) { // When using LazyList, don't support sorting by default // as the sorting should most probably be done at backend call level return Collections.emptySet(); } final ArrayList<String> props = new ArrayList<String>(); for (Object a : getContainerPropertyIds()) { DynaProperty db = getDynaClass().getDynaProperty(a.toString()); if (db != null && db.getType() != null && (db.getType(). isPrimitive() || Comparable.class.isAssignableFrom( db.getType()))) { props.add(db.getName()); } } return props; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Property getContainerProperty(Object itemId, Object propertyId) { Item i = getItem(itemId); return (i != null) ? i.getItemProperty(propertyId) : null; }
#vulnerable code @Override public Property getContainerProperty(Object itemId, Object propertyId) { return getItem(itemId).getItemProperty(propertyId); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visitIincInsn(int var, int increment) { super.visitIincInsn(var, increment); // Track variable state at variable increases (e.g. i++). LocalVariableScope lvs = getLocalVariableScope(var); instrumentToTrackVariableState(lvs, lineNumber); }
#vulnerable code @Override public void visitIincInsn(int var, int increment) { super.visitIincInsn(var, increment); // Track variable state and name at variable stores. (At variable increases.) LocalVariableScope lvs = getLocalVariableScope(var); instrumentToTrackVariableName(lvs); instrumentToTrackVariableState(lvs); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.