Skip to content

Commit

Permalink
fix: check that iteration variable in for-each loop not used outside (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
skylot committed Jul 17, 2019
1 parent aad2d24 commit 24dc686
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,13 @@ private static boolean checkIterableForEach(MethodNode mth, LoopRegion loopRegio
if (iterVar == null) {
return false;
}
if (!usedOnlyInLoop(mth, loopRegion, iterVar)) {
return false;
}
if (!assignOnlyInLoop(mth, loopRegion, iterVar)) {
return false;
}

if (nextCall.contains(AFlag.WRAPPED)) {
InsnArg wrapArg = BlockUtils.searchWrappedInsnParent(mth, nextCall);
if (wrapArg != null && wrapArg.getParentInsn() != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package jadx.tests.integration.loops;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.junit.jupiter.api.Test;

import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;

import static jadx.tests.api.utils.JadxMatchers.containsOne;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;

public class TestLoopDetection5 extends IntegrationTest {

public static class TestCls {

public String test(String str) {
Iterator<String> it = getStrings().iterator();
String otherStr = null;
while (it.hasNext()) {
otherStr = it.next();
if (otherStr.equalsIgnoreCase(str)) {
break;
}
}
return otherStr;
}

private List<String> getStrings() {
return Arrays.asList("str", "otherStr", "STR", "OTHERSTR");
}

public void check() {
assertThat(test("OTHERSTR"), is("otherStr"));
}
}

@Test
public void test() {
noDebugInfo();
ClassNode cls = getClassNode(TestCls.class);
String code = cls.getCode().toString();

assertThat(code, not(containsString("for (")));
assertThat(code, containsOne("it.next();"));
}
}

0 comments on commit 24dc686

Please sign in to comment.