Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integrate fast v2 #2836

Merged
merged 4 commits into from
Mar 26, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions semgrep/semgrep/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,11 @@ def cli() -> None:
"containing a 'nosem' comment at the end."
),
)
output.add_argument(
"--experimental",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we name this something less generic like --core-direct-rules?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's probably fine; this is really only meant for internal use. I think Pad was thinking that this would be an entrypoint for future experimental work, too. In any case, we can always change it later - it's just a string after all.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep, --core-direct-rules sounds good.

action="store_true",
help="Pass rules directly to Semgrep core. This will use the logic evaluation available in Semgrep core.",
)

output.add_argument(
MAX_LINES_FLAG_NAME,
Expand Down Expand Up @@ -476,4 +481,5 @@ def cli() -> None:
skip_unknown_extensions=args.skip_unknown_extensions,
severity=args.severity,
report_time=args.json_time,
experimental=args.experimental,
)
92 changes: 91 additions & 1 deletion semgrep/semgrep/core_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,10 +535,97 @@ def _run_rules(
match_time_matrix,
)

def _run_rules_direct_to_semgrep_core(
self,
rules: List[Rule],
target_manager: TargetManager,
profiler: ProfileManager,
) -> Tuple[
Dict[Rule, List[RuleMatch]],
Dict[Rule, List[Any]],
List[SemgrepError],
Set[Path],
Dict[Any, Any],
]:
from itertools import chain
from collections import defaultdict

outputs: Dict[Rule, List[RuleMatch]] = defaultdict(list)
errors: List[SemgrepError] = []
for rule, language in tuple(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Later on we can try to pass multiple rules at the same time if they have the same language and same set of target files
so we can start to dedup identical patterns and even even identical subformulas used in different rules (e.g., in nodejsscan, ajin reuse many times the same subformulas).

chain(
*([(rule, language) for language in rule.languages] for rule in rules)
)
):
with tempfile.NamedTemporaryFile(
"w", suffix=".yaml"
) as rule_file, tempfile.NamedTemporaryFile("w") as target_file:
targets = self.get_files_for_language(language, rule, target_manager)
target_file.write("\n".join(map(lambda p: str(p), targets)))
target_file.flush()
yaml = YAML()
yaml.dump({"rules": [rule._raw]}, rule_file)
rule_file.flush()

cmd = [SEMGREP_PATH] + [
"-lang",
language,
"-fast",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory -fast is another thing, but we can bundle it in --experimental.

"-json",
"-config",
rule_file.name,
minusworld marked this conversation as resolved.
Show resolved Hide resolved
"-j",
str(self._jobs),
"-target_file",
target_file.name,
"-timeout",
str(self._timeout),
"-max_memory",
str(self._max_memory),
]

r = sub_run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_bytes, err_bytes, returncode = r.stdout, r.stderr, r.returncode
output_json = self._parse_core_output(out_bytes, err_bytes, returncode)

if returncode != 0:
if "error" in output_json:
self._raise_semgrep_error_from_json(output_json, [], rule)
else:
raise SemgrepError(
f"unexpected json output while invoking semgrep-core with rule '{rule.id}':\n{PLEASE_FILE_ISSUE_TEXT}"
)

# end with tempfile.NamedTemporaryFile(...) ...
outputs[rule].extend(
[
RuleMatch.from_pattern_match(
rule.id,
PatternMatch(pattern_match),
message=rule.message,
metadata=rule.metadata,
severity=rule.severity,
fix=rule.fix,
fix_regex=rule.fix_regex,
)
for pattern_match in output_json["matches"]
]
)
errors.extend(
CoreException.from_json(e, language, rule.id).into_semgrep_error()
for e in output_json["errors"]
)
# end for rule, language ...

return outputs, {}, errors, set(Path(p) for p in target_manager.targets), {}

# end _run_rules_direct_to_semgrep_core

def invoke_semgrep(
self,
target_manager: TargetManager,
rules: List[Rule],
experimental: bool = False,
) -> Tuple[
Dict[Rule, List[RuleMatch]],
Dict[Rule, List[Dict[str, Any]]],
Expand All @@ -553,13 +640,16 @@ def invoke_semgrep(
start = datetime.now()
profiler = ProfileManager()

runner_fxn = (
self._run_rules_direct_to_semgrep_core if experimental else self._run_rules
)
(
findings_by_rule,
debug_steps_by_rule,
errors,
all_targets,
match_time_matrix,
) = self._run_rules(rules, target_manager, profiler)
) = runner_fxn(rules, target_manager, profiler)

logger.debug(
f"semgrep ran in {datetime.now() - start} on {len(all_targets)} files"
Expand Down
3 changes: 2 additions & 1 deletion semgrep/semgrep/semgrep_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ def main(
skip_unknown_extensions: bool = False,
severity: Optional[List[str]] = None,
report_time: bool = False,
experimental: bool = False,
) -> None:
if include is None:
include = []
Expand Down Expand Up @@ -263,7 +264,7 @@ def main(
timeout_threshold=timeout_threshold,
report_time=report_time,
).invoke_semgrep(
target_manager, filtered_rules
target_manager, filtered_rules, experimental
)

output_handler.handle_semgrep_errors(semgrep_errors)
Expand Down
3 changes: 3 additions & 0 deletions semgrep/semgrep/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ def generate_file_pairs(
unsafe: bool,
json_output: bool,
save_test_output_tar: bool = True,
experimental: bool = False,
) -> None:
configs = list(config.rglob("*"))
targets = list(target.rglob("*"))
Expand Down Expand Up @@ -303,6 +304,7 @@ def generate_file_pairs(
no_rewrite_rule_ids=True,
strict=strict,
dangerously_allow_arbitrary_code_execution_from_rules=unsafe,
experimental=experimental,
)
with multiprocessing.Pool(multiprocessing.cpu_count()) as pool:
results = pool.starmap(invoke_semgrep_fn, config_with_tests)
Expand Down Expand Up @@ -435,4 +437,5 @@ def test_main(args: argparse.Namespace) -> None:
args.dangerously_allow_arbitrary_code_execution_from_rules,
args.json,
args.save_test_output_tar,
experimental=args.experimental,
)