instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rendersHomePage() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String uid = "yegor256"; new Awards(farm, uid).bootstrap().add(1, "gh:test/test#1", "reason"); new Agenda(farm, uid).bootstrap().add("gh:test/test#2", "QA"); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new TkApp(farm).act( new RqWithUser( farm, new RqFake("GET", "/u/Yegor256") ) ) ).printBody() ), XhtmlMatchers.hasXPaths("//xhtml:body") ); }
#vulnerable code @Test public void rendersHomePage() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String uid = "yegor256"; final People people = new People(farm).bootstrap(); people.touch(uid); people.invite(uid, "mentor"); new Awards(farm, uid).bootstrap().add(1, "gh:test/test#1", "reason"); new Agenda(farm, uid).bootstrap().add("gh:test/test#2", "QA"); final String pid = "9A0007788"; new Projects(farm, uid).bootstrap().add(pid); new Catalog(farm).bootstrap().add(pid, "2018/01/9A0007788/"); final Take take = new TkApp(farm); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( take.act( new RqWithHeaders( new RqFake("GET", "/u/Yegor256"), // @checkstyle LineLength (1 line) "Cookie: PsCookie=0975A5A5-F6DB193E-AF18000A-75726E3A-74657374-3A310005-6C6F6769-6E000879-65676F72-323536AE" ) ) ).printBody() ), XhtmlMatchers.hasXPaths("//xhtml:body") ); } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rendersDebts() throws Exception { final Farm farm = FkFarm.props(); final Debts debts = new Debts(farm).bootstrap(); final String uid = "yegor256"; final String first = "details 1"; final String second = "details 2"; final String price = "$9.99"; final String amount = "$3.33"; final String reason = "reason"; debts.add(uid, new Cash.S(price), first, reason); debts.add(uid, new Cash.S(amount), second, reason); final String html = new View(farm, String.format("/u/%s", uid)).html(); MatcherAssert.assertThat( html, Matchers.allOf( XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", first, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", second, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", price).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", amount).asString() ) ) ); }
#vulnerable code @Test public void rendersDebts() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final Debts debts = new Debts(farm).bootstrap(); final String uid = "yegor256"; final String first = "details 1"; final String second = "details 2"; final String price = "$9.99"; final String amount = "$3.33"; final String reason = "reason"; debts.add(uid, new Cash.S(price), first, reason); debts.add(uid, new Cash.S(amount), second, reason); final String html = new View(farm, String.format("/u/%s", uid)).html(); MatcherAssert.assertThat( html, Matchers.allOf( XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", first, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", second, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", price).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", amount).asString() ) ) ); } #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 rendersWithoutChromeNotice() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String get = new RsPrint( new TkApp(farm).act( new RqWithUser.WithInit( farm, new RqFake( "GET", "/a/C00000000?a=pm/staff/roles" ) ) ) ).printBody(); MatcherAssert.assertThat( get, Matchers.not(Matchers.containsString("Chrome")) ); }
#vulnerable code @Test public void rendersWithoutChromeNotice() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String get = new RsPrint( new TkApp(farm).act( new RqWithUser( farm, new RqFake( "GET", "/a/C00000000?a=pm/staff/roles" ) ) ) ).printBody(); MatcherAssert.assertThat( get, Matchers.not(Matchers.containsString("Chrome")) ); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void givesNoBonus() throws Exception { final Speed speed = new Speed( new FkFarm(new FkProject()), "other" ).bootstrap(); final String job = "gh:bonus/slow#1"; speed.add("TST100009", job, Duration.ofDays(Tv.THREE).toMinutes()); MatcherAssert.assertThat(speed.bonus(job), Matchers.equalTo(0)); }
#vulnerable code @Test public void givesNoBonus() throws Exception { final FkProject project = new FkProject(); final FkFarm farm = new FkFarm(project); final Speed speed = new Speed(farm, "other").bootstrap(); final String job = "gh:bonus/slow#1"; speed.add("TST100009", job, Tv.THREE * Tv.THOUSAND); MatcherAssert.assertThat(speed.bonus(job), Matchers.equalTo(0)); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean applied(final String uid) throws IOException { this.checkExisting(uid); try (final Item item = this.item()) { return !new Xocument(item).nodes( String.format("//people/person[@id ='%s']/applied", uid) ).isEmpty(); } }
#vulnerable code public boolean applied(final String uid) throws IOException { if (!this.exists(uid)) { throw new IllegalArgumentException( new Par("Person @%s doesn't exist").say(uid) ); } try (final Item item = this.item()) { return !new Xocument(item).nodes( String.format("//people/person[@id ='%s']/applied", uid) ).isEmpty(); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @SuppressWarnings("unchecked") public void showsThatUserAlreadyHasMentor() throws IOException { final Farm farm = new PropsFarm(new FkFarm()); final People people = new People(farm).bootstrap(); final String mentor = "yoda"; final String applicant = "luke"; people.touch(mentor); people.touch(applicant); people.invite(applicant, mentor, true); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( new RqWithUser( farm, new RqFake("GET", "/join-post"), applicant ), "personality=INTJ-A&stackoverflow=187242" ) ), Matchers.allOf( new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER), new HmRsHeader("Location", "/join"), new HmRsHeader( "Set-Cookie", Matchers.hasItems( Matchers.containsString( URLEncoder.encode( new FormattedText( "You already have a mentor (@%s)", mentor ).asString(), StandardCharsets.UTF_8.displayName() ) ) ) ) ) ); }
#vulnerable code @Test @SuppressWarnings("unchecked") public void showsThatUserAlreadyHasMentor() throws IOException { final Farm farm = FkFarm.props(); final People people = new People(farm).bootstrap(); final String mentor = "yoda"; final String applicant = "luke"; people.touch(mentor); people.touch(applicant); people.invite(applicant, mentor, true); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( new RqWithUser( farm, new RqFake("GET", "/join-post"), applicant ), "personality=INTJ-A&stackoverflow=187242" ) ), Matchers.allOf( new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER), new HmRsHeader("Location", "/join"), new HmRsHeader( "Set-Cookie", Matchers.hasItems( Matchers.containsString( URLEncoder.encode( new FormattedText( "You already have a mentor (@%s)", mentor ).asString(), StandardCharsets.UTF_8.displayName() ) ) ) ) ) ); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rendersProfilePageWithoutRateInFirefox() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String uid = "yegor256"; MatcherAssert.assertThat( new View(farm, String.format("/u/%s", uid)).html(), Matchers.containsString("rate</a> is not defined") ); }
#vulnerable code @Test public void rendersProfilePageWithoutRateInFirefox() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final People people = new People(farm).bootstrap(); final String uid = "yegor256"; people.wallet( uid, "test123" ); MatcherAssert.assertThat( new View(farm, String.format("/u/%s", uid)).html(), Matchers.containsString("rate</a> is not defined") ); } #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 rendersHomePage() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new TkApp(farm).act( new RqWithUser.WithInit( farm, new RqFake( "GET", "/a/C00000000?a=pm/staff/roles" ) ) ) ).printBody() ), XhtmlMatchers.hasXPaths("//xhtml:table") ); }
#vulnerable code @Test public void rendersHomePage() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new TkApp(farm).act( new RqWithUser( farm, new RqFake( "GET", "/a/C00000000?a=pm/staff/roles" ) ) ) ).printBody() ), XhtmlMatchers.hasXPaths("//xhtml:table") ); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void speed(final String uid, final double speed) throws IOException { this.checkExisting(uid); try (final Item item = this.item()) { new Xocument(item.path()).modify( new Directives().xpath( String.format( "/people/person[@id='%s']", uid ) ).addIf("speed").set(speed) ); } }
#vulnerable code public void speed(final String uid, final double speed) throws IOException { if (!this.exists(uid)) { throw new IllegalArgumentException( new Par("Person @%s doesn't exist").say(uid) ); } try (final Item item = this.item()) { new Xocument(item.path()).modify( new Directives().xpath( String.format( "/people/person[@id='%s']", uid ) ).addIf("speed").set(speed) ); } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void setsEstimatesOnAssign() throws Exception { final Project project = new FkProject(); final PropsFarm farm = new PropsFarm(); new Ledger(farm, project).bootstrap().add( new Ledger.Transaction( new Cash.S("$1000"), "assets", "cash", "income", "sponsor", "There is some funding just arrived" ) ); final String login = "dmarkov"; new Rates(project).bootstrap().set(login, new Cash.S("$50")); final String job = "gh:yegor256/0pdd#19"; final Wbs wbs = new Wbs(project).bootstrap(); wbs.add(job); wbs.role(job, "REV"); final Orders orders = new Orders(farm, project).bootstrap(); orders.assign(job, login, UUID.randomUUID().toString()); MatcherAssert.assertThat( new Estimates(farm, project).bootstrap().get(job), Matchers.equalTo(new Cash.S("$12.50")) ); }
#vulnerable code @Test public void setsEstimatesOnAssign() throws Exception { final Project project = new FkProject(); final PropsFarm farm = new PropsFarm(); new Ledger(farm, project).bootstrap().add( new Ledger.Transaction( new Cash.S("$1000"), "assets", "cash", "income", "sponsor", "There is some funding just arrived" ) ); final String login = "dmarkov"; new Rates(project).bootstrap().set(login, new Cash.S("$50")); final String job = "gh:yegor256/0pdd#19"; final Wbs wbs = new Wbs(project).bootstrap(); wbs.add(job); wbs.role(job, "REV"); final Orders orders = new Orders(farm, project).bootstrap(); orders.assign(job, login, "0"); MatcherAssert.assertThat( new Estimates(farm, project).bootstrap().get(job), Matchers.equalTo(new Cash.S("$12.50")) ); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rendersHomePageViaHttp() throws Exception { final Take app = new TkApp(FkFarm.props()); new FtRemote(app).exec( home -> new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .assertXPath("/xhtml:html/xhtml:body") ); }
#vulnerable code @Test public void rendersHomePageViaHttp() throws Exception { final Take app = new TkApp(new PropsFarm(new FkFarm())); new FtRemote(app).exec( home -> new JdkRequest(home) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .assertXPath("/xhtml:html/xhtml:body") ); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void redirectOnError() throws Exception { final Take take = new TkApp(FkFarm.props()); final String message = "Internal application error"; MatcherAssert.assertThat( "Could not redirect on error", new TextOf( take.act(new RqFake("GET", "/?PsByFlag=PsGithub")).body() ).asString(), new IsNot<>( new StringContains(message) ) ); MatcherAssert.assertThat( "Could not redirect on error (with code)", new TextOf( take.act( new RqFake( "GET", "/?PsByFlag=PsGithub&code=1257b773ba07221e7eb5" ) ).body() ).asString(), new IsNot<>( new StringContains(message) ) ); }
#vulnerable code @Test @Ignore public void redirectOnError() throws Exception { final Take take = new TkApp(new PropsFarm(new FkFarm())); final String message = "Internal application error"; MatcherAssert.assertThat( "Could not redirect on error", new TextOf( take.act(new RqFake("GET", "/?PsByFlag=PsGithub")).body() ).asString(), new IsNot<>( new StringContains(message) ) ); MatcherAssert.assertThat( "Could not redirect on error (with code)", new TextOf( take.act( new RqFake( "GET", "/?PsByFlag=PsGithub&code=1257b773ba07221e7eb5" ) ).body() ).asString(), new IsNot<>( new StringContains(message) ) ); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rendersProfilePageInFirefoxWithReputation() throws Exception { final Farm farm = FkFarm.props(); final String user = "yegor256"; MatcherAssert.assertThat( new View(farm, String.format("/u/%s", user)).html(), XhtmlMatchers.hasXPath( String.format( "//xhtml:a[@href='https://github.com/%s']", user ) ) ); }
#vulnerable code @Test public void rendersProfilePageInFirefoxWithReputation() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final String user = "yegor256"; MatcherAssert.assertThat( new View(farm, String.format("/u/%s", user)).html(), XhtmlMatchers.hasXPath( String.format( "//xhtml:a[@href='https://github.com/%s']", user ) ) ); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void votesHighIfMaxJobsReached() throws Exception { final Project project = new FkProject(); final String user = "g4s8"; final int total = 10; final Pmo pmo = new Pmo(new FkFarm()); new Options(pmo, user).bootstrap().maxJobsInAgenda(total); final Agenda agenda = new Agenda(pmo, user).bootstrap(); for (int num = 0; num < total; ++num) { agenda.add(project, String.format("gh:test/test#%d", num), "DEV"); } MatcherAssert.assertThat( new VsOptionsMaxJobs(pmo).take(user, new StringBuilder(0)), // @checkstyle MagicNumberCheck (1 lines) Matchers.closeTo(1.0, 0.001) ); }
#vulnerable code @Test public void votesHighIfMaxJobsReached() throws Exception { final Project project = new FkProject(); final FkFarm farm = new FkFarm(); final String user = "g4s8"; final int total = 10; final Pmo pmo = new Pmo(farm); new Options(pmo, user).bootstrap().maxJobsInAgenda(total); final Agenda agenda = new Agenda(pmo, user).bootstrap(); for (int num = 0; num < total; ++num) { agenda.add(project, String.format("gh:test/test#%d", num), "DEV"); } MatcherAssert.assertThat( new VsOptionsMaxJobs(pmo).take(user, new StringBuilder(0)), // @checkstyle MagicNumberCheck (1 lines) Matchers.closeTo(1.0, 0.001) ); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Input pdf(final String login) throws IOException { final double share = this.share(login); if (share == 0.0d) { throw new IllegalArgumentException( new Par( "@%s doesn't have any share in %s" ).say(login, this.project.pid()) ); } try (final Item item = this.item()) { final Xocument doc = new Xocument(item); String latex = new TextOf( new ResourceOf("com/zerocracy/pm/cost/equity.tex") ).asString(); latex = latex .replace("[OWNER]", login) .replace("[ENTITY]", doc.xpath("//entity/text()", "PROJECT")) .replace("[ADDRESS]", doc.xpath("//address/text()", "USA")) .replace("[CEO]", doc.xpath("//ceo/text()", "CEO")) .replace("[SHARE]", String.format("%.2f", share)) .replace("[SHARES]", String.format("%.0f", this.shares())) .replace("[PAR]", this.par().toString()); return new Latex(latex).pdf(); } }
#vulnerable code public Input pdf(final String login) throws IOException { final double share = this.share(login); if (share == 0.0d) { throw new IllegalArgumentException( new Par( "@%s doesn't have any share in %s" ).say(login, this.project.pid()) ); } try (final Item item = this.item()) { final Xocument doc = new Xocument(item); String latex = new TextOf( new ResourceOf("com/zerocracy/pm/cost/equity.tex") ).asString(); latex = latex .replace("[OWNER]", login) .replace("[ENTITY]", doc.xpath("//entity/text()", "PROJECT")) .replace("[CEO]", doc.xpath("//ceo/text()", "CEO")) .replace("[SHARE]", String.format("%.2f", share)) .replace("[SHARES]", String.format("%.0f", this.shares())) .replace("[PAR]", this.par().toString()); return new Latex(latex).pdf(); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void exec() throws IOException { final Properties props = new Properties(); try (final InputStream input = this.getClass().getResourceAsStream("/main.properties")) { props.load(input); } final Github github = new RtGithub( props.getProperty("github.0crat.login"), props.getProperty("github.0crat.password") ); final Map<String, SlackSession> sessions = new ConcurrentHashMap<>(0); final Farm farm = new PingFarm( new ReactiveFarm( new SyncFarm( new S3Farm( new Region.Simple( props.getProperty("s3.key"), props.getProperty("s3.secret") ).bucket(props.getProperty("s3.bucket")) ) ), Stream.of( new StkNotify(github), new com.zerocracy.radars.slack.StkNotify(sessions), new StkAdd(github), new StkRemove(), new StkShow(), new StkParent(), new StkSet(), new com.zerocracy.stk.pmo.profile.rate.StkShow(), new com.zerocracy.stk.pmo.profile.wallet.StkSet(), new com.zerocracy.stk.pmo.profile.wallet.StkShow(), new com.zerocracy.stk.pmo.profile.skills.StkAdd(), new com.zerocracy.stk.pmo.profile.skills.StkShow(), new com.zerocracy.stk.pmo.profile.aliases.StkShow() ).map(StkSafe::new).collect(Collectors.toList()) ) ); final GithubRadar ghradar = Main.ghradar(farm, github); final SlackRadar skradar = Main.skradar(farm, props, sessions); try (final Radar chain = new Radar.Chain(ghradar, skradar)) { final GhookRadar gkradar = Main.gkradar(farm, github); chain.start(); new FtCli( new TkApp( props, new FkRegex("/slack", skradar), new FkRegex("/alias", new TkAlias(farm)), new FkRegex("/ghook", gkradar) ), this.arguments ).start(Exit.NEVER); } }
#vulnerable code public void exec() throws IOException { final Properties props = new Properties(); try (final InputStream input = this.getClass().getResourceAsStream("/main.properties")) { props.load(input); } final Github github = new RtGithub( props.getProperty("github.0crat.login"), props.getProperty("github.0crat.password") ); final Map<String, SlackSession> sessions = new ConcurrentHashMap<>(0); final Farm farm = new PingFarm( new ReactiveFarm( new SyncFarm( new S3Farm( new Region.Simple( props.getProperty("s3.key"), props.getProperty("s3.secret") ).bucket(props.getProperty("s3.bucket")) ) ), Arrays.asList( new StkNotify(github), new com.zerocracy.radars.slack.StkNotify(sessions), new StkAdd(github), new StkRemove(), new StkShow(), new StkParent(), new StkSet(), new com.zerocracy.stk.pmo.profile.rate.StkShow(), new com.zerocracy.stk.pmo.profile.wallet.StkSet(), new com.zerocracy.stk.pmo.profile.wallet.StkShow(), new com.zerocracy.stk.pmo.profile.skills.StkAdd(), new com.zerocracy.stk.pmo.profile.skills.StkShow(), new com.zerocracy.stk.pmo.profile.aliases.StkShow() ) ) ); final GithubRadar ghradar = Main.ghradar(farm, github); final SlackRadar skradar = Main.skradar(farm, props, sessions); try (final Radar chain = new Radar.Chain(ghradar, skradar)) { final GhookRadar gkradar = Main.gkradar(farm, github); chain.start(); new FtCli( new TkApp( props, new FkRegex("/slack", skradar), new FkRegex("/alias", new TkAlias(farm)), new FkRegex("/ghook", gkradar) ), this.arguments ).start(Exit.NEVER); } } #location 41 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @SuppressWarnings("unchecked") public void showsThatUserAlreadyHasMentor() throws IOException { final Farm farm = FkFarm.props(); final People people = new People(farm).bootstrap(); final String mentor = "yoda"; final String applicant = "luke"; people.touch(mentor); people.touch(applicant); people.invite(applicant, mentor, true); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( new RqWithUser( farm, new RqFake("GET", "/join-post"), applicant ), "personality=INTJ-A&stackoverflow=187242" ) ), Matchers.allOf( new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER), new HmRsHeader("Location", "/join"), new HmRsHeader( "Set-Cookie", Matchers.hasItems( Matchers.containsString( URLEncoder.encode( new FormattedText( "You already have a mentor (@%s)", mentor ).asString(), StandardCharsets.UTF_8.displayName() ) ) ) ) ) ); }
#vulnerable code @Test @SuppressWarnings("unchecked") public void showsThatUserAlreadyHasMentor() throws IOException { final Farm farm = new PropsFarm(new FkFarm()); final People people = new People(farm).bootstrap(); final String mentor = "yoda"; final String applicant = "luke"; people.touch(mentor); people.touch(applicant); people.invite(applicant, mentor, true); MatcherAssert.assertThat( new TkApp(farm).act( new RqWithBody( new RqWithUser( farm, new RqFake("GET", "/join-post"), applicant ), "personality=INTJ-A&stackoverflow=187242" ) ), Matchers.allOf( new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER), new HmRsHeader("Location", "/join"), new HmRsHeader( "Set-Cookie", Matchers.hasItems( Matchers.containsString( URLEncoder.encode( new FormattedText( "You already have a mentor (@%s)", mentor ).asString(), StandardCharsets.UTF_8.displayName() ) ) ) ) ) ); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void parsesJson() throws Exception { MatcherAssert.assertThat( new TkGithub( new PropsFarm(), new Rebound.Fake("nothing") ).act( new RqWithBody( new RqFake("POST", "/"), String.format( "payload=%s", URLEncoder.encode( "{\"foo\": \"bar\"}", StandardCharsets.UTF_8.displayName() ) ) ) ), new HmRsStatus(HttpURLConnection.HTTP_OK) ); }
#vulnerable code @Test public void parsesJson() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final Take take = new TkGithub( farm, (frm, github, event) -> "nothing" ); MatcherAssert.assertThat( take.act( new RqWithBody( new RqFake("POST", "/"), String.format( "payload=%s", URLEncoder.encode( "{\"foo\": \"bar\"}", StandardCharsets.UTF_8.displayName() ) ) ) ), new HmRsStatus(HttpURLConnection.HTTP_OK) ); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void payZold() throws Exception { final Farm farm = new PropsFarm(); final String target = "yegor256"; new Roles(new Pmo(farm)).bootstrap().assign(target, "PO"); MatcherAssert.assertThat( new Zold(farm).pay( target, new Cash.S("$0.01"), "ZoldITCase#payZold", "none" ), Matchers.not(Matchers.isEmptyString()) ); }
#vulnerable code @Test public void payZold() throws Exception { MatcherAssert.assertThat( new Zold(new PropsFarm()).pay( "yegor256", new Cash.S("$0.01"), "ZoldITCase#payZold", "none" ), Matchers.not(Matchers.isEmptyString()) ); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void setsEstimatesOnAssign() throws Exception { final Project project = new FkProject(); final PropsFarm farm = new PropsFarm(); new Ledger(farm, project).bootstrap().add( new Ledger.Transaction( new Cash.S("$1000"), "assets", "cash", "income", "sponsor", "There is some funding just arrived" ) ); final String login = "dmarkov"; new Rates(project).bootstrap().set(login, new Cash.S("$50")); final String job = "gh:yegor256/0pdd#19"; final Wbs wbs = new Wbs(project).bootstrap(); wbs.add(job); wbs.role(job, "REV"); final Orders orders = new Orders(farm, project).bootstrap(); orders.assign(job, login, UUID.randomUUID().toString()); MatcherAssert.assertThat( new Estimates(farm, project).bootstrap().get(job), Matchers.equalTo(new Cash.S("$12.50")) ); }
#vulnerable code @Test public void setsEstimatesOnAssign() throws Exception { final Project project = new FkProject(); final PropsFarm farm = new PropsFarm(); new Ledger(farm, project).bootstrap().add( new Ledger.Transaction( new Cash.S("$1000"), "assets", "cash", "income", "sponsor", "There is some funding just arrived" ) ); final String login = "dmarkov"; new Rates(project).bootstrap().set(login, new Cash.S("$50")); final String job = "gh:yegor256/0pdd#19"; final Wbs wbs = new Wbs(project).bootstrap(); wbs.add(job); wbs.role(job, "REV"); final Orders orders = new Orders(farm, project).bootstrap(); orders.assign(job, login, "0"); MatcherAssert.assertThat( new Estimates(farm, project).bootstrap().get(job), Matchers.equalTo(new Cash.S("$12.50")) ); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Dependency> dependencies(final Resource resource, final Properties properties) { if ("true".equals(properties.getProperty("computed", "false"))) { log.info("Dependencies are pre-computed in properties"); Model model = new Model(); model = ThinPropertiesModelProcessor.process(model, properties); return aetherDependencies(model.getDependencies(), properties); } initialize(); try { log.info("Computing dependencies from pom and properties"); ProjectBuildingRequest request = getProjectBuildingRequest(properties); request.setResolveDependencies(true); synchronized (DependencyResolver.class) { ProjectBuildingResult result = projectBuilder .build(new PropertiesModelSource(properties, resource), request); DependencyResolver.globals = null; DependencyResolutionResult dependencies = result .getDependencyResolutionResult(); if (!dependencies.getUnresolvedDependencies().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Dependency dependency : dependencies .getUnresolvedDependencies()) { List<Exception> errors = dependencies .getResolutionErrors(dependency); for (Exception exception : errors) { if (builder.length() > 0) { builder.append("\n"); } builder.append(exception.getMessage()); } } throw new RuntimeException(builder.toString()); } List<Dependency> output = runtime(dependencies.getDependencies()); if (log.isInfoEnabled()) { for (Dependency dependency : output) { log.info("Resolved: " + coordinates(dependency) + "=" + dependency.getArtifact().getFile()); } } return output; } } catch (ProjectBuildingException | NoLocalRepositoryManagerException e) { throw new IllegalStateException("Cannot build model", e); } }
#vulnerable code public List<Dependency> dependencies(final Resource resource, final Properties properties) { if ("true".equals(properties.getProperty("computed", "false"))) { log.info("Dependencies are pre-computed in properties"); Model model = new Model(); model = ThinPropertiesModelProcessor.process(model, properties); return aetherDependencies(model.getDependencies()); } initialize(); try { log.info("Computing dependencies from pom and properties"); ProjectBuildingRequest request = getProjectBuildingRequest(properties); request.setResolveDependencies(true); synchronized (DependencyResolver.class) { ProjectBuildingResult result = projectBuilder .build(new PropertiesModelSource(properties, resource), request); DependencyResolver.globals = null; DependencyResolutionResult dependencies = result .getDependencyResolutionResult(); if (!dependencies.getUnresolvedDependencies().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Dependency dependency : dependencies .getUnresolvedDependencies()) { List<Exception> errors = dependencies .getResolutionErrors(dependency); for (Exception exception : errors) { if (builder.length() > 0) { builder.append("\n"); } builder.append(exception.getMessage()); } } throw new RuntimeException(builder.toString()); } List<Dependency> output = runtime(dependencies.getDependencies()); if (log.isInfoEnabled()) { for (Dependency dependency : output) { log.info("Resolved: " + coordinates(dependency) + "=" + dependency.getArtifact().getFile()); } } return output; } } catch (ProjectBuildingException | NoLocalRepositoryManagerException e) { throw new IllegalStateException("Cannot build model", e); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static Model process(Model model, Properties properties) { if (properties != null) { Set<String> exclusions = new HashSet<>(); for (String name : properties.stringPropertyNames()) { if (name.startsWith("boms.")) { String bom = properties.getProperty(name); DefaultArtifact artifact = artifact(bom); if (model.getDependencyManagement() == null) { model.setDependencyManagement(new DependencyManagement()); } boolean replaced = false; for (Dependency dependency : model.getDependencyManagement() .getDependencies()) { if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(), dependency.getArtifactId()) && ObjectUtils.nullSafeEquals(artifact.getGroupId(), dependency.getGroupId())) { dependency.setVersion(artifact.getVersion()); } } if (isParentBom(model, artifact)) { model.getParent().setVersion(artifact.getVersion()); replaced = true; } if (!replaced) { model.getDependencyManagement().addDependency(bom(artifact)); } } else if (name.startsWith("dependencies.")) { String pom = properties.getProperty(name); DefaultArtifact artifact = artifact(pom); boolean replaced = false; for (Dependency dependency : model.getDependencies()) { if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(), dependency.getArtifactId()) && ObjectUtils.nullSafeEquals(artifact.getGroupId(), dependency.getGroupId()) && artifact.getVersion() != null) { dependency.setVersion( StringUtils.hasLength(artifact.getVersion()) ? artifact.getVersion() : null); dependency.setScope("runtime"); replaced = true; } } if (!replaced) { model.getDependencies().add(dependency(artifact)); } } else if (name.startsWith("exclusions.")) { String pom = properties.getProperty(name); exclusions.add(pom); } } for (String pom : exclusions) { Exclusion exclusion = exclusion(pom); Dependency target = dependency(artifact(pom)); Dependency excluded = null; for (Dependency dependency : model.getDependencies()) { dependency.addExclusion(exclusion); if (dependency.getGroupId().equals(target.getGroupId()) && dependency .getArtifactId().equals(target.getArtifactId())) { excluded = dependency; } } if (excluded != null) { model.getDependencies().remove(excluded); } } } for (Dependency dependency : new ArrayList<>(model.getDependencies())) { if ("test".equals(dependency.getScope()) || "provided".equals(dependency.getScope())) { model.getDependencies().remove(dependency); } } return model; }
#vulnerable code static Model process(Model model, Properties properties) { if (properties != null) { Set<String> exclusions = new HashSet<>(); for (String name : properties.stringPropertyNames()) { if (name.startsWith("boms.")) { String bom = properties.getProperty(name); DefaultArtifact artifact = artifact(bom); if (model.getDependencyManagement() == null) { model.setDependencyManagement(new DependencyManagement()); } boolean replaced = false; for (Dependency dependency : model.getDependencyManagement() .getDependencies()) { if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(), dependency.getArtifactId()) && ObjectUtils.nullSafeEquals(artifact.getGroupId(), dependency.getGroupId())) { dependency.setVersion(artifact.getVersion()); } } if (isParentBom(model, artifact)) { model.getParent().setVersion(artifact.getVersion()); replaced = true; } if (!replaced) { model.getDependencyManagement().addDependency(bom(artifact)); } } else if (name.startsWith("dependencies.")) { String pom = properties.getProperty(name); DefaultArtifact artifact = artifact(pom); boolean replaced = false; for (Dependency dependency : model.getDependencies()) { if (ObjectUtils.nullSafeEquals(artifact.getArtifactId(), dependency.getArtifactId()) && ObjectUtils.nullSafeEquals(artifact.getGroupId(), dependency.getGroupId()) && artifact.getVersion() != null) { dependency.setVersion( StringUtils.hasLength(artifact.getVersion()) ? artifact.getVersion() : null); dependency.setScope("runtime"); replaced = true; } } if (!replaced) { model.getDependencies().add(dependency(artifact)); } } else if (name.startsWith("exclusions.")) { String pom = properties.getProperty(name); exclusions.add(pom); } } for (String pom : exclusions) { Exclusion exclusion = exclusion(pom); Dependency target = dependency(artifact(pom)); Dependency excluded = null; for (Dependency dependency : model.getDependencies()) { dependency.addExclusion(exclusion); if (dependency.getGroupId().equals(target.getGroupId()) && dependency .getArtifactId().equals(target.getArtifactId())) { excluded = dependency; } } if (excluded != null) { model.getDependencies().remove(excluded); } } } return model; } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Dependency> dependencies(final Resource resource, final Properties properties) { if ("true".equals(properties.getProperty("computed", "false"))) { log.info("Dependencies are pre-computed in properties"); Model model = new Model(); model = ThinPropertiesModelProcessor.process(model, properties); return aetherDependencies(model.getDependencies(), properties); } initialize(); try { log.info("Computing dependencies from pom and properties"); ProjectBuildingRequest request = getProjectBuildingRequest(properties); request.setResolveDependencies(true); synchronized (DependencyResolver.class) { ProjectBuildingResult result = projectBuilder .build(new PropertiesModelSource(properties, resource), request); DependencyResolver.globals = null; DependencyResolutionResult dependencies = result .getDependencyResolutionResult(); if (!dependencies.getUnresolvedDependencies().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Dependency dependency : dependencies .getUnresolvedDependencies()) { List<Exception> errors = dependencies .getResolutionErrors(dependency); for (Exception exception : errors) { if (builder.length() > 0) { builder.append("\n"); } builder.append(exception.getMessage()); } } throw new RuntimeException(builder.toString()); } List<Dependency> output = runtime(dependencies.getDependencies()); if (log.isInfoEnabled()) { for (Dependency dependency : output) { log.info("Resolved: " + coordinates(dependency) + "=" + dependency.getArtifact().getFile()); } } return output; } } catch (ProjectBuildingException | NoLocalRepositoryManagerException e) { throw new IllegalStateException("Cannot build model", e); } }
#vulnerable code public List<Dependency> dependencies(final Resource resource, final Properties properties) { if ("true".equals(properties.getProperty("computed", "false"))) { log.info("Dependencies are pre-computed in properties"); Model model = new Model(); model = ThinPropertiesModelProcessor.process(model, properties); return aetherDependencies(model.getDependencies()); } initialize(); try { log.info("Computing dependencies from pom and properties"); ProjectBuildingRequest request = getProjectBuildingRequest(properties); request.setResolveDependencies(true); synchronized (DependencyResolver.class) { ProjectBuildingResult result = projectBuilder .build(new PropertiesModelSource(properties, resource), request); DependencyResolver.globals = null; DependencyResolutionResult dependencies = result .getDependencyResolutionResult(); if (!dependencies.getUnresolvedDependencies().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Dependency dependency : dependencies .getUnresolvedDependencies()) { List<Exception> errors = dependencies .getResolutionErrors(dependency); for (Exception exception : errors) { if (builder.length() > 0) { builder.append("\n"); } builder.append(exception.getMessage()); } } throw new RuntimeException(builder.toString()); } List<Dependency> output = runtime(dependencies.getDependencies()); if (log.isInfoEnabled()) { for (Dependency dependency : output) { log.info("Resolved: " + coordinates(dependency) + "=" + dependency.getArtifact().getFile()); } } return output; } } catch (ProjectBuildingException | NoLocalRepositoryManagerException e) { throw new IllegalStateException("Cannot build model", e); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code void findKBest(int k, PriorityQueue<Pair> heap, Vector hidden, Vector output) { computeOutputSoftmax(hidden, output); for (int i = 0; i < osz_; i++) { if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { continue; } heap.add(new Pair(output.data_[i], i)); if (heap.size() > k) { heap.remove(); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float negativeSampling(int target, float lr) { float loss = 0.0f; grad_.zero(); for (int n = 0; n <= args_.neg; n++) { if (n == 0) { loss += binaryLogistic(target, true, lr); } else { loss += binaryLogistic(getNegative(target), false, lr); } } return loss; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code int getNegative(int target) { int negative; do { negative = negatives.get(negpos); negpos = (negpos + 1) % negatives.size(); } while (target == negative); return negative; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setInfo() { setLevel(Level.INFO); }
#vulnerable code public static void setInfo() { setLevel(Level.INFO); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float negativeSampling(int target, float lr) { float loss = 0.0f; grad_.zero(); for (int n = 0; n <= args_.neg; n++) { if (n == 0) { loss += binaryLogistic(target, true, lr); } else { loss += binaryLogistic(getNegative(target), false, lr); } } return loss; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code void update(int[] input, int target, float lr) { assert (target >= 0); assert (target < osz_); if (input.length == 0) return; computeHidden(input, hidden_); if (args_.loss == Args.loss_name.ns) { loss_ += negativeSampling(target, lr); } else if (args_.loss == Args.loss_name.hs) { loss_ += hierarchicalSoftmax(target, lr); } else { loss_ += softmax(target, lr); } nexamples_ += 1; if (args_.model == Args.model_name.sup) { grad_.mul(1.0f / input.length); } synchronized (this) { for (int i : input) { wi_.addRow(grad_, i, 1.0f); } } } #location 20 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float negativeSampling(int target, float lr) { float loss = 0.0f; grad_.zero(); for (int n = 0; n <= args_.neg; n++) { if (n == 0) { loss += binaryLogistic(target, true, lr); } else { loss += binaryLogistic(getNegative(target), false, lr); } } return loss; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float softmax(int target, float lr) { grad_.zero(); computeOutputSoftmax(); for (int i = 0; i < osz_; i++) { float label = (i == target) ? 1.0f : 0.0f; float alpha = lr * (label - output_.data_[i]); grad_.addRow(wo_, i, alpha); synchronized (this) { wo_.addRow(hidden_, i, alpha); } } return -log(output_.data_[target]); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code void update(int[] input, int target, float lr) { assert (target >= 0); assert (target < osz_); if (input.length == 0) return; computeHidden(input, hidden_); if (args_.loss == Args.loss_name.ns) { loss_ += negativeSampling(target, lr); } else if (args_.loss == Args.loss_name.hs) { loss_ += hierarchicalSoftmax(target, lr); } else { loss_ += softmax(target, lr); } nexamples_ += 1; if (args_.model == Args.model_name.sup) { grad_.mul(1.0f / input.length); } synchronized (this) { for (int i : input) { wi_.addRow(grad_, i, 1.0f); } } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float getLoss() { return loss_ / nexamples_; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code void update(int[] input, int target, float lr) { assert (target >= 0); assert (target < osz_); if (input.length == 0) return; computeHidden(input, hidden_); if (args_.loss == Args.loss_name.ns) { loss_ += negativeSampling(target, lr); } else if (args_.loss == Args.loss_name.hs) { loss_ += hierarchicalSoftmax(target, lr); } else { loss_ += softmax(target, lr); } nexamples_ += 1; if (args_.model == Args.model_name.sup) { grad_.mul(1.0f / input.length); } synchronized (this) { for (int i : input) { wi_.addRow(grad_, i, 1.0f); } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float binaryLogistic(int target, boolean label, float lr) { float score = sigmoid(wo_.dotRow(hidden_, target)); float alpha = lr * (label ? 1f : 0f - score); grad_.addRow(wo_, target, alpha); synchronized (this) { wo_.addRow(hidden_, target, alpha); } if (label) { return -log(score); } else { return -log(1.0f - score); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code List<Pair> predict(int[] input, int k, Vector hidden, Vector output) { assert (k > 0); computeHidden(input, hidden); PriorityQueue<Pair> heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR); if (args_.loss == Args.loss_name.hs) { dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); } else { findKBest(k, heap, hidden, output); } List<Pair> result = new ArrayList<>(heap); Collections.sort(result); return result; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2)); String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2)); String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2)); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); }
#vulnerable code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim(); String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim(); String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim(); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code void computeHidden(int[] input, Vector hidden) { assert (hidden.size() == hsz_); hidden.zero(); for (int i : input) { hidden.addRow(wi_, i); } hidden.mul(1.0f / input.length); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code List<Pair> predict(int[] input, int k) { return predict(input, k, hidden_, output_); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2)); String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2)); String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2)); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); }
#vulnerable code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim(); String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim(); String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim(); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code int getNegative(int target) { int negative; do { negative = negatives[negpos]; negpos = (negpos + 1) % negatives.length; } while (target == negative); return negative; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code void computeOutputSoftmax() { computeOutputSoftmax(hidden_, output_); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
#vulnerable code float binaryLogistic(int target, boolean label, float lr) { float score = sigmoid(wo_.dotRow(hidden_, target)); float alpha = lr * (label ? 1f : 0f - score); grad_.addRow(wo_, target, alpha); synchronized (this) { wo_.addRow(hidden_, target, alpha); } if (label) { return -log(score); } else { return -log(1.0f - score); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2)); String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2)); String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2)); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); }
#vulnerable code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim(); String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim(); String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim(); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = getAttribute(Regexps.firstMatch(labelPattern, meta, 2)); String category = getAttribute(Regexps.firstMatch(categoryPattern, meta, 2)); String title = getAttribute(Regexps.firstMatch(titlePattern, meta, 2)); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); }
#vulnerable code public static WebDocument fromText(String meta, List<String> pageData) { String url = Regexps.firstMatch(urlPattern, meta, 2); String id = url.replaceAll("http://|https://", ""); String source = Regexps.firstMatch(sourcePattern, meta, 2); String crawlDate = Regexps.firstMatch(crawlDatePattern, meta, 2); String labels = Regexps.firstMatch(labelPattern, meta, 2).replace('\"', ' ').trim(); String category = Regexps.firstMatch(categoryPattern, meta, 2).replace('\"', ' ').trim(); String title = Regexps.firstMatch(titlePattern, meta, 2).replace('\"', ' ').trim(); int i = source.lastIndexOf("/"); if (i >= 0 && i < source.length()) { source = source.substring(i + 1); } return new WebDocument(source, id, title, pageData, url, crawlDate, labels, category); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void internalClose() throws IOException { if (!closed) { closed = true; backend.rrdClose(); } }
#vulnerable code void realClose() throws IOException { if (!closed) { closed = true; backend.rrdClose(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void testFile(String file, String version) throws IOException { URL url = getClass().getResource(file); RRDatabase rrd = new RRDatabase(url.getFile()); Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate()); Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives()); Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size()); Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat()); Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat()); Assert.assertEquals("Invalid version", version, rrd.header.getVersion()); Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount()); Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount()); boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading); boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2)); if("0003".equals(version) ) { Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1); } Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1); rrd.rrdFile.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow); double speed = readDouble(rrd.rrdFile); double weight = readDouble(rrd.rrdFile); Assert.assertEquals(1.4316185300e+07, speed, 1e-7); Assert.assertEquals(3, weight, 1e-7); DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300); Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7); Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7); }
#vulnerable code private void testFile(String file, String version) throws IOException { URL url = getClass().getResource(file); RRDatabase rrd = new RRDatabase(url.getFile()); Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate()); Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives()); Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size()); Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat()); Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat()); Assert.assertEquals("Invalid version", version, rrd.header.getVersion()); Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount()); Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount()); boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading); boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2)); if("0003".equals(version) ) { Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1); } Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1); rrd.rrdFile.ras.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow); double speed = readDouble(rrd.rrdFile); double weight = readDouble(rrd.rrdFile); Assert.assertEquals(1.4316185300e+07, speed, 1e-7); Assert.assertEquals(3, weight, 1e-7); DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300); Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7); Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; }
#vulnerable code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } try { //Wait until the pool is not full and //Don't lock on anything while(ref.count == 0 && ! tryGetSlot()) { passNext(ACTION.SWAP, ref); countLock.lockInterruptibly(); full.await(); countLock.unlock(); ref = getEntry(path, true); } } catch (InterruptedException e) { passNext(ACTION.DROP, ref); throw new RuntimeException("request interrupted for " + path, e); } finally { if(countLock.isHeldByCurrentThread()) { countLock.unlock(); } } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; } #location 31 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void testFile(String file, String version) throws IOException { URL url = getClass().getResource(file); RRDatabase rrd = new RRDatabase(url.getFile()); Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate()); Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives()); Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size()); Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat()); Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat()); Assert.assertEquals("Invalid version", version, rrd.header.getVersion()); Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount()); Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount()); boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading); boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2)); if("0003".equals(version) ) { Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1); } Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1); rrd.rrdFile.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow); double speed = readDouble(rrd.rrdFile); double weight = readDouble(rrd.rrdFile); Assert.assertEquals(1.4316185300e+07, speed, 1e-7); Assert.assertEquals(3, weight, 1e-7); DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300); Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7); Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7); }
#vulnerable code private void testFile(String file, String version) throws IOException { URL url = getClass().getResource(file); RRDatabase rrd = new RRDatabase(url.getFile()); Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate()); Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives()); Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size()); Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat()); Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat()); Assert.assertEquals("Invalid version", version, rrd.header.getVersion()); Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount()); Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount()); boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading); boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2)); if("0003".equals(version) ) { Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1); } Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1); rrd.rrdFile.ras.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow); double speed = readDouble(rrd.rrdFile); double weight = readDouble(rrd.rrdFile); Assert.assertEquals(1.4316185300e+07, speed, 1e-7); Assert.assertEquals(3, weight, 1e-7); DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300); Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7); Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7); } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } try { //Wait until the pool is not full and //Don't lock on anything while(ref.count == 0 && ! tryGetSlot()) { passNext(ACTION.SWAP, ref); countLock.lockInterruptibly(); full.await(); countLock.unlock(); ref = getEntry(path, true); } } catch (InterruptedException e) { passNext(ACTION.DROP, ref); throw new RuntimeException("request interrupted for " + path, e); } finally { if(countLock.isHeldByCurrentThread()) { countLock.unlock(); } } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; }
#vulnerable code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } if(ref.count == 0) { //Wait until the pool is not full //Don't lock on anything while(usage.get() >= maxCapacity) { passNext(ACTION.SWAP, ref); try { countLock.lockInterruptibly(); full.await(); ref = getEntry(path, true); //Get an empty ref, can use it, reserve the slot if(ref.count == 0 && usage.get() < maxCapacity) { usage.incrementAndGet(); break; } } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } finally { if(countLock.isHeldByCurrentThread()) { countLock.unlock(); } } } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); passNext(ACTION.SWAP, ref); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } } else { passNext(ACTION.SWAP, ref); } ref.count++; return ref.rrdDb; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException { createGaugeRrd(180); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<160; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -80)); } rrd.close(); prepareGraph(); // Original expectMajorGridLine(" -80"); expectMajorGridLine(" -40"); expectMajorGridLine(" 0"); expectMajorGridLine(" 40"); expectMajorGridLine(" 80"); run(); }
#vulnerable code @Test public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException { createGaugeRrd(180); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<160; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -80)); } rrd.close(); prepareGraph(); // Original expectMajorGridLine(" -80"); expectMajorGridLine(" -40"); expectMajorGridLine(" 0"); expectMajorGridLine(" 40"); expectMajorGridLine(" 80"); run(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void internalClose() throws IOException { if (!closed) { closed = true; backend.rrdClose(); } }
#vulnerable code void realClose() throws IOException { if (!closed) { closed = true; backend.rrdClose(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; }
#vulnerable code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } try { //Wait until the pool is not full and //Don't lock on anything while(ref.count == 0 && ! tryGetSlot()) { passNext(ACTION.SWAP, ref); countLock.lockInterruptibly(); full.await(); countLock.unlock(); ref = getEntry(path, true); } } catch (InterruptedException e) { passNext(ACTION.DROP, ref); throw new RuntimeException("request interrupted for " + path, e); } finally { if(countLock.isHeldByCurrentThread()) { countLock.unlock(); } } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testTwoEntriesInRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<2; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp+":100"); } rrd.close(); prepareGraph(); expectMajorGridLine(" 90"); expectMinorGridLines(1); expectMajorGridLine(" 100"); expectMinorGridLines(1); expectMajorGridLine(" 110"); expectMinorGridLines(1); expectMajorGridLine(" 120"); expectMinorGridLines(1); run(); }
#vulnerable code @Test public void testTwoEntriesInRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<2; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp+":100"); } rrd.close(); prepareGraph(); expectMajorGridLine(" 90"); expectMinorGridLines(1); expectMajorGridLine(" 100"); expectMinorGridLines(1); expectMajorGridLine(" 110"); expectMinorGridLines(1); expectMajorGridLine(" 120"); expectMinorGridLines(1); run(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void release(RrdDb rrdDb) throws IOException { // null pointer should not kill the thread, just ignore it if (rrdDb == null) { return; } RrdEntry ref; try { ref = getEntry(rrdDb.getPath(), false); } catch (InterruptedException e) { throw new RuntimeException("release interrupted for " + rrdDb, e); } if(ref == null) { return; } if (ref.count <= 0) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested"); } if (--ref.count == 0) { if(ref.rrdDb == null) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption"); } ref.rrdDb.close(); passNext(ACTION.DROP, ref); //If someone is waiting for an empty entry, signal it ref.waitempty.countDown(); } else { passNext(ACTION.SWAP, ref); } }
#vulnerable code public void release(RrdDb rrdDb) throws IOException { // null pointer should not kill the thread, just ignore it if (rrdDb == null) { return; } RrdEntry ref; try { ref = getEntry(rrdDb.getPath(), false); } catch (InterruptedException e) { throw new RuntimeException("release interrupted for " + rrdDb, e); } if(ref == null) { return; } if (ref.count <= 0) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested"); } if (--ref.count == 0) { if(ref.rrdDb == null) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption"); } ref.rrdDb.close(); usage.decrementAndGet(); try { countLock.lockInterruptibly(); if(usage.get() < maxCapacity) { full.signal(); } countLock.unlock(); } catch (InterruptedException e) { throw new RuntimeException("release interrupted for " + rrdDb, e); } finally { passNext(ACTION.DROP, ref); } //If someone is waiting for an empty entry, signal it ref.waitempty.countDown(); } else { passNext(ACTION.SWAP, ref); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEntriesZeroTo100InRrd() throws IOException, FontFormatException { createGaugeRrd(105); //Make sure all entries are recorded (5 is just a buffer for consolidation) RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<100; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + i); } rrd.close(); prepareGraph(); expectMinorGridLines(4); expectMajorGridLine(" 50"); expectMinorGridLines(4); expectMajorGridLine(" 100"); run(); }
#vulnerable code @Test public void testEntriesZeroTo100InRrd() throws IOException, FontFormatException { createGaugeRrd(105); //Make sure all entries are recorded (5 is just a buffer for consolidation) RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<100; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + i); } rrd.close(); prepareGraph(); expectMinorGridLines(4); expectMajorGridLine(" 50"); expectMinorGridLines(4); expectMajorGridLine(" 100"); run(); } #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 testEntriesNeg80To90InRrd() throws IOException, FontFormatException { createGaugeRrd(180); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<170; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -80)); } rrd.close(); prepareGraph(); expectMajorGridLine(" -90"); expectMajorGridLine(" -45"); expectMajorGridLine(" 0"); expectMajorGridLine(" 45"); expectMajorGridLine(" 90"); run(); }
#vulnerable code @Test public void testEntriesNeg80To90InRrd() throws IOException, FontFormatException { createGaugeRrd(180); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<170; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -80)); } rrd.close(); prepareGraph(); expectMajorGridLine(" -90"); expectMajorGridLine(" -45"); expectMajorGridLine(" 0"); expectMajorGridLine(" 45"); expectMajorGridLine(" 90"); run(); } #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 testBackendFactoryDefaults() throws IOException { try (RrdNioBackendFactory factory = new RrdNioBackendFactory(0)) { File rrdfile = testFolder.newFile("testfile"); super.testBackendFactory(factory,rrdfile.getCanonicalPath()); } }
#vulnerable code @Test public void testBackendFactoryDefaults() throws IOException { // Don't close a default NIO, it will close the background sync threads executor @SuppressWarnings("resource") RrdNioBackendFactory factory = new RrdNioBackendFactory(); File rrdfile = testFolder.newFile("testfile"); super.testBackendFactory(factory,rrdfile.getCanonicalPath()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void release(RrdDb rrdDb) throws IOException { // null pointer should not kill the thread, just ignore it if (rrdDb == null) { return; } RrdEntry ref; try { ref = getEntry(rrdDb.getPath(), false); } catch (InterruptedException e) { throw new RuntimeException("release interrupted for " + rrdDb, e); } if(ref == null) { return; } if (ref.count <= 0) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested"); } if (--ref.count == 0) { if(ref.rrdDb == null) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption"); } ref.rrdDb.close(); passNext(ACTION.DROP, ref); //If someone is waiting for an empty entry, signal it ref.waitempty.countDown(); } else { passNext(ACTION.SWAP, ref); } }
#vulnerable code public void release(RrdDb rrdDb) throws IOException { // null pointer should not kill the thread, just ignore it if (rrdDb == null) { return; } RrdEntry ref; try { ref = getEntry(rrdDb.getPath(), false); } catch (InterruptedException e) { throw new RuntimeException("release interrupted for " + rrdDb, e); } if(ref == null) { return; } if (ref.count <= 0) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested"); } if (--ref.count == 0) { if(ref.rrdDb == null) { passNext(ACTION.DROP, ref); throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption"); } ref.rrdDb.close(); usage.decrementAndGet(); try { countLock.lockInterruptibly(); if(usage.get() < maxCapacity) { full.signal(); } countLock.unlock(); } catch (InterruptedException e) { throw new RuntimeException("release interrupted for " + rrdDb, e); } finally { passNext(ACTION.DROP, ref); } //If someone is waiting for an empty entry, signal it ref.waitempty.countDown(); } else { passNext(ACTION.SWAP, ref); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEntriesNeg55To105InRrd() throws IOException, FontFormatException { createGaugeRrd(165); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<160; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -55)); } rrd.close(); prepareGraph(); expectMajorGridLine("-120"); expectMajorGridLine(" -60"); expectMajorGridLine(" 0"); expectMajorGridLine(" 60"); expectMajorGridLine(" 120"); run(); }
#vulnerable code @Test public void testEntriesNeg55To105InRrd() throws IOException, FontFormatException { createGaugeRrd(165); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<160; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -55)); } rrd.close(); prepareGraph(); expectMajorGridLine("-120"); expectMajorGridLine(" -60"); expectMajorGridLine(" 0"); expectMajorGridLine(" 60"); expectMajorGridLine(" 120"); run(); } #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 testOneEntryInRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); long nowSeconds = new Date().getTime(); long fiveMinutesAgo = nowSeconds - (5 * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(fiveMinutesAgo+":10"); rrd.close(); prepareGraph(); checkForBasicGraph(); }
#vulnerable code @Test public void testOneEntryInRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = new RrdDb(jrbFileName); long nowSeconds = new Date().getTime(); long fiveMinutesAgo = nowSeconds - (5 * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(fiveMinutesAgo+":10"); rrd.close(); prepareGraph(); checkForBasicGraph(); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException { createGaugeRrd(180); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<160; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -80)); } rrd.close(); prepareGraph(); // Original expectMinorGridLines(3); expectMajorGridLine(" -50"); expectMinorGridLines(4); expectMajorGridLine(" 0"); expectMinorGridLines(4); expectMajorGridLine(" 50"); expectMinorGridLines(3); run(); }
#vulnerable code @Test public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException { createGaugeRrd(180); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<160; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -80)); } rrd.close(); prepareGraph(); // Original expectMinorGridLines(3); expectMajorGridLine(" -50"); expectMinorGridLines(4); expectMajorGridLine(" 0"); expectMinorGridLines(4); expectMajorGridLine(" 50"); expectMinorGridLines(3); run(); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String readFromFile(File file) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8")); StringBuilder out = new StringBuilder(); String line; while ((line = in.readLine()) != null) { out.append(line); } in.close(); return out.toString(); }
#vulnerable code private static String readFromFile(File file) throws IOException { Reader reader = new FileReader(file); CharBuffer charBuffer = CharBuffer.allocate(MAX_TEST_DATA_FILE_SIZE); reader.read(charBuffer); charBuffer.position(0); return charBuffer.toString(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void bindScope(Class<? extends Annotation> annotationType, Scope scope) { Scope existing = scopes.get(nonNull(annotationType, "annotation type")); if (existing != null) { addError(source(), ErrorMessages.DUPLICATE_SCOPES, existing, annotationType, scope); } else { scopes.put(annotationType, nonNull(scope, "scope")); } }
#vulnerable code public void bindScope(Class<? extends Annotation> annotationType, Scope scope) { ensureNotCreated(); Scope existing = scopes.get(nonNull(annotationType, "annotation type")); if (existing != null) { addError(source(), ErrorMessages.DUPLICATE_SCOPES, existing, annotationType, scope); } else { scopes.put(annotationType, nonNull(scope, "scope")); } } #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> LinkedBindingBuilderImpl<T> link(Key<T> key) { LinkedBindingBuilderImpl<T> builder = new LinkedBindingBuilderImpl<T>(this, key).from(source()); linkedBindingBuilders.add(builder); return builder; }
#vulnerable code public <T> LinkedBindingBuilderImpl<T> link(Key<T> key) { ensureNotCreated(); LinkedBindingBuilderImpl<T> builder = new LinkedBindingBuilderImpl<T>(this, key).from(source()); linkedBindingBuilders.add(builder); return builder; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code InternalContext(InjectorOptions options, Object[] toClear) { this.options = options; this.toClear = toClear; this.enterCount = 1; }
#vulnerable code java.util.List<com.google.inject.spi.DependencyAndSource> getDependencyChain() { com.google.common.collect.ImmutableList.Builder<com.google.inject.spi.DependencyAndSource> builder = com.google.common.collect.ImmutableList.builder(); for (int i = 0; i < dependencyStackSize; i += 2) { Object evenEntry = dependencyStack[i]; Dependency<?> dependency; if (evenEntry instanceof com.google.inject.Key) { dependency = Dependency.get((com.google.inject.Key<?>) evenEntry); } else { dependency = (Dependency<?>) evenEntry; } builder.add(new com.google.inject.spi.DependencyAndSource(dependency, dependencyStack[i + 1])); } return builder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testReturnDelegateCookies() { Cookie[] cookies = new Cookie[]{ new Cookie("testName1", TEST_VALUE_1), new Cookie("testName2", "testValue2") }; HttpServletRequest delegate = createMock(HttpServletRequest.class); expect(delegate.getCookies()).andStubReturn(cookies); replay(delegate); ContinuingHttpServletRequest continuingRequest = new ContinuingHttpServletRequest( delegate); assertCookieArraysEqual(cookies, continuingRequest.getCookies()); // Now mutate the original cookies, this shouldnt be reflected in the continued request. cookies[0].setValue("INVALID"); cookies[1].setValue("INVALID"); cookies[1].setMaxAge(123); try { assertCookieArraysEqual(cookies, continuingRequest.getCookies()); throw new Error(); } catch (AssertionFailedError e) { // Expected. } // Verify that they remain equal to the original values. assertEquals(TEST_VALUE_1, continuingRequest.getCookies()[0].getValue()); assertEquals(TEST_VALUE_2, continuingRequest.getCookies()[1].getValue()); assertEquals(DEFAULT_MAX_AGE, continuingRequest.getCookies()[1].getMaxAge()); // Perform a snapshot of the snapshot. ContinuingHttpServletRequest furtherContinuingRequest = new ContinuingHttpServletRequest( continuingRequest); // The cookies should be fixed. assertCookieArraysEqual(continuingRequest.getCookies(), furtherContinuingRequest.getCookies()); verify(delegate); }
#vulnerable code public void testReturnDelegateCookies() { Cookie[] cookies = new Cookie[]{ new Cookie("testName1", TEST_VALUE_1), new Cookie("testName2", "testValue2") }; HttpServletRequest delegate = createMock(HttpServletRequest.class); expect(delegate.getCookies()).andStubReturn(cookies); replay(delegate); ContinuingHttpServletRequest continuingRequest = new ContinuingHttpServletRequest( delegate); assertCookieArraysEqual(cookies, continuingRequest.getCookies()); // Now mutate the original cookies, this shouldnt be reflected in the continued request. cookies[0].setValue("INVALID"); cookies[1].setValue("INVALID"); cookies[1].setMaxAge(123); try { assertCookieArraysEqual(cookies, continuingRequest.getCookies()); fail(); } catch (AssertionFailedError e) { // Expected. } // Verify that they remain equal to the original values. assertEquals(TEST_VALUE_1, continuingRequest.getCookies()[0].getValue()); assertEquals(TEST_VALUE_2, continuingRequest.getCookies()[1].getValue()); assertEquals(DEFAULT_MAX_AGE, continuingRequest.getCookies()[1].getMaxAge()); // Perform a snapshot of the snapshot. ContinuingHttpServletRequest furtherContinuingRequest = new ContinuingHttpServletRequest( continuingRequest); // The cookies should be fixed. assertCookieArraysEqual(continuingRequest.getCookies(), furtherContinuingRequest.getCookies()); verify(delegate); } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ConstantBindingBuilderImpl bindConstant(Annotation annotation) { return bind(source(), Key.strategyFor(annotation)); }
#vulnerable code public ConstantBindingBuilderImpl bindConstant(Annotation annotation) { ensureNotCreated(); return bind(source(), Key.strategyFor(annotation)); } #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 bindInterceptor(Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) { proxyFactoryBuilder.intercept(classMatcher, methodMatcher, interceptors); }
#vulnerable code public void bindInterceptor(Matcher<? super Class<?>> classMatcher, Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) { ensureNotCreated(); proxyFactoryBuilder.intercept(classMatcher, methodMatcher, interceptors); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected double evaluateFunction(final Access1D<?> solution) { final MatrixStore<Double> tmpX = this.getSolutionX(); return tmpX.transpose().multiply(this.getMatrixQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getMatrixC())).doubleValue(0L); }
#vulnerable code @Override protected double evaluateFunction(final Access1D<?> solution) { final MatrixStore<Double> tmpX = this.getMatrixX(); return tmpX.transpose().multiply(this.getMatrixQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getMatrixC())).doubleValue(0L); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) { if (myInverse == null) { final MatrixStore<N> tmpQ1 = this.getQ1(); final Array1D<Double> tmpSingulars = this.getSingularValues(); final MatrixStore<N> tmpQ2 = this.getQ2(); final int tmpRowDim = (int) tmpSingulars.count(); final int tmpColDim = (int) tmpQ1.countRows(); final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim); double tmpValue; final int rank = this.getRank(); for (int i = 0; i < rank; i++) { tmpValue = tmpSingulars.doubleValue(i); for (int j = 0; j < tmpColDim; j++) { tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber()); } } preallocated.fillByMultiplying(tmpQ2, tmpMtrx); myInverse = preallocated; } return myInverse; }
#vulnerable code public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) { if (myInverse == null) { preallocated.fillAll(this.scalar().zero().getNumber()); final PhysicalStore<N> tmpMtrx = preallocated; final MatrixStore<N> tmpQ1 = this.getQ1(); final MatrixStore<N> tmpD = this.getD(); final int tmpColDim = (int) tmpQ1.countRows(); double tmpSingularValue; final int rank = this.getRank(); for (int i = 0; i < rank; i++) { tmpSingularValue = tmpD.doubleValue(i, i); for (int j = 0; j < tmpColDim; j++) { tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber()); } } myInverse = this.getQ2().multiply(tmpMtrx); } return myInverse; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) { if (myInverse == null) { final MatrixStore<N> tmpQ1 = this.getQ1(); final Array1D<Double> tmpSingulars = this.getSingularValues(); final MatrixStore<N> tmpQ2 = this.getQ2(); final int tmpRowDim = (int) tmpSingulars.count(); final int tmpColDim = (int) tmpQ1.countRows(); final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim); double tmpValue; final int rank = this.getRank(); for (int i = 0; i < rank; i++) { tmpValue = tmpSingulars.doubleValue(i); for (int j = 0; j < tmpColDim; j++) { tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber()); } } preallocated.fillByMultiplying(tmpQ2, tmpMtrx); myInverse = preallocated; } return myInverse; }
#vulnerable code public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) { if (myInverse == null) { preallocated.fillAll(this.scalar().zero().getNumber()); final PhysicalStore<N> tmpMtrx = preallocated; final MatrixStore<N> tmpQ1 = this.getQ1(); final MatrixStore<N> tmpD = this.getD(); final int tmpColDim = (int) tmpQ1.countRows(); double tmpSingularValue; final int rank = this.getRank(); for (int i = 0; i < rank; i++) { tmpSingularValue = tmpD.doubleValue(i, i); for (int j = 0; j < tmpColDim; j++) { tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber()); } } myInverse = this.getQ2().multiply(tmpMtrx); } return myInverse; } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public N remove(final long key) { final int index = myStorage.index(key); final N oldValue = index >= 0 ? myStorage.getInternally(index) : null; myStorage.remove(key, index); return oldValue; }
#vulnerable code public N remove(final long key) { final N tmpOldVal = myStorage.get(key); myStorage.set(key, 0.0); return tmpOldVal; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) { final Array1D<Double> doubles = Array1D.factory(Primitive32Array.FACTORY).makeFilled(10, new Uniform()); System.out.println(doubles.toString()); final Array1D<Double> rollingMedian = Array1D.PRIMITIVE32.makeZero(doubles.size()); rollingMedian.set(0, doubles.get(0)); System.out.printf("%1$s -> %1$s\n", doubles.get(0)); final Array1D<Double> someSamples2 = doubles.subList(0, 2); final double mean2 = SampleSet.wrap(someSamples2).getMean(); rollingMedian.set(1, mean2); System.out.printf("%s -> %s\n", someSamples2.toString(), mean2); for (int i = 2; i < doubles.length; i++) { final Array1D<Double> someSamples = doubles.subList(i - 2, i + 1); final double mean = SampleSet.wrap(someSamples).getMean(); rollingMedian.set(i, mean); System.out.printf("%s -> %s\n", someSamples.toString(), mean2); } System.out.println(rollingMedian.toString()); for (int i = 0; i < doubles.length; i++) { final int first = Math.max(0, i - 2); final int limit = i + 1; final double mean = doubles.aggregateRange(first, limit, Aggregator.AVERAGE); rollingMedian.set(i, mean); } System.out.println(rollingMedian.toString()); final SampleSet samples = SampleSet.make(); for (int i = 0; i < doubles.length; i++) { final int first = Math.max(0, i - 2); final int limit = i + 1; samples.swap(doubles.sliceRange(first, limit)); final double mean = samples.getMean(); rollingMedian.set(i, mean); } System.out.println(rollingMedian.toString()); final PrimitiveDenseStore org = MatrixUtils.makeSPD(10); final Eigenvalue<Double> evd = Eigenvalue.PRIMITIVE.make(true); evd.decompose(org); final MatrixStore<Double> expSquared = org.multiply(org); final MatrixStore<Double> v = evd.getV(); final MatrixStore<Double> d = evd.getD().logical().diagonal(false).get(); final Array1D<ComplexNumber> values = evd.getEigenvalues(); final MatrixStore<Double> ident = v.multiply(v.conjugate()); final MatrixStore<Double> actSquared = v.multiply(d).multiply(d).multiply(v.conjugate()); TestUtils.assertEquals(expSquared, actSquared); final PhysicalStore<Double> copied = v.copy(); copied.loopRow(0, (r, c) -> copied.modifyColumn(c, PrimitiveFunction.MULTIPLY.second(values.doubleValue(c) * values.doubleValue(c)))); final MatrixStore<Double> actSquared2 = copied.multiply(v.conjugate()); TestUtils.assertEquals(expSquared, actSquared2); final MatrixStore<Double> matrix = org; matrix.logical().limits(3, 3).offsets(1, 1).get(); matrix.logical().offsets(1, 1).get(); }
#vulnerable code public static void main(final String[] args) { final Array1D<Double> doubles = Array1D.factory(Primitive32Array.FACTORY).makeFilled(10, new Uniform()); System.out.println(doubles.toString()); final Array1D<Double> rollingMedian = Array1D.PRIMITIVE32.makeZero(doubles.size()); rollingMedian.set(0, doubles.get(0)); System.out.printf("%1$s -> %1$s\n", doubles.get(0)); final Array1D<Double> someSamples2 = doubles.subList(0, 2); final double mean2 = SampleSet.wrap(someSamples2).getMean(); rollingMedian.set(1, mean2); System.out.printf("%s -> %s\n", someSamples2.toString(), mean2); for (int i = 2; i < doubles.length; i++) { final Array1D<Double> someSamples = doubles.subList(i - 2, i + 1); final double mean = SampleSet.wrap(someSamples).getMean(); rollingMedian.set(i, mean); System.out.printf("%s -> %s\n", someSamples.toString(), mean2); } System.out.println(rollingMedian.toString()); for (int i = 0; i < doubles.length; i++) { final int first = Math.max(0, i - 2); final int limit = i + 1; final double mean = doubles.aggregateRange(first, limit, Aggregator.AVERAGE); rollingMedian.set(i, mean); } System.out.println(rollingMedian.toString()); final SampleSet samples = SampleSet.make(); for (int i = 0; i < doubles.length; i++) { final int first = Math.max(0, i - 2); final int limit = i + 1; samples.swap(doubles.sliceRange(first, limit)); final double mean = samples.getMean(); rollingMedian.set(i, mean); } System.out.println(rollingMedian.toString()); final PrimitiveDenseStore org = MatrixUtils.makeSPD(10); final Eigenvalue<Double> evd = Eigenvalue.PRIMITIVE.make(true); evd.decompose(org); final MatrixStore<Double> expSquared = org.multiply(org); final MatrixStore<Double> v = evd.getV(); final MatrixStore<Double> d = evd.getD().logical().diagonal(false).get(); final Array1D<ComplexNumber> values = evd.getEigenvalues(); final MatrixStore<Double> ident = v.multiply(v.conjugate()); final MatrixStore<Double> actSquared = v.multiply(d).multiply(d).multiply(v.conjugate()); TestUtils.assertEquals(expSquared, actSquared); final PhysicalStore<Double> copied = v.copy(); copied.loopRow(0, (r, c) -> copied.modifyColumn(c, PrimitiveFunction.MULTIPLY.second(values.doubleValue(c) * values.doubleValue(c)))); final MatrixStore<Double> actSquared2 = copied.multiply(v.conjugate()); TestUtils.assertEquals(expSquared, actSquared2); final MatrixStore<Double> matrix = null; matrix.logical().limits(3, 3).offsets(1, 1).get(); matrix.logical().offsets(1, 1).get(); } #location 70 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void doTestFeedForward(final Factory<Double, ?> factory) { int counter = 0; ArtificialNeuralNetwork network = this.getInitialNetwork(factory); NetworkInvoker invoker = network.newInvoker(); for (Data triplet : this.getTestCases()) { if ((triplet.input != null) && (triplet.expected != null)) { TestUtils.assertEquals(triplet.expected, invoker.invoke(triplet.input), this.precision()); counter++; } } if (counter == 0) { TestUtils.fail(TEST_DID_NOT_DO_ANYTHING); } }
#vulnerable code void doTestFeedForward(Factory<Double, ?> factory) { int counter = 0; ArtificialNeuralNetwork network = this.getInitialNetwork(factory).get(); for (Data triplet : this.getTestCases()) { if ((triplet.input != null) && (triplet.expected != null)) { TestUtils.assertEquals(triplet.expected, network.invoke(triplet.input), this.precision()); counter++; } } if (counter == 0) { TestUtils.fail(TEST_DID_NOT_DO_ANYTHING); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int getRank() { final double tolerance = s[0] * this.getDimensionalEpsilon(); int rank = 0; for (int i = 0; i < s.length; i++) { if (s[i] > tolerance) { rank++; } } return rank; }
#vulnerable code public int getRank() { final Array1D<Double> tmpSingularValues = this.getSingularValues(); int retVal = tmpSingularValues.size(); // Tolerance based on min-dim but should be max-dim final double tmpTolerance = retVal * (tmpSingularValues.doubleValue(0) * PrimitiveMath.MACHINE_EPSILON); for (int i = retVal - 1; i >= 0; i--) { if (tmpSingularValues.doubleValue(i) <= tmpTolerance) { retVal--; } else { return retVal; } } return retVal; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static MathProgSysModel make(final File file) { final MathProgSysModel retVal = new MathProgSysModel(); String line; FileSection section = null; try (BufferedReader reader = new BufferedReader(new FileReader(file))) { // Returns the content of a line MINUS the newline. // Returns null only for the END of the stream. // Returns an empty String if two newlines appear in a row. while ((line = reader.readLine()) != null) { // BasicLogger.debug("Line: {}", line); if ((line.length() == 0) || line.startsWith(COMMENT) || line.startsWith(COMMENT_REF)) { // Skip this line } else if (line.startsWith(SPACE)) { retVal.parseSectionLine(section, line); } else { section = retVal.identifySection(line); } } } catch (IOException xcptn) { xcptn.printStackTrace(); } return retVal; }
#vulnerable code public static MathProgSysModel make(final File file) { final MathProgSysModel retVal = new MathProgSysModel(); String tmpLine; FileSection tmpSection = null; try { final BufferedReader tmpBufferedFileReader = new BufferedReader(new FileReader(file)); //readLine is a bit quirky : //it returns the content of a line MINUS the newline. //it returns null only for the END of the stream. //it returns an empty String if two newlines appear in a row. while ((tmpLine = tmpBufferedFileReader.readLine()) != null) { // BasicLogger.debug("Line: {}", tmpLine); if ((tmpLine.length() == 0) || tmpLine.startsWith(COMMENT) || tmpLine.startsWith(COMMENT_REF)) { // Skip this line } else if (tmpLine.startsWith(SPACE)) { retVal.parseSectionLine(tmpSection, tmpLine); } else { tmpSection = retVal.identifySection(tmpLine); } } tmpBufferedFileReader.close(); } catch (final FileNotFoundException anException) { anException.printStackTrace(); } catch (final IOException anException) { anException.printStackTrace(); } return retVal; } #location 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testXhtmlParsing() throws Exception { String path = "/test-documents/testXHTML.html"; Metadata metadata = new Metadata(); String content = Tika.parseToString( HtmlParserTest.class.getResourceAsStream(path), metadata); assertEquals("application/xhtml+xml", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("XHTML test document", metadata.get(Metadata.TITLE)); assertEquals("Tika Developers", metadata.get("Author")); assertEquals("5", metadata.get("refresh")); assertTrue(content.contains("ability of Apache Tika")); assertTrue(content.contains("extract content")); assertTrue(content.contains("an XHTML document")); }
#vulnerable code public void testXhtmlParsing() throws Exception { Parser parser = new AutoDetectParser(); // Should auto-detect! ContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); InputStream stream = HtmlParserTest.class.getResourceAsStream( "/test-documents/testXHTML.html"); try { parser.parse(stream, handler, metadata); } finally { stream.close(); } assertEquals("application/xhtml+xml", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("XHTML test document", metadata.get(Metadata.TITLE)); String content = handler.toString(); assertEquals("Tika Developers", metadata.get("Author")); assertEquals("5", metadata.get("refresh")); assertTrue(content.contains("ability of Apache Tika")); assertTrue(content.contains("extract content")); assertTrue(content.contains("an XHTML document")); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void extract(InputStream input) throws Exception { RereadableInputStream ris = new RereadableInputStream(input, MEMORY_THRESHOLD); try { // First, extract properties this.reader = new POIFSReader(); this.reader.registerListener(new PropertiesReaderListener(), SummaryInformation.DEFAULT_STREAM_NAME); if (input.available() > 0) { reader.read(ris); } while (ris.read() != -1) { } ris.rewind(); // Extract document full text this.text = extractText(ris); } finally { ris.close(); } }
#vulnerable code public void extract(InputStream input) throws Exception { // First, extract properties this.reader = new POIFSReader(); this.reader.registerListener(new PropertiesReaderListener(), SummaryInformation.DEFAULT_STREAM_NAME); RereadableInputStream ris = new RereadableInputStream(input, MEMORY_THRESHOLD); if (input.available() > 0) { reader.read(ris); } while (ris.read() != -1) { } ris.rewind(); // Extract document full text this.text = extractText(ris); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void parse( InputStream stream, ContentHandler handler, Metadata metadata) throws IOException, SAXException, TikaException { metadata.set(Metadata.CONTENT_TYPE, "text/plain"); // CharsetDetector expects a stream to support marks if (!stream.markSupported()) { stream = new BufferedInputStream(stream); } // Detect the content encoding (the stream is reset to the beginning) // TODO: Better use of the possible encoding hint in input metadata CharsetMatch match = new CharsetDetector().setText(stream).detect(); if (match != null) { metadata.set(Metadata.CONTENT_ENCODING, match.getName()); // Is the encoding language-specific (KOI8-R, SJIS, etc.)? String language = match.getLanguage(); if (language != null) { metadata.set(Metadata.CONTENT_LANGUAGE, match.getLanguage()); metadata.set(Metadata.LANGUAGE, match.getLanguage()); } } String encoding = metadata.get(Metadata.CONTENT_ENCODING); if (encoding == null) { throw new TikaException( "Text encoding could not be detected and no encoding" + " hint is available in document metadata"); } try { Reader reader = new BufferedReader(new InputStreamReader(stream, encoding)); // TIKA-240: Drop the BOM when extracting plain text reader.mark(1); int bom = reader.read(); if (bom != '\ufeff') { // zero-width no-break space reader.reset(); } XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); xhtml.startElement("p"); char[] buffer = new char[4096]; int n = reader.read(buffer); while (n != -1) { xhtml.characters(buffer, 0, n); n = reader.read(buffer); } xhtml.endElement("p"); xhtml.endDocument(); } catch (UnsupportedEncodingException e) { throw new TikaException( "Unsupported text encoding: " + encoding, e); } }
#vulnerable code public void parse( InputStream stream, ContentHandler handler, Metadata metadata) throws IOException, SAXException, TikaException { CharsetDetector detector = new CharsetDetector(); // Use the declared character encoding, if available String encoding = metadata.get(Metadata.CONTENT_ENCODING); if (encoding != null) { detector.setDeclaredEncoding(encoding); } // CharsetDetector expects a stream to support marks if (!stream.markSupported()) { stream = new BufferedInputStream(stream); } detector.setText(stream); CharsetMatch match = detector.detect(); if (match == null) { throw new TikaException("Unable to detect character encoding"); } Reader reader = new BufferedReader(match.getReader()); // TIKA-240: Drop the BOM when extracting plain text reader.mark(1); int bom = reader.read(); if (bom != '\ufeff') { // zero-width no-break space reader.reset(); } metadata.set(Metadata.CONTENT_TYPE, "text/plain"); metadata.set(Metadata.CONTENT_ENCODING, match.getName()); String language = match.getLanguage(); if (language != null) { metadata.set(Metadata.CONTENT_LANGUAGE, match.getLanguage()); metadata.set(Metadata.LANGUAGE, match.getLanguage()); } XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); xhtml.startElement("p"); char[] buffer = new char[4096]; for (int n = reader.read(buffer); n != -1; n = reader.read(buffer)) { xhtml.characters(buffer, 0, n); } xhtml.endElement("p"); xhtml.endDocument(); } #location 47 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private MagicMatch readMatch(Element element) throws MimeTypeException { String offset = null; String value = null; String mask = null; String type = null; NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); if (attr.getName().equals(MATCH_OFFSET_ATTR)) { offset = attr.getValue(); } else if (attr.getName().equals(MATCH_TYPE_ATTR)) { type = attr.getValue(); } else if (attr.getName().equals(MATCH_VALUE_ATTR)) { value = attr.getValue(); } else if (attr.getName().equals(MATCH_MASK_ATTR)) { mask = attr.getValue(); } } // Parse OffSet int offStart = 0; int offEnd = 0; if (offset != null) { int colon = offset.indexOf(':'); if (colon == -1) { offStart = Integer.parseInt(offset); offEnd = offStart; } else { offStart = Integer.parseInt(offset.substring(0, colon)); offEnd = Integer.parseInt(offset.substring(colon + 1)); offEnd = Math.max(offStart, offEnd); } } return new MagicMatch(offStart, offEnd, type, mask, value); }
#vulnerable code private MagicMatch readMatch(Element element) throws MimeTypeException { String offset = null; String value = null; String mask = null; String type = null; NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); if (attr.getName().equals(MATCH_OFFSET_ATTR)) { offset = attr.getValue(); } else if (attr.getName().equals(MATCH_TYPE_ATTR)) { type = attr.getValue(); } else if (attr.getName().equals(MATCH_VALUE_ATTR)) { value = attr.getValue(); } else if (attr.getName().equals(MATCH_MASK_ATTR)) { mask = attr.getValue(); } } // Parse OffSet String[] offsets = offset.split(":"); int offStart = 0; int offEnd = 0; try { offStart = Integer.parseInt(offsets[0]); } catch (Exception e) { // WARN log + avoid loading } try { offEnd = Integer.parseInt(offsets[1]); } catch (Exception e) { // WARN log } offEnd = Math.max(offStart, offEnd); return new MagicMatch(offStart, offEnd, type, mask, value); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void parse( InputStream stream, ContentHandler handler, Metadata metadata) throws IOException, SAXException, TikaException { ZipInputStream zip = new ZipInputStream(stream); ZipEntry entry = zip.getNextEntry(); while (entry != null) { if (entry.getName().equals("mimetype")) { String type = IOUtils.toString(zip, "UTF-8"); metadata.set(Metadata.CONTENT_TYPE, type); } else if (entry.getName().equals("meta.xml")) { meta.parse(zip, new DefaultHandler(), metadata); } else if (entry.getName().equals("content.xml")) { content.parse(zip, handler, metadata); } entry = zip.getNextEntry(); } }
#vulnerable code public void parse( InputStream stream, ContentHandler handler, Metadata metadata) throws IOException, SAXException, TikaException { ZipInputStream zip = new ZipInputStream(stream); ZipEntry entry = zip.getNextEntry(); while (entry != null) { if (entry.getName().equals("mimetype")) { StringBuilder buffer = new StringBuilder(); Reader reader = new InputStreamReader(zip, "UTF-8"); for (int ch = reader.read(); ch != -1; ch = reader.read()) { buffer.append((char) ch); } metadata.set(Metadata.CONTENT_TYPE, buffer.toString()); } else if (entry.getName().equals("meta.xml")) { meta.parse(zip, new DefaultHandler(), metadata); } else if (entry.getName().equals("content.xml")) { content.parse(zip, handler, metadata); } entry = zip.getNextEntry(); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String handleTypeName(String typeName) { if (getTypeNames() == null && getTypeNames().size() == 0) { return null; } String[] tokens = typeName.split(","); boolean foundIt = false; for (String token : tokens) { String[] keys = token.split("="); for (String key : keys) { // we want the next item in the array. if (foundIt) { return key; } if (getTypeNames().contains(key)) { foundIt = true; } } } return null; }
#vulnerable code private String handleTypeName(String typeName) { String[] tokens = typeName.split(","); boolean foundIt = false; for (String token : tokens) { String[] keys = token.split("="); for (String key : keys) { // we want the next item in the array. if (foundIt) { return key; } if (getTypeNames().contains(key)) { foundIt = true; } } } return null; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doWrite(Query query) throws Exception { List<String> typeNames = this.getTypeNames(); DatagramSocket socket = (DatagramSocket) pool.borrowObject(this.address); try { for (Result result : query.getResults()) { if (isDebugEnabled()) { log.debug(result.toString()); } Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { if (JmxUtils.isNumeric(values.getValue())) { StringBuilder sb = new StringBuilder(); sb.append(JmxUtils.getKeyString(query, result, values, typeNames, rootPrefix)); sb.append(":"); sb.append(values.getValue().toString()); sb.append("|"); sb.append(bucketType); sb.append("\n"); String line = sb.toString(); byte[] sendData = line.getBytes(); if (isDebugEnabled()) { log.debug("StatsD Message: " + line.trim()); } DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length); socket.send(sendPacket); } } } } } finally { pool.returnObject(address, socket); } }
#vulnerable code public void doWrite(Query query) throws Exception { List<String> typeNames = this.getTypeNames(); DatagramSocket socket = new DatagramSocket(); try { for (Result result : query.getResults()) { if (isDebugEnabled()) { log.debug(result.toString()); } Map<String, Object> resultValues = result.getValues(); if (resultValues != null) { for (Entry<String, Object> values : resultValues.entrySet()) { if (JmxUtils.isNumeric(values.getValue())) { StringBuilder sb = new StringBuilder(); sb.append(JmxUtils.getKeyString(query, result, values, typeNames, rootPrefix)); sb.append(":"); sb.append(values.getValue().toString()); sb.append("|"); sb.append("c\n"); String line = sb.toString(); byte[] sendData = sb.toString().trim().getBytes(); if (isDebugEnabled()) { log.debug("StatsD Message: " + line.trim()); } DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port); socket.send(sendPacket); } } } } } finally { if (socket != null && ! socket.isClosed()) { socket.close(); } } } #location 39 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void finishOutput() throws IOException { }
#vulnerable code @Override protected void finishOutput() throws IOException { try { this.out.flush(); } catch (IOException e) { log.error("flush failed"); throw e; } // Read and log the response from the server for diagnostic purposes. InputStreamReader socketInputStream = new InputStreamReader(socket.getInputStream()); BufferedReader bufferedSocketInputStream = new BufferedReader(socketInputStream); String line; while (socketInputStream.ready() && (line = bufferedSocketInputStream.readLine()) != null) { log.warn("OpenTSDB says: " + line); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void processQuery(MBeanServerConnection mbeanServer, Query query) throws Exception { List<Result> resList = new ArrayList<Result>(); ObjectName oName = new ObjectName(query.getObj()); Set<ObjectName> queryNames = mbeanServer.queryNames(oName, null); for (ObjectName queryName : queryNames) { MBeanInfo info = mbeanServer.getMBeanInfo(queryName); ObjectInstance oi = mbeanServer.getObjectInstance(queryName); List<String> queryAttributes = query.getAttr(); if (queryAttributes == null || queryAttributes.size() == 0) { MBeanAttributeInfo[] attrs = info.getAttributes(); for (MBeanAttributeInfo attrInfo : attrs) { query.addAttr(attrInfo.getName()); } } try { if (query.getAttr() != null && query.getAttr().size() > 0) { log.debug("Started query: " + query); AttributeList al = mbeanServer.getAttributes(queryName, query.getAttr().toArray(new String[query.getAttr().size()])); for (Attribute attribute : al.asList()) { getResult(resList, info, oi, (Attribute)attribute, query); } if (log.isDebugEnabled()) { log.debug("Finished query."); } query.setResults(resList); // Now run the filters. runFiltersForQuery(query); if (log.isDebugEnabled()) { log.debug("Finished running filters: " + query); } } } catch (UnmarshalException ue) { if (ue.getCause() != null && ue.getCause() instanceof ClassNotFoundException) { log.debug("Bad unmarshall, continuing. This is probably ok and due to something like this: " + "http://ehcache.org/xref/net/sf/ehcache/distribution/RMICacheManagerPeerListener.html#52", ue.getMessage()); } } } }
#vulnerable code public static void processQuery(MBeanServerConnection mbeanServer, Query query) throws Exception { List<Result> resList = new ArrayList<Result>(); ObjectName oName = new ObjectName(query.getObj()); Set<ObjectName> queryNames = mbeanServer.queryNames(oName, null); for (ObjectName queryName : queryNames) { MBeanInfo info = mbeanServer.getMBeanInfo(queryName); ObjectInstance oi = mbeanServer.getObjectInstance(queryName); List<String> queryAttributes = query.getAttr(); if (queryAttributes == null || queryAttributes.size() == 0) { MBeanAttributeInfo[] attrs = info.getAttributes(); for (MBeanAttributeInfo attrInfo : attrs) { query.addAttr(attrInfo.getName()); } } AttributeList al = mbeanServer.getAttributes(queryName, query.getAttr().toArray(new String[query.getAttr().size()])); for (Attribute attribute : al.asList()) { getResult(resList, info, oi, (Attribute)attribute, query); } } if (log.isDebugEnabled()) { log.debug("Executed query: " + query); } query.setResults(resList); // Now run the filters. runFiltersForQuery(query); if (log.isDebugEnabled()) { log.debug("Finished running filters: " + query); } } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private IndexIterator getFuzzy(final byte[] tok, final int e) { int[][] ft = null; byte[] to; int i = 0; final int is = li.readBytes(0, 1L)[0]; int ts = li.readBytes(1L, 2L)[0]; int dif = Math.abs(tok.length - ts); while (i < is && dif > e) { i++; ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0]; dif = Math.abs(tok.length - ts); } if (i == is) return null; int p; int pe; while (i < is && dif <= e) { p = li.readInt(1L + i * 5L + 1L); pe = li.readInt(1L + (i + 1) * 5L + 1L); while(p < pe) { to = ti.readBytes(p, p + ts); if (calcEQ(to, 0, tok, e)) { //System.out.println(new String(to)); // read data ft = FTUnion.calculateFTOr(ft, finish(getData(getPointerOnData(p, ts), getDataSize(p, ts)))); } p += ts + 4L + 5L; } i++; ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0]; dif = Math.abs(tok.length - ts); } return new IndexArrayIterator(ft); }
#vulnerable code private IndexIterator getFuzzy(final byte[] tok, final int e) { int[][] ft = null; byte[] to; int dif; int i = 0; final int is = li.readBytes(0, 1L)[0]; int ts = li.readBytes(1L, 2L)[0]; dif = (tok.length - ts < 0) ? ts - tok.length : tok.length - ts; while (i < is && dif > e) { i++; ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0]; dif = (tok.length - ts < 0) ? ts - tok.length : tok.length - ts; } if (i == is) return null; int p; int pe; while (i < is && dif <= e) { p = li.readInt(1L + i * 5L + 1L); pe = li.readInt(1L + (i + 1) * 5L + 1L); while(p < pe) { to = ti.readBytes(p, p + ts); if (calcEQ(to, 0, tok, e)) { //System.out.println(new String(to)); // read data ft = FTUnion.calculateFTOr(ft, finish(getData(getPointerOnData(p, ts), getDataSize(p, ts)))); } p += ts + 4L + 5L; } i++; ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0]; dif = (tok.length - ts < 0) ? ts - tok.length : tok.length - ts; } return new IndexArrayIterator(ft[0], ft[1]); } #location 43 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void actionPerformed(final ActionEvent e) { if(e == null) { if(GUIProp.execrt) query(false); return; } final Object source = e.getSource(); int cp = 0; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c++) if(panel.getComponent(c) == source) cp = c; if((cp & 1) == 0) { // ComboBox with tags/attributes final BaseXCombo combo = (BaseXCombo) source; panel.remove(cp + 1); if(combo.getSelectedIndex() != 0) { final String item = combo.getSelectedItem().toString(); final StatsKey key = GUI.context.data().stats.get(Token.token(item)); switch(key.kind) { case INT: addSlider(key.min, key.max, cp + 1, item.equals("@size"), item.equals("@mtime"), true); break; case DBL: addSlider(key.min, key.max, cp + 1, false, false, false); break; case CAT: addCombo(keys(key.cats), cp + 1); break; case TEXT: addInput(cp + 1); break; case NONE: final BaseXLabel label = new BaseXLabel(""); label.setBorder(new EmptyBorder(3, 0, 0, 0)); panel.add(label, cp + 1); break; } if(cp + 2 == cs) addKeys(cp + 2); panel.validate(); panel.repaint(); } else { panel.add(new BaseXLabel(""), cp + 1); if(cp + 4 == cs && ((BaseXCombo) panel.getComponent(cp + 2)). getSelectedIndex() == 0) { panel.remove(cp + 2); panel.remove(cp + 2); panel.validate(); panel.repaint(); } } } if(GUIProp.execrt) query(false); }
#vulnerable code public void actionPerformed(final ActionEvent e) { if(e == null) { if(GUIProp.execrt) query(false); return; } final Object source = e.getSource(); int cp = 0; final int cs = panel.getComponentCount(); for(int c = 0; c < cs; c++) if(panel.getComponent(c) == source) cp = c; if((cp & 1) == 0) { // ComboBox with tags/attributes final BaseXCombo combo = (BaseXCombo) source; panel.remove(cp + 1); if(combo.getSelectedIndex() != 0) { final String item = combo.getSelectedItem().toString(); final StatsKey key = GUI.context.data().stats.get(Token.token(item)); switch(key.kind) { case INT: addSlider(key.min, key.max, cp + 1, item.equals("@size"), item.equals("@mtime"), true); break; case DBL: addSlider(key.min, key.max, cp + 1, false, false, false); break; case CAT: addCombo(keys(key.cats), cp + 1); break; case TEXT: addInput(cp + 1); break; case NONE: //final BaseXLabel label = new BaseXLabel("(no texts available)"); final BaseXLabel label = new BaseXLabel(""); label.setBorder(new EmptyBorder(3, 0, 0, 0)); panel.add(label, cp + 1); break; } if(cp + 2 == cs) addKeys(cp + 2); panel.validate(); panel.repaint(); } else { panel.add(new BaseXLabel(""), cp + 1); if(cp + 4 == cs && ((BaseXCombo) panel.getComponent(cp + 2)). getSelectedIndex() == 0) { panel.remove(cp + 2); panel.remove(cp + 2); panel.validate(); panel.repaint(); } } } if(GUIProp.execrt) query(false); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public IndexIterator ids(final IndexToken ind) { if(ind.range()) return idRange((RangeToken) ind); final FTTokenizer ft = (FTTokenizer) ind; final byte[] tok = ft.get(); if(ft.fz) { int k = Prop.lserr; if(k == 0) k = Math.max(1, tok.length >> 2); final int[][] ids = getNodeFuzzy(0, null, -1, tok, 0, 0, 0, k); return new IndexArrayIterator(ids); } if(ft.wc) { final int pw = Token.indexOf(tok, '.'); if(pw != -1) { final int[][] ids = getNodeFromTrieWithWildCard(tok, pw); return new IndexArrayIterator(ids); } } if(!cs && ft.cs) { // case insensitive index create - check real case with dbdata int[][] ids = getNodeFromTrieRecursive(0, Token.lc(tok), false); if(ids == null) { return null; } byte[] tokenFromDB; byte[] textFromDB; int[][] rIds = new int[2][ids[0].length]; int count = 0; int readId; int i = 0; // check real case of each result node while(i < ids[0].length) { // get date from disk readId = ids[0][i]; textFromDB = data.text(ids[0][i]); tokenFromDB = new byte[tok.length]; System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length); // check unique node ones while(i < ids[0].length && readId == ids[0][i]) { System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length); readId = ids[0][i]; // check unique node ones // compare token from db with token from query if(Token.eq(tokenFromDB, tok)) { rIds[0][count] = ids[0][i]; rIds[1][count++] = ids[1][i]; // jump over same ids while(i < ids[0].length && readId == ids[0][i]) i++; break; } i++; } } return new IndexArrayIterator(rIds, count); } final int[][] tmp = getNodeFromTrieRecursive(0, tok, ft.cs); return new IndexArrayIterator(tmp); }
#vulnerable code @Override public IndexIterator ids(final IndexToken ind) { if(ind.range()) return idRange((RangeToken) ind); final FTTokenizer ft = (FTTokenizer) ind; final byte[] tok = ft.get(); if(ft.fz) { int k = Prop.lserr; if(k == 0) k = Math.max(1, tok.length >> 2); final int[][] ids = getNodeFuzzy(0, null, -1, tok, 0, 0, 0, k); return new IndexArrayIterator(ids[0], ids[1]); } if(ft.wc) { final int pw = Token.indexOf(tok, '.'); if(pw != -1) { final int[][] ids = getNodeFromTrieWithWildCard(tok, pw); return new IndexArrayIterator(ids[0], ids[1]); } } if(!cs && ft.cs) { // case insensitive index create - check real case with dbdata int[][] ids = getNodeFromTrieRecursive(0, Token.lc(tok), false); if(ids == null) { return null; } byte[] tokenFromDB; byte[] textFromDB; int[][] rIds = new int[2][ids[0].length]; int count = 0; int readId; int i = 0; // check real case of each result node while(i < ids[0].length) { // get date from disk readId = ids[0][i]; textFromDB = data.text(ids[0][i]); tokenFromDB = new byte[tok.length]; System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length); // check unique node ones while(i < ids[0].length && readId == ids[0][i]) { System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length); readId = ids[0][i]; // check unique node ones // compare token from db with token from query if(Token.eq(tokenFromDB, tok)) { rIds[0][count] = ids[0][i]; rIds[1][count++] = ids[1][i]; // jump over same ids while(i < ids[0].length && readId == ids[0][i]) i++; break; } i++; } } if(count == 0) return null; final int[][] tmp = new int[2][count]; System.arraycopy(rIds[0], 0, tmp[0], 0, count); System.arraycopy(rIds[1], 0, tmp[1], 0, count); return new IndexArrayIterator(tmp[0], tmp[1]); } final int[][] tmp = getNodeFromTrieRecursive(0, tok, ft.cs); return new IndexArrayIterator(tmp[0], tmp[1]); } #location 71 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void drawTemperature(final Graphics g, final int level) { // array with all rects of a level // System.out.print("RectCount: " + rectCount + " level " // + level + " size :" // + parentList.size); final RealRect[] tRect = new RealRect[rectCount]; final Data data = GUI.context.data(); final int size = parentList.size; final HashMap<Integer, Double> temp = new HashMap<Integer, Double>(); double x = 0; final int y = 1 * level * fontHeight * 2; final double width = this.getSize().width - 1; final double ratio = width / size; final int minSpace = 35; // minimum Space for Tags final boolean space = ratio > minSpace ? true : false; int r = 0; for(int i = 0; i < size; i++) { final int pre = parentList.list[i]; if(pre == -1) { x += ratio; continue; } int nodeKind = data.kind(pre); final int nodeSize = data.size(pre, nodeKind); final double nodePercent = nodeSize / (double) sumNodeSizeInLine; g.setColor(Color.black); final int l = (int) ratio; //rectangle length final int h = fontHeight; //rectangle height g.drawRect((int) x, y, l, h); tRect[r++] = new RealRect(pre, (int) x, y, (int) x + l, y + h); int c = (int) Math.rint(255 * nodePercent * 40); c = c > 255 ? 255 : c; g.setColor(new Color(c, 0, 255 - c)); g.fillRect((int) x + 1, y + 1, l - 1, h - 1); final double boxMiddle = x + ratio / 2f; if(space) { String s = ""; switch(nodeKind) { case Data.ELEM: s = Token.string(data.tag(pre)); g.setColor(Color.WHITE); break; case Data.COMM: s = Token.string(data.text(pre)); g.setColor(Color.GREEN); break; case Data.PI: s = Token.string(data.text(pre)); g.setColor(Color.PINK); break; case Data.DOC: s = Token.string(data.text(pre)); g.setColor(Color.BLUE); break; default: s = Token.string(data.text(pre)); g.setColor(Color.YELLOW); } Token.string(data.text(pre)); int textWidth = 0; while((textWidth = BaseXLayout.width(g, s)) + 4 > ratio) { s = s.substring(0, s.length() / 2).concat("?"); } g.drawString(s, (int) boxMiddle - textWidth / 2, y + fontHeight - 2); } if(parentPos != null) { final double parentMiddle = parentPos.get(data.parent(pre, nodeKind)); g.setColor(new Color(c, 0, 255 - c, 100)); g.drawLine((int) boxMiddle, y - 1, (int) parentMiddle, y - fontHeight + 1); // final int line = Math.round(fontHeight / 4f); // g.drawLine((int) boxMiddle, y, (int) boxMiddle, y - line); // g.drawLine((int) boxMiddle, y - line, // (int) parentMiddle, y - line); // g.drawLine((int) parentMiddle, y - line, (int) parentMiddle, y // - fontHeight); } if(nodeSize > 0) temp.put(pre, boxMiddle); x += ratio; } rects.add(tRect); parentPos = temp; }
#vulnerable code private void drawTemperature(final Graphics g, final int level) { // array with all rects of a level // System.out.print("RectCount: " + rectCount + " level " // + level + " size :" // + parentList.size); final RealRect[] tRect = new RealRect[rectCount]; final Data data = GUI.context.data(); final int size = parentList.size; final HashMap<Integer, Double> temp = new HashMap<Integer, Double>(); double x = 0; final int y = 1 * level * fontHeight * 2; final double width = this.getSize().width - 1; final double ratio = width / size; final int minSpace = 35; // minimum Space for Tags final boolean space = ratio > minSpace ? true : false; int r = 0; for(int i = 0; i < size; i++) { final int pre = parentList.list[i]; if(pre == -1) { x += ratio; continue; } final int nodeSize = data.size(pre, Data.ELEM); final double nodePercent = nodeSize / (double) sumNodeSizeInLine; g.setColor(Color.black); final int l = (int) ratio; //rectangle length final int h = fontHeight; //rectangle height g.drawRect((int) x, y, l, h); tRect[r++] = new RealRect(pre, (int) x, y, (int) x + l, y + h); int c = (int) Math.rint(255 * nodePercent * 40); c = c > 255 ? 255 : c; g.setColor(new Color(c, 0, 255 - c)); g.fillRect((int) x + 1, y + 1, l - 1, h - 1); final double boxMiddle = x + ratio / 2f; g.setColor(Color.WHITE); if(space) { String s = Token.string(data.tag(pre)); int textWidth = 0; while((textWidth = BaseXLayout.width(g, s)) + 4 > ratio) { s = s.substring(0, s.length() / 2).concat("?"); } g.drawString(s, (int) boxMiddle - textWidth / 2, y + fontHeight - 2); } if(parentPos != null) { final double parentMiddle = parentPos.get(data.parent(pre, Data.ELEM)); g.setColor(new Color(c, 0, 255 - c, 100)); g.drawLine((int) boxMiddle, y - 1, (int) parentMiddle, y - fontHeight + 1); // final int line = Math.round(fontHeight / 4f); // g.drawLine((int) boxMiddle, y, (int) boxMiddle, y - line); // g.drawLine((int) boxMiddle, y - line, // (int) parentMiddle, y - line); // g.drawLine((int) parentMiddle, y - line, (int) parentMiddle, y // - fontHeight); } if(nodeSize > 0) temp.put(pre, boxMiddle); x += ratio; } rects.add(tRect); parentPos = temp; } #location 60 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void locateMain(final String cmd) throws IOException { GetOpts g = new GetOpts(cmd, "chl:V:", 1); char version = (char) -1; int limit = -1; // get all Options int ch = g.getopt(); while (ch != -1) { switch (ch) { case 'c': //Suppress normal output; instead print a //count of matching file names. cFlag = true; break; case 'h': printHelp(); fAccomplished = true; break; case 'l': // Limit output to number of file names and exit. limit = Integer.parseInt(g.getOptarg()); lFlag = true; break; case 'V': version = g.getOptarg().charAt(0); break; case ':': fError = true; out.print("ls: missing argument"); break; case '?': fError = true; out.print("ls: illegal option"); break; } if(fError || fAccomplished) { // more options ? return; } ch = g.getopt(); } fileToFind = g.getPath(); if(fileToFind == null) { out.print("usage: locate [-l limit] [-c] [-h] -V 1 ..."); out.print(NL); return; } fileToFindByte = Token.token(fileToFind); // Version - 1 = use table // 2 = use xquery // 3 = use xquery + index switch (version) { case '1': fileToFind = FSUtils.transformToRegex(fileToFind); locateTable(FSUtils.getROOTDIR(), limit); break; case '2': locateXQuery(limit); break; case '3': out.print("Not yet implemented"); break; default: locateXQuery(limit); break; } if(cFlag) { printCount(); } }
#vulnerable code public void locateMain(final String cmd) throws IOException { GetOpts g = new GetOpts(cmd, "chl:V:", 1); char version = (char) -1; int limit = -1; // get all Options int ch = g.getopt(); while (ch != -1) { switch (ch) { case 'c': //Suppress normal output; instead print a //count of matching file names. cFlag = true; break; case 'h': printHelp(); fAccomplished = true; break; case 'l': // Limit output to number of file names and exit. limit = Integer.parseInt(g.getOptarg()); lFlag = true; break; case 'V': version = g.getOptarg().charAt(0); break; case ':': fError = true; out.print("ls: missing argument"); break; case '?': fError = true; out.print("ls: illegal option"); break; } if(fError || fAccomplished) { // more options ? return; } ch = g.getopt(); } fileToFind = g.getPath(); fileToFindByte = Token.token(fileToFind); if(fileToFind == null) { out.print("usage: locate [-l limit] [-c] [-h] -V 1 ..."); out.print(NL); } // Version - 1 = use table // 2 = use xquery // 3 = use xquery + index switch (version) { case '1': locateTable(FSUtils.getROOTDIR(), limit); break; case '2': locateXQuery(limit); break; case '3': out.print("Not yet implemented"); break; default: locateXQuery(limit); break; } if(cFlag) { printCount(); } } #location 45 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { InputStream in = XmlSpike.class.getResourceAsStream("Config.xml"); Properties props = load(in); File file = new File("target/test-resources/props.xml"); file.getParentFile().mkdirs(); ByteArrayOutputStream propertiesxmlformat = new ByteArrayOutputStream(); props.storeToXML(propertiesxmlformat, "test"); String propsXmlString = propertiesxmlformat.toString(); System.out.println("java xml properties format:" + propsXmlString); Properties props2 = new Properties(); props2.loadFromXML(new FileInputStream(file)); Properties props3 = load(new FileInputStream(file)); props.store(System.out, "props"); props2.store(System.out, "props2"); props3.store(System.out, "props3"); }
#vulnerable code public static void main(String[] args) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); InputStream in = XmlSpike.class.getResourceAsStream("Config.xml"); String input = convertStreamToString(in); System.out.println("input:\n" + input); StringWriter output = new StringWriter(); PrintWriter pw = new PrintWriter(output); XmlToPropsHandler h = new XmlToPropsHandler(pw); parser.parse(new StringInputStream(input), h); pw.flush(); System.out.println("output:\n" + output); File file = new File("target/test-resources/props.xml"); file.getParentFile().mkdirs(); Properties props = new Properties(); props.load(new StringInputStream(output.toString())); ByteArrayOutputStream propertiesxmlformat = new ByteArrayOutputStream(); props.storeToXML(propertiesxmlformat, "test"); String propsXmlString = propertiesxmlformat.toString(); System.out.println("java xml properties format:" + propsXmlString); boolean isJavaProp = propsXmlString.contains("http://java.sun.com/dtd/properties.dtd"); System.out.println("isJavaProp: " + isJavaProp); } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldReturnTheResourceForAClass() throws IOException { ConfigURLStreamHandler handler = new ConfigURLStreamHandler(SampleConfig.class.getClassLoader(), new SystemVariablesExpander()); ConfigURLStreamHandler spy = spy(handler); ConfigFactory.getPropertiesFor(SampleConfig.class, spy); URL expected = new URL(null, "classpath:org/aeonbits/owner/SampleConfig.properties", handler); verify(spy, times(1)).openConnection(eq(expected)); }
#vulnerable code @Test public void shouldReturnTheResourceForAClass() throws IOException { ConfigURLStreamHandler handler = new ConfigURLStreamHandler(SampleConfig.class.getClassLoader(), new SystemVariablesExpander()); ConfigURLStreamHandler spy = spy(handler); ConfigFactory.getStreamFor(SampleConfig.class, spy); URL expected = new URL(null, "classpath:org/aeonbits/owner/SampleConfig.properties", handler); verify(spy, times(1)).openConnection(eq(expected)); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testReload() throws Throwable { assertEquals(Integer.valueOf(10), reloadableConfig.someValue()); save(new Properties() {{ setProperty("someValue", "20"); }}); reloadableConfig.reload(); assertEquals(Integer.valueOf(20), reloadableConfig.someValue()); }
#vulnerable code @Test public void testReload() throws Throwable { assertEquals(Integer.valueOf(10), reloadableConfig.someValue()); synchronized (target) { save(new Properties() {{ setProperty("someValue", "20"); }}); reloadableConfig.reload(); } assertEquals(Integer.valueOf(20), reloadableConfig.someValue()); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code PropertiesManager(Class<? extends Config> clazz, Properties properties, Map<?, ?>... imports) { this.clazz = clazz; this.properties = properties; this.imports = imports; handler = new ConfigURLStreamHandler(clazz.getClassLoader(), expander); sources = clazz.getAnnotation(Sources.class); LoadPolicy loadPolicy = clazz.getAnnotation(LoadPolicy.class); loadType = (loadPolicy != null) ? loadPolicy.value() : FIRST; HotReload hotReload = clazz.getAnnotation(HotReload.class); if (sources != null && hotReload != null) syncHotReload = new SyncHotReload(clazz, handler, this); else syncHotReload = null; }
#vulnerable code String getProperty(String key) { if (syncHotReload != null) syncHotReload.checkAndReload(lastLoadTime); readLock.lock(); try { return properties.getProperty(key); } finally { readLock.unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void multiThreadedReloadTest() throws Throwable { Object lock = new Object(); ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100)); WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70)); start(readers, writers); notifyAll(lock); join(readers, writers); assertNoErrors(readers, writers); }
#vulnerable code @Test public void multiThreadedReloadTest() throws Throwable { Object lock = new Object(); ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100)); WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70)); start(readers, writers); synchronized (lock) { lock.notifyAll(); } join(readers, writers); assertNoErrors(readers, writers); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void saveJar(File target, String entryName, Properties props) throws IOException { File parent = target.getParentFile(); parent.mkdirs(); storeJar(target, entryName, props); }
#vulnerable code public static void saveJar(File target, String entryName, Properties props) throws IOException { byte[] bytes = toBytes(props); InputStream input = new ByteArrayInputStream(bytes); FileOutputStream fos = new FileOutputStream(target); JarOutputStream output = new JarOutputStream(fos); try { ZipEntry entry = new ZipEntry(entryName); output.putNextEntry(entry); byte[] buffer = new byte[4096]; int size; while ((size = input.read(buffer)) != -1) output.write(buffer, 0, size); output.flush(); } finally { input.close(); output.close(); fos.close(); } } #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 shouldReturnTheResourceForAClass() throws IOException { PropertiesManagerForTest manager = new PropertiesManagerForTest(SampleConfig.class, new Properties(), scheduler, expander, loaders); manager.load(); verify(loaders, times(1)).findLoader(any(URL.class)); verify(loaders, times(1)).findLoader(argThat(urlMatches( "org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig.properties"))); }
#vulnerable code @Test public void shouldReturnTheResourceForAClass() throws IOException { PropertiesManagerForTest manager = new PropertiesManagerForTest(SampleConfig.class, new Properties(), scheduler, expander); assertEquals(1, manager.getUrls().size()); for(URL url : manager.getUrls()) assertTrue(url.getPath().contains("org/aeonbits/owner/loadstrategies/DefaultLoadStrategyTest$SampleConfig")); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void save(File target, Properties p) throws IOException { File parent = target.getParentFile(); parent.mkdirs(); if (isWindows()) { store(new FileOutputStream(target), p); } else { File tempFile = createTempFile(target.getName(), ".temp", parent); store(new FileOutputStream(tempFile), p); rename(tempFile, target); } }
#vulnerable code public static void save(File target, Properties p) throws IOException { File parent = target.getParentFile(); parent.mkdirs(); if (isWindows()) { p.store(new FileWriter(target), "saved for test"); } else { File tempFile = File.createTempFile(target.getName(), "temp", parent); p.store(new FileWriter(tempFile), "saved for test"); if (!tempFile.renameTo(target)) throw new IOException(String.format("Failed to overwrite %s to %s", tempFile.toString(), target.toString())); } } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object execute() { boolean lockRemoved = false; try { // Configure command before execution introspector.getHystrixProperties() .entrySet() .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); // Get lock and check breaker delay if (introspector.hasCircuitBreaker()) { breakerHelper.lock(); // acquire exclusive access to command data // OPEN_MP -> HALF_OPEN_MP if (breakerHelper.getState() == State.OPEN_MP) { long delayNanos = TimeUtil.convertToNanos(introspector.getCircuitBreaker().delay(), introspector.getCircuitBreaker().delayUnit()); if (breakerHelper.getCurrentStateNanos() > delayNanos) { breakerHelper.setState(State.HALF_OPEN_MP); } } logCircuitBreakerState("Enter"); } // Record state of breaker boolean wasBreakerOpen = isCircuitBreakerOpen(); // Track invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.trackInvocation(this); } // Execute command Object result = null; Throwable throwable = null; long startNanos = System.nanoTime(); try { result = super.execute(); } catch (Throwable t) { throwable = t; } executionTime = System.nanoTime() - startNanos; boolean hasFailed = (throwable != null); if (introspector.hasCircuitBreaker()) { // Keep track of failure ratios breakerHelper.pushResult(throwable == null); // Query breaker states boolean breakerOpening = false; boolean isClosedNow = !wasBreakerOpen; /* * Special logic for MP circuit breakers to support failOn. If not a * throwable to fail on, restore underlying breaker and return. */ if (hasFailed) { final Throwable throwableFinal = throwable; Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn(); boolean failOn = Arrays.asList(throwableClasses) .stream() .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); if (!failOn) { updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening); logCircuitBreakerState("Exit 1"); throw ExceptionUtil.toWrappedException(throwable); } } // CLOSED_MP -> OPEN_MP if (breakerHelper.getState() == State.CLOSED_MP) { double failureRatio = breakerHelper.getFailureRatio(); if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { breakerHelper.setState(State.OPEN_MP); breakerOpening = true; } } // HALF_OPEN_MP -> OPEN_MP if (hasFailed) { if (breakerHelper.getState() == State.HALF_OPEN_MP) { breakerHelper.setState(State.OPEN_MP); } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening); logCircuitBreakerState("Exit 2"); throw ExceptionUtil.toWrappedException(throwable); } // Otherwise, increment success count breakerHelper.incSuccessCount(); // HALF_OPEN_MP -> CLOSED_MP if (breakerHelper.getState() == State.HALF_OPEN_MP) { if (breakerHelper.getSuccessCount() == introspector.getCircuitBreaker().successThreshold()) { breakerHelper.setState(State.CLOSED_MP); breakerHelper.resetCommandData(); lockRemoved = true; isClosedNow = true; } } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening); } // Untrack invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.untrackInvocation(this); } // Display circuit breaker state at exit logCircuitBreakerState("Exit 3"); // Outcome of execution if (throwable != null) { throw ExceptionUtil.toWrappedException(throwable); } else { return result; } } finally { // Free lock unless command data was reset if (introspector.hasCircuitBreaker() && !lockRemoved) { breakerHelper.unlock(); } } }
#vulnerable code @Override public Object execute() { // Configure command before execution introspector.getHystrixProperties() .entrySet() .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); // Ensure our internal state is consistent with Hystrix if (introspector.hasCircuitBreaker()) { breakerHelper.ensureConsistentState(); LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Record state of breaker boolean wasBreakerOpen = isCircuitBreakerOpen(); // Track invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.trackInvocation(this); } // Execute command Object result = null; Throwable throwable = null; long startNanos = System.nanoTime(); try { result = super.execute(); } catch (Throwable t) { throwable = t; } executionTime = System.nanoTime() - startNanos; boolean hasFailed = (throwable != null); if (introspector.hasCircuitBreaker()) { // Keep track of failure ratios breakerHelper.pushResult(throwable == null); // Query breaker states boolean breakerWillOpen = false; boolean isClosedNow = !isCircuitBreakerOpen(); /* * Special logic for MP circuit breakers to support failOn. If not a * throwable to fail on, restore underlying breaker and return. */ if (hasFailed) { final Throwable throwableFinal = throwable; Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn(); boolean failOn = Arrays.asList(throwableClasses) .stream() .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); if (!failOn) { restoreBreaker(); // clears Hystrix counters updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); throw ExceptionUtil.toWrappedException(throwable); } } /* * Special logic for MP circuit breakers to support an arbitrary success * threshold used to return a breaker back to its CLOSED state. Hystrix * only supports a threshold of 1 here, so additional logic is required. */ synchronized (breakerHelper.getSyncObject()) { // If failure ratio exceeded, then switch state to OPEN_MP if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) { double failureRatio = breakerHelper.getFailureRatio(); if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { breakerWillOpen = true; breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); runTripBreaker(); } } // If latest run failed, may need to switch state to OPEN_MP if (hasFailed) { if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) { // If failed and in HALF_OPEN_MP, we need to force breaker to open runTripBreaker(); breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); throw ExceptionUtil.toWrappedException(throwable); } // Check next state of breaker based on outcome if (wasBreakerOpen && isClosedNow) { // Last called was successful breakerHelper.incSuccessCount(); // We stay in HALF_OPEN_MP until successThreshold is reached if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) { breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP); } else { breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP); breakerHelper.resetCommandData(); } } } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); } // Untrack invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.untrackInvocation(this); } // Display circuit breaker state at exit if (introspector.hasCircuitBreaker()) { LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Outcome of execution if (throwable != null) { throw ExceptionUtil.toWrappedException(throwable); } else { return result; } } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION