id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
157,203 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
class CrashInfo:
"""Parsed crash information."""
def __init__(self):
self.crash_type = ''
self.crash_address = ''
self.crash_state = ''
self.crash_stacktrace = ''
self.crash_categories = set()
self.frame_count = 0
self.process_name = None
self.process_died = False
# Following fields are for internal use only and subject to change. Do not
# rely on these.
self.frames = []
self.last_frame_id = -1
self.raw_frames = []
# Additional tracking for Java bugs.
self.found_java_exception = False
# Additional tracking for bad casts.
self.found_bad_cast_crash_end_marker = False
# Additional tracking for check failures.
self.check_failure_source_file = ''
# Additional tracking for fatal errors.
self.fatal_error_occurred = False
# Additional tracking for lkl bugs.
self.lkl_kernel_build_id = None
# Additional tracking for fuzzing directory frames,
self.fuzzer_dir_frames = 0
self.is_kasan = False
self.is_lkl = False
self.is_golang = False
self.is_python = False
self.is_js = False
self.found_python_crash = False
self.found_golang_crash = False
self.found_android_kernel_crash = False
self.is_trusty = False
The provided code snippet includes necessary dependencies for implementing the `convert_crashes_to_dicts` function. Write a Python function `def convert_crashes_to_dicts( crashes: List[uworker_msg_pb2.CrashInfo]) -> List[Dict[str, Any]]` to solve the following problem:
Converts crashes to groups (in an array of dicts) for JobRun.
Here is the function:
def convert_crashes_to_dicts(
crashes: List[uworker_msg_pb2.CrashInfo]) -> List[Dict[str, Any]]:
"""Converts crashes to groups (in an array of dicts) for JobRun."""
return [{
'is_new': crash_info.is_new,
'count': crash_info.count,
'crash_type': crash_info.crash_type,
'crash_state': crash_info.crash_state,
'security_flag': crash_info.security_flag,
} for crash_info in crashes] | Converts crashes to groups (in an array of dicts) for JobRun. |
157,204 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
def _track_testcase_run_result(fuzzer, job_type, new_crash_count,
known_crash_count):
"""Track testcase run result."""
monitoring_metrics.FUZZER_KNOWN_CRASH_COUNT.increment_by(
known_crash_count, {
'fuzzer': fuzzer,
})
monitoring_metrics.FUZZER_NEW_CRASH_COUNT.increment_by(
new_crash_count, {
'fuzzer': fuzzer,
})
monitoring_metrics.JOB_KNOWN_CRASH_COUNT.increment_by(known_crash_count, {
'job': job_type,
})
monitoring_metrics.JOB_NEW_CRASH_COUNT.increment_by(new_crash_count, {
'job': job_type,
})
The provided code snippet includes necessary dependencies for implementing the `upload_job_run_stats` function. Write a Python function `def upload_job_run_stats(fuzzer_name: str, job_type: str, revision: int, timestamp: float, new_crash_count: int, known_crash_count: int, testcases_executed: int, groups: List[Dict[str, Any]])` to solve the following problem:
Upload job run stats.
Here is the function:
def upload_job_run_stats(fuzzer_name: str, job_type: str, revision: int,
timestamp: float, new_crash_count: int,
known_crash_count: int, testcases_executed: int,
groups: List[Dict[str, Any]]):
"""Upload job run stats."""
# New format.
job_run = fuzzer_stats.JobRun(fuzzer_name, job_type, revision, timestamp,
testcases_executed, new_crash_count,
known_crash_count, groups)
fuzzer_stats.upload_stats([job_run])
_track_testcase_run_result(fuzzer_name, job_type, new_crash_count,
known_crash_count) | Upload job run stats. |
157,205 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
def truncate_fuzzer_output(output, limit):
"""Truncate output in the middle according to limit."""
if len(output) < limit:
return output
separator = '\n...truncated...\n'
reduced_limit = limit - len(separator)
left = reduced_limit // 2 + reduced_limit % 2
right = reduced_limit // 2
assert reduced_limit > 0
return ''.join([output[:left], separator, output[-right:]])
The provided code snippet includes necessary dependencies for implementing the `store_fuzzer_run_results` function. Write a Python function `def store_fuzzer_run_results(testcase_file_paths, fuzzer, fuzzer_command, fuzzer_output, fuzzer_return_code, generated_testcase_count, expected_testcase_count, generated_testcase_string, fuzz_task_input)` to solve the following problem:
Store fuzzer run results in database.
Here is the function:
def store_fuzzer_run_results(testcase_file_paths, fuzzer, fuzzer_command,
fuzzer_output, fuzzer_return_code,
generated_testcase_count, expected_testcase_count,
generated_testcase_string, fuzz_task_input):
"""Store fuzzer run results in database."""
# Upload fuzzer script output to bucket.
fuzzer_logs.upload_script_log(
fuzzer_output, signed_upload_url=fuzz_task_input.script_log_upload_url)
# Save the test results for the following cases.
# 1. There is no result yet.
# 2. There is no timestamp associated with the result.
# 3. Last update timestamp is more than a day old.
# 4. Return code is non-zero and was not found before.
# 5. Testcases generated were fewer than expected in this run and zero return
# code did occur before and zero generated testcases didn't occur before.
# TODO(mbarbella): Break this up for readability.
# pylint: disable=consider-using-in
save_test_results = (
not fuzzer.result or not fuzzer.result_timestamp or
dates.time_has_expired(fuzzer.result_timestamp, days=1) or
(fuzzer_return_code != 0 and fuzzer_return_code != fuzzer.return_code) or
(generated_testcase_count != expected_testcase_count and
fuzzer.return_code == 0 and ' 0/' not in fuzzer.result))
# pylint: enable=consider-using-in
if not save_test_results:
return None
logs.log('Started storing results from fuzzer run.')
fuzzer_run_results_output = uworker_msg_pb2.StoreFuzzerRunResultsOutput()
if testcase_file_paths:
with open(testcase_file_paths[0], 'rb') as sample_testcase_file_handle:
sample_testcase_file = sample_testcase_file_handle.read()
fuzzer_run_results_output.uploaded_sample_testcase = True
storage.upload_signed_url(sample_testcase_file,
fuzz_task_input.sample_testcase_upload_url)
# Store fuzzer console output.
bot_name = environment.get_value('BOT_NAME')
if fuzzer_return_code is not None:
fuzzer_return_code_string = 'Return code (%d).' % fuzzer_return_code
else:
fuzzer_return_code_string = 'Fuzzer timed out.'
truncated_fuzzer_output = truncate_fuzzer_output(fuzzer_output,
data_types.ENTITY_SIZE_LIMIT)
console_output = (f'{bot_name}: {fuzzer_return_code_string}\n{fuzzer_command}'
f'\n{truncated_fuzzer_output}')
fuzzer_run_results_output.console_output = console_output
fuzzer_run_results_output.generated_testcase_string = (
generated_testcase_string)
fuzzer_run_results_output.fuzzer_return_code = fuzzer_return_code
return fuzzer_run_results_output | Store fuzzer run results in database. |
157,206 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
The provided code snippet includes necessary dependencies for implementing the `postprocess_store_fuzzer_run_results` function. Write a Python function `def postprocess_store_fuzzer_run_results(output)` to solve the following problem:
Postprocess store_fuzzer_run_results.
Here is the function:
def postprocess_store_fuzzer_run_results(output):
"""Postprocess store_fuzzer_run_results."""
if not output.fuzz_task_output.fuzzer_run_results:
return
uworker_input = output.uworker_input
fuzzer = data_types.Fuzzer.query(
data_types.Fuzzer.name == output.uworker_input.fuzzer_name).get()
if not fuzzer:
logs.log_fatal_and_exit('Fuzzer does not exist, exiting.')
fuzzer_run_results = output.fuzz_task_output.fuzzer_run_results
if fuzzer.revision != output.fuzz_task_output.fuzzer_revision:
logs.log('Fuzzer was recently updated, skipping results from old version.')
return
fuzzer.sample_testcase = (
uworker_input.fuzz_task_input.sample_testcase_upload_key)
fuzzer.console_output = fuzzer_run_results.console_output
fuzzer.result = fuzzer_run_results.generated_testcase_string
fuzzer.result_timestamp = datetime.datetime.utcnow()
fuzzer.return_code = fuzzer_run_results.fuzzer_return_code
fuzzer.put()
logs.log('Finished storing results from fuzzer run.') | Postprocess store_fuzzer_run_results. |
157,207 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
class CrashGroup:
"""Represent a group of identical crashes. The key is
(crash_type, crash_state, security_flag)."""
def __init__(self, crashes, context):
for c in crashes:
assert crashes[0].crash_type == c.crash_type
assert crashes[0].crash_state == c.crash_state
assert crashes[0].security_flag == c.security_flag
self.crashes = crashes
if context.fuzz_target:
fully_qualified_fuzzer_name = context.fuzz_target.fully_qualified_name()
else:
fully_qualified_fuzzer_name = context.fuzzer_name
self.main_crash, self.one_time_crasher_flag = find_main_crash(
crashes, fully_qualified_fuzzer_name, context.test_timeout)
self.newly_created_testcase = None
# Getting existing_testcase after finding the main crash is important.
# Because finding the main crash can take a long time; it tests
# reproducibility on every crash.
#
# Getting existing testcase at the last possible moment helps avoid race
# condition among different machines. One machine might finish first and
# prevent other machines from creating identical testcases.
self.existing_testcase = data_handler.find_testcase(
context.project_name,
crashes[0].crash_type,
crashes[0].crash_state,
crashes[0].security_flag,
fuzz_target=fully_qualified_fuzzer_name)
def is_new(self):
"""Return true if there's no existing testcase."""
return not self.existing_testcase
def should_create_testcase(self):
"""Return true if this crash should create a testcase."""
if not self.existing_testcase:
# No existing testcase, should create a new one.
return True
if not self.existing_testcase.one_time_crasher_flag:
# Existing testcase is reproducible, don't need to create another one.
return False
if not self.one_time_crasher_flag:
# Current testcase is reproducible, where existing one is not. Should
# create a new one.
return True
# Both current and existing testcases are unreproducible, shouldn't create
# a new testcase.
# TODO(aarya): We should probably update last tested stacktrace in existing
# testcase without any race conditions.
return False
def has_existing_reproducible_testcase(self):
"""Return true if this crash has a reproducible testcase."""
return (self.existing_testcase and
not self.existing_testcase.one_time_crasher_flag)
def create_testcase(group, context):
"""Create a testcase based on crash."""
crash = group.main_crash
fully_qualified_fuzzer_name = get_fully_qualified_fuzzer_name(context)
# TODO(https://b.corp.google.com/issues/328691756): Set trusted based on the
# job when we start doing untrusted fuzzing.
testcase_id = data_handler.store_testcase(
crash=crash,
fuzzed_keys=crash.fuzzed_key,
minimized_keys=get_fixed_or_minimized_key(group.one_time_crasher_flag),
regression=get_regression(group.one_time_crasher_flag),
fixed=get_fixed_or_minimized_key(group.one_time_crasher_flag),
one_time_crasher_flag=group.one_time_crasher_flag,
crash_revision=context.crash_revision,
comment='Fuzzer %s generated testcase crashed in %d seconds (r%d)' %
(fully_qualified_fuzzer_name, crash.crash_time, context.crash_revision),
absolute_path=crash.absolute_path,
fuzzer_name=context.fuzzer_name,
fully_qualified_fuzzer_name=fully_qualified_fuzzer_name,
job_type=context.job_type,
archived=crash.archived,
archive_filename=crash.archive_filename,
http_flag=crash.http_flag,
gestures=crash.gestures,
redzone=context.redzone,
disable_ubsan=context.disable_ubsan,
window_argument=context.window_argument,
timeout_multiplier=get_testcase_timeout_multiplier(
context.timeout_multiplier, crash, context.test_timeout,
context.thread_wait_timeout),
minimized_arguments=crash.arguments,
trusted=True)
testcase = data_handler.get_testcase_by_id(testcase_id)
if context.fuzzer_metadata:
for key, value in context.fuzzer_metadata.items():
testcase.set_metadata(key, value, update_testcase=False)
testcase.put()
if crash.fuzzing_strategies:
testcase.set_metadata(
'fuzzing_strategies', crash.fuzzing_strategies, update_testcase=True)
# If there is one, record the original file this testcase was mutated from.
if (crash.file_path in context.testcases_metadata and
'original_file_path' in context.testcases_metadata[crash.file_path] and
context.testcases_metadata[crash.file_path]['original_file_path']):
testcase_relative_path = utils.get_normalized_relative_path(
context.testcases_metadata[crash.file_path]['original_file_path'],
context.data_directory)
testcase.set_metadata('original_file_path', testcase_relative_path)
# Track that app args appended by trials are required.
trial_app_args = environment.get_value('TRIAL_APP_ARGS')
if trial_app_args:
testcase.set_metadata('additional_required_app_args', trial_app_args)
# Create tasks to
# 1. Minimize testcase (minimize).
# 2. Find regression range (regression).
# 3. Find testcase impact on production branches (impact).
# 4. Check whether testcase is fixed (progression).
# 5. Get second stacktrace from another job in case of
# one-time crashers (stack).
task_creation.create_tasks(testcase)
return testcase
def filter_crashes(crashes: List[CrashInfo]) -> List[CrashInfo]:
"""Filter crashes based on is_valid()."""
filtered = []
for crash in crashes:
if not crash.is_valid():
logs.log(
(f'Ignore crash (reason={crash.get_error()}, '
f'type={crash.crash_type}, state={crash.crash_state})'),
stacktrace=crash.crash_stacktrace)
continue
filtered.append(crash)
return filtered
def write_crashes_to_big_query(group, context):
"""Write a group of crashes to BigQuery."""
created_at = int(time.time())
# Many of ChromeOS fuzz targets run on Linux bots, so we incorrectly set the
# linux platform for this. We cannot change platform_id in testcase as
# otherwise linux bots can no longer lease those testcase. So, just change
# this value in crash stats. This helps cleanup task put correct OS label.
if environment.is_chromeos_job(context.job_type):
actual_platform = 'chrome'
else:
actual_platform = context.platform_id
# Write to a specific partition.
table_id = ('crashes$%s' % (
datetime.datetime.utcfromtimestamp(created_at).strftime('%Y%m%d')))
client = big_query.Client(dataset_id='main', table_id=table_id)
insert_id_prefix = ':'.join(
[group.crashes[0].key, context.bot_name,
str(created_at)])
rows = []
for index, crash in enumerate(group.crashes):
created_testcase_id = None
if crash == group.main_crash and group.newly_created_testcase:
created_testcase_id = str(group.newly_created_testcase.key.id())
rows.append(
big_query.Insert(
row={
'crash_type': crash.crash_type,
'crash_state': crash.crash_state,
'created_at': created_at,
'platform': actual_platform,
'crash_time_in_ms': int(crash.crash_time * 1000),
'parent_fuzzer_name': get_engine(context),
'fuzzer_name': get_fully_qualified_fuzzer_name(context),
'job_type': context.job_type,
'security_flag': crash.security_flag,
'project': context.project_name,
'reproducible_flag': not group.one_time_crasher_flag,
'revision': str(context.crash_revision),
'new_flag': group.is_new() and crash == group.main_crash,
'testcase_id': created_testcase_id
},
insert_id='%s:%s' % (insert_id_prefix, index)))
row_count = len(rows)
try:
result = client.insert(rows)
if result is None:
# Happens in case the big query function is disabled (local development).
return
errors = result.get('insertErrors', [])
failed_count = len(errors)
monitoring_metrics.BIG_QUERY_WRITE_COUNT.increment_by(
row_count - failed_count, {'success': True})
monitoring_metrics.BIG_QUERY_WRITE_COUNT.increment_by(
failed_count, {'success': False})
for error in errors:
logs.log_error(
('Ignoring error writing the crash (%s) to BigQuery.' %
group.crashes[error['index']].crash_type),
exception=Exception(error))
except Exception:
logs.log_error('Ignoring error writing a group of crashes to BigQuery')
monitoring_metrics.BIG_QUERY_WRITE_COUNT.increment_by(
row_count, {'success': False})
def _update_testcase_variant_if_needed(group, context):
"""Update testcase variant if this is not already covered by existing testcase
variant on this job."""
assert group.existing_testcase
variant = data_handler.get_or_create_testcase_variant(
group.existing_testcase.key.id(), context.job_type)
if not variant or variant.status == data_types.TestcaseVariantStatus.PENDING:
# Either no variant created yet since minimization hasn't finished OR
# variant analysis is not yet finished. Wait in both cases, since we
# prefer existing testcase over current one.
return
if (variant.status == data_types.TestcaseVariantStatus.REPRODUCIBLE and
variant.is_similar):
# Already have a similar reproducible variant, don't need to update.
return
variant.reproducer_key = group.main_crash.fuzzed_key
if group.one_time_crasher_flag:
variant.status = data_types.TestcaseVariantStatus.FLAKY
else:
variant.status = data_types.TestcaseVariantStatus.REPRODUCIBLE
variant.revision = context.crash_revision
variant.crash_type = group.main_crash.crash_type
variant.crash_state = group.main_crash.crash_state
variant.security_flag = group.main_crash.security_flag
variant.is_similar = True
variant.put()
The provided code snippet includes necessary dependencies for implementing the `process_crashes` function. Write a Python function `def process_crashes(crashes, context)` to solve the following problem:
Process a list of crashes.
Here is the function:
def process_crashes(crashes, context):
"""Process a list of crashes."""
processed_groups = []
new_crash_count = 0
known_crash_count = 0
def key_fn(crash):
return crash.key
# Filter invalid crashes.
crashes = filter_crashes(crashes)
group_of_crashes = itertools.groupby(sorted(crashes, key=key_fn), key_fn)
for _, grouped_crashes in group_of_crashes:
group = CrashGroup(list(grouped_crashes), context)
# Archiving testcase to blobstore might fail for all crashes within this
# group.
if not group.main_crash:
logs.log('Unable to store testcase in blobstore: %s' %
group.crashes[0].crash_state)
continue
logs.log(
'Process the crash group (file=%s, '
'fuzzed_key=%s, '
'return code=%s, '
'crash time=%d, '
'crash type=%s, '
'crash state=%s, '
'security flag=%s, '
'crash stacktrace=%s)' %
(group.main_crash.filename, group.main_crash.fuzzed_key,
group.main_crash.return_code, group.main_crash.crash_time,
group.main_crash.crash_type, group.main_crash.crash_state,
group.main_crash.security_flag, group.main_crash.crash_stacktrace))
if group.should_create_testcase():
group.newly_created_testcase = create_testcase(
group=group, context=context)
else:
_update_testcase_variant_if_needed(group, context)
write_crashes_to_big_query(group, context)
if group.is_new():
new_crash_count += 1
known_crash_count += len(group.crashes) - 1
else:
known_crash_count += len(group.crashes)
processed_groups.append(group)
# Artificial delay to throttle appengine updates.
time.sleep(1)
logs.log('Finished processing crashes.')
logs.log(f'New crashes: {new_crash_count}, known crashes: {known_crash_count}'
f', processed groups: {processed_groups}')
return new_crash_count, known_crash_count, processed_groups | Process a list of crashes. |
157,208 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
class FuzzErrorCode:
FUZZER_TIMEOUT = -1
FUZZER_SETUP_FAILED = -2
FUZZER_EXECUTION_FAILED = -3
DATA_BUNDLE_SETUP_FAILED = -4
BUILD_SETUP_FAILED = -5
def _track_fuzzer_run_result(fuzzer_name, generated_testcase_count,
expected_testcase_count, return_code):
"""Track fuzzer run result"""
if expected_testcase_count > 0:
ratio = float(generated_testcase_count) / expected_testcase_count
monitoring_metrics.FUZZER_TESTCASE_COUNT_RATIO.add(ratio,
{'fuzzer': fuzzer_name})
def clamp(val, minimum, maximum):
return max(minimum, min(maximum, val))
# Clamp return code to max, min int 32-bit, otherwise it can get detected as
# type long and we will exception out in infra_libs parsing pipeline.
min_int32 = -(2**31)
max_int32 = 2**31 - 1
return_code = int(clamp(return_code, min_int32, max_int32))
monitoring_metrics.FUZZER_RETURN_CODE_COUNT.increment({
'fuzzer': fuzzer_name,
'return_code': return_code,
})
def handle_fuzz_build_setup_failure(output):
_track_fuzzer_run_result(output.uworker_input.fuzzer_name, 0, 0,
FuzzErrorCode.BUILD_SETUP_FAILED) | null |
157,209 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
class FuzzErrorCode:
FUZZER_TIMEOUT = -1
FUZZER_SETUP_FAILED = -2
FUZZER_EXECUTION_FAILED = -3
DATA_BUNDLE_SETUP_FAILED = -4
BUILD_SETUP_FAILED = -5
def _track_fuzzer_run_result(fuzzer_name, generated_testcase_count,
expected_testcase_count, return_code):
"""Track fuzzer run result"""
if expected_testcase_count > 0:
ratio = float(generated_testcase_count) / expected_testcase_count
monitoring_metrics.FUZZER_TESTCASE_COUNT_RATIO.add(ratio,
{'fuzzer': fuzzer_name})
def clamp(val, minimum, maximum):
return max(minimum, min(maximum, val))
# Clamp return code to max, min int 32-bit, otherwise it can get detected as
# type long and we will exception out in infra_libs parsing pipeline.
min_int32 = -(2**31)
max_int32 = 2**31 - 1
return_code = int(clamp(return_code, min_int32, max_int32))
monitoring_metrics.FUZZER_RETURN_CODE_COUNT.increment({
'fuzzer': fuzzer_name,
'return_code': return_code,
})
def handle_fuzz_data_bundle_setup_failure(output):
_track_fuzzer_run_result(output.uworker_input.fuzzer_name, 0, 0,
FuzzErrorCode.DATA_BUNDLE_SETUP_FAILED) | null |
157,210 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
class FuzzErrorCode:
FUZZER_TIMEOUT = -1
FUZZER_SETUP_FAILED = -2
FUZZER_EXECUTION_FAILED = -3
DATA_BUNDLE_SETUP_FAILED = -4
BUILD_SETUP_FAILED = -5
def _track_fuzzer_run_result(fuzzer_name, generated_testcase_count,
expected_testcase_count, return_code):
"""Track fuzzer run result"""
if expected_testcase_count > 0:
ratio = float(generated_testcase_count) / expected_testcase_count
monitoring_metrics.FUZZER_TESTCASE_COUNT_RATIO.add(ratio,
{'fuzzer': fuzzer_name})
def clamp(val, minimum, maximum):
return max(minimum, min(maximum, val))
# Clamp return code to max, min int 32-bit, otherwise it can get detected as
# type long and we will exception out in infra_libs parsing pipeline.
min_int32 = -(2**31)
max_int32 = 2**31 - 1
return_code = int(clamp(return_code, min_int32, max_int32))
monitoring_metrics.FUZZER_RETURN_CODE_COUNT.increment({
'fuzzer': fuzzer_name,
'return_code': return_code,
})
def handle_fuzz_no_fuzzer(output):
_track_fuzzer_run_result(output.uworker_input.fuzzer_name, 0, 0,
FuzzErrorCode.FUZZER_SETUP_FAILED) | null |
157,211 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
def _make_session(uworker_input):
test_timeout = environment.get_value('TEST_TIMEOUT')
return FuzzingSession(
uworker_input,
test_timeout,
)
The provided code snippet includes necessary dependencies for implementing the `utask_main` function. Write a Python function `def utask_main(uworker_input)` to solve the following problem:
Runs the given fuzzer for one round.
Here is the function:
def utask_main(uworker_input):
"""Runs the given fuzzer for one round."""
session = _make_session(uworker_input)
return session.run() | Runs the given fuzzer for one round. |
157,212 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
def utask_preprocess(fuzzer_name, job_type, uworker_env):
def save_fuzz_targets(output):
def handle_fuzz_no_fuzz_target_selected(output):
save_fuzz_targets(output)
# Try again now that there are some fuzz targets.
utask_preprocess(output.uworker_input.fuzzer_name,
output.uworker_input.job_type,
output.uworker_input.uworker_env) | null |
157,213 | import collections
import datetime
import itertools
import json
import os
import random
import re
import time
from typing import Any
from typing import Dict
from typing import List
from google.cloud import ndb
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats as libfuzzer_stats
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks import trials
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import fuzzer_selection
from clusterfuzz._internal.fuzzing import gesture_handler
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import monitoring_metrics
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
from clusterfuzz.stacktraces.__init__ import CrashInfo
def _make_session(uworker_input):
test_timeout = environment.get_value('TEST_TIMEOUT')
return FuzzingSession(
uworker_input,
test_timeout,
)
_ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({
uworker_msg_pb2.ErrorType.FUZZ_BUILD_SETUP_FAILURE:
handle_fuzz_build_setup_failure,
uworker_msg_pb2.ErrorType.FUZZ_DATA_BUNDLE_SETUP_FAILURE:
handle_fuzz_data_bundle_setup_failure,
uworker_msg_pb2.ErrorType.FUZZ_NO_FUZZER:
handle_fuzz_no_fuzzer,
uworker_msg_pb2.ErrorType.FUZZ_NO_FUZZ_TARGET_SELECTED:
handle_fuzz_no_fuzz_target_selected,
}).compose_with(uworker_handle_errors.UNHANDLED_ERROR_HANDLER)
def save_fuzz_targets(output):
"""Saves fuzz targets that were seen in the build to the database."""
if not output.fuzz_task_output.fuzz_targets:
return
logs.log(f'Saving fuzz targets: {output.fuzz_task_output.fuzz_targets}.')
data_handler.record_fuzz_targets(output.uworker_input.fuzzer_name,
output.fuzz_task_output.fuzz_targets,
output.uworker_input.job_type)
def utask_postprocess(output):
if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR:
_ERROR_HANDLER.handle(output)
return
save_fuzz_targets(output)
session = _make_session(output.uworker_input)
session.postprocess(output) | null |
157,214 | from typing import Callable
from typing import Dict
from clusterfuzz._internal.protos import uworker_msg_pb2
def noop_handler(*args, **kwargs):
del args
del kwargs | null |
157,215 | from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def _get_variant_testcase_for_job(testcase, job_type):
"""Return a testcase entity for variant task use. This changes the fuzz target
params for a particular fuzzing engine."""
if testcase.job_type == job_type:
# Update stack operation on same testcase.
return testcase
if not environment.is_engine_fuzzer_job(testcase.job_type):
# For blackbox fuzzer testcases, there is no change of fuzzer required.
return testcase
engine_name = environment.get_engine_for_job(job_type)
project = data_handler.get_project_name(job_type)
binary_name = testcase.get_metadata('fuzzer_binary_name')
fully_qualified_fuzzer_name = data_types.fuzz_target_fully_qualified_name(
engine_name, project, binary_name)
variant_testcase = data_types.clone_entity(testcase)
variant_testcase.key = testcase.key
variant_testcase.fuzzer_name = engine_name
variant_testcase.overridden_fuzzer_name = fully_qualified_fuzzer_name
variant_testcase.job_type = job_type
# Remove put() method to avoid updates. DO NOT REMOVE THIS.
variant_testcase.put = lambda: None
return variant_testcase
The provided code snippet includes necessary dependencies for implementing the `utask_preprocess` function. Write a Python function `def utask_preprocess(testcase_id, job_type, uworker_env)` to solve the following problem:
Run a test case with a different job type to see if they reproduce.
Here is the function:
def utask_preprocess(testcase_id, job_type, uworker_env):
"""Run a test case with a different job type to see if they reproduce."""
testcase = data_handler.get_testcase_by_id(testcase_id)
uworker_io.check_handling_testcase_safe(testcase)
if (environment.is_engine_fuzzer_job(testcase.job_type) !=
environment.is_engine_fuzzer_job(job_type)):
# We should never reach here. But in case we do, we should bail out as
# otherwise we will run into exceptions.
return None
# Use a cloned testcase entity with different fuzz target paramaters for
# a different fuzzing engine.
original_job_type = testcase.job_type
testcase = _get_variant_testcase_for_job(testcase, job_type)
setup_input = setup.preprocess_setup_testcase(
testcase, uworker_env, with_deps=False)
variant_input = uworker_msg_pb2.VariantTaskInput(
original_job_type=original_job_type)
uworker_input = uworker_msg_pb2.Input(
job_type=job_type,
testcase=uworker_io.entity_to_protobuf(testcase),
uworker_env=uworker_env,
testcase_id=testcase_id,
variant_task_input=variant_input,
setup_input=setup_input,
)
testcase_manager.preprocess_testcase_manager(testcase, uworker_input)
return uworker_input | Run a test case with a different job type to see if they reproduce. |
157,216 | from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
class CrashComparer:
"""Compares two crash results."""
COMPARE_THRESHOLD = 0.8
SAME_FRAMES_THRESHOLD = 2
def __init__(self, crash_state_1, crash_state_2, compare_threshold=None):
self.crash_state_1 = crash_state_1
self.crash_state_2 = crash_state_2
self.compare_threshold = compare_threshold or self.COMPARE_THRESHOLD
def is_similar(self):
"""Return a bool for whether the two crash results are similar."""
# If one of the crash state is empty, it can't match anything.
if not self.crash_state_1 or not self.crash_state_2:
return False
# Optimization: Do a == check first before others.
if self.crash_state_1 == self.crash_state_2:
return True
# If there is a fuzzer hash string in state, then rely on exact comparison.
# Since we failed the check above, our hashes don't match.
if 'FuzzerHash=' in self.crash_state_1:
return False
# TODO(aarya): Improve this algorithm and leverage other parts of
# stacktrace.
crash_state_lines_1 = self.crash_state_1.splitlines()
crash_state_lines_2 = self.crash_state_2.splitlines()
if (longest_common_subsequence(crash_state_lines_1, crash_state_lines_2) >=
self.SAME_FRAMES_THRESHOLD):
return True
lines_compared = 0
similarity_ratio_sum = 0.0
for i in range(len(crash_state_lines_1)):
if i >= len(crash_state_lines_2):
break
similarity_ratio = _similarity_ratio(crash_state_lines_1[i],
crash_state_lines_2[i])
lines_compared += 1
similarity_ratio_sum += similarity_ratio
similarity_ratio_average = similarity_ratio_sum / lines_compared
return similarity_ratio_average > self.compare_threshold
The provided code snippet includes necessary dependencies for implementing the `utask_main` function. Write a Python function `def utask_main(uworker_input)` to solve the following problem:
The main part of the variant task. Downloads the testcase and build checks if the build can reproduce the error.
Here is the function:
def utask_main(uworker_input):
"""The main part of the variant task. Downloads the testcase and build checks
if the build can reproduce the error."""
testcase = uworker_io.entity_from_protobuf(uworker_input.testcase,
data_types.Testcase)
if environment.is_engine_fuzzer_job(testcase.job_type):
# Remove put() method to avoid updates. DO NOT REMOVE THIS.
# Repeat this because the in-memory executor may allow puts.
# TODO(metzman): Remove this when we use batch.
testcase.put = lambda: None
# Setup testcase and its dependencies.
_, testcase_file_path, error = setup.setup_testcase(
testcase, uworker_input.job_type, uworker_input.setup_input)
if error:
return error
# Set up a custom or regular build. We explicitly omit the crash revision
# since we want to test against the latest build here.
try:
build_manager.setup_build()
except errors.BuildNotFoundError:
logs.log_warn('Matching build not found.')
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.UNHANDLED)
# Check if we have an application path. If not, our build failed to setup
# correctly.
if not build_manager.check_app_path():
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.VARIANT_BUILD_SETUP)
# Disable gestures if we're running on a different platform from that of
# the original test case.
use_gestures = testcase.platform == environment.platform().lower()
# Reproduce the crash.
app_path = environment.get_value('APP_PATH')
command = testcase_manager.get_command_line_for_application(
testcase_file_path, app_path=app_path, needs_http=testcase.http_flag)
test_timeout = environment.get_value('TEST_TIMEOUT', 10)
revision = environment.get_value('APP_REVISION')
fuzz_target = testcase_manager.get_fuzz_target_from_input(uworker_input)
try:
result = testcase_manager.test_for_crash_with_retries(
fuzz_target,
testcase,
testcase_file_path,
test_timeout,
http_flag=testcase.http_flag,
use_gestures=use_gestures,
compare_crash=False)
except testcase_manager.TargetNotFoundError:
logs.log_warn('Could not find target in build, probably does not exist.')
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.UNHANDLED)
if result.is_crash() and not result.should_ignore():
crash_state = result.get_state()
crash_type = result.get_type()
security_flag = result.is_security_issue()
gestures = testcase.gestures if use_gestures else None
fuzz_target = testcase_manager.get_fuzz_target_from_input(uworker_input)
one_time_crasher_flag = not testcase_manager.test_for_reproducibility(
fuzz_target, testcase_file_path, crash_type, crash_state, security_flag,
test_timeout, testcase.http_flag, gestures)
if one_time_crasher_flag:
status = data_types.TestcaseVariantStatus.FLAKY
else:
status = data_types.TestcaseVariantStatus.REPRODUCIBLE
crash_comparer = CrashComparer(crash_state, testcase.crash_state)
is_similar = (
crash_comparer.is_similar() and security_flag == testcase.security_flag)
unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False)
symbolized_crash_stacktrace = result.get_stacktrace(symbolized=True)
crash_stacktrace_output = utils.get_crash_stacktrace_output(
command, symbolized_crash_stacktrace, unsymbolized_crash_stacktrace)
else:
status = data_types.TestcaseVariantStatus.UNREPRODUCIBLE
is_similar = False
crash_type = None
crash_state = None
security_flag = False
crash_stacktrace_output = 'No crash occurred.'
# Regular case of variant analysis.
variant_task_output = uworker_msg_pb2.VariantTaskOutput()
variant_task_output.status = status
variant_task_output.revision = int(revision)
if crash_type is not None:
variant_task_output.crash_type = crash_type
if crash_state is not None:
variant_task_output.crash_state = crash_state
variant_task_output.security_flag = bool(security_flag)
variant_task_output.is_similar = bool(is_similar)
variant_task_output.platform = environment.platform().lower()
return uworker_msg_pb2.Output(
variant_task_output=variant_task_output,
crash_stacktrace_output=crash_stacktrace_output) | The main part of the variant task. Downloads the testcase and build checks if the build can reproduce the error. |
157,217 | from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def handle_build_setup_error(output):
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
data_handler.update_testcase_comment(
testcase, data_types.TaskState.ERROR,
f'Build setup failed with job: {output.uworker_input.testcase_id}') | null |
157,218 | from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
_ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({
uworker_msg_pb2.ErrorType.VARIANT_BUILD_SETUP: handle_build_setup_error,
}).compose_with(
uworker_handle_errors.UNHANDLED_ERROR_HANDLER,
setup.ERROR_HANDLER,
)
The provided code snippet includes necessary dependencies for implementing the `utask_postprocess` function. Write a Python function `def utask_postprocess(output)` to solve the following problem:
Handle the output from utask_main.
Here is the function:
def utask_postprocess(output):
"""Handle the output from utask_main."""
if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR:
_ERROR_HANDLER.handle(output)
return
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
if environment.is_engine_fuzzer_job(output.uworker_input.job_type):
# Remove put() method to avoid updates. DO NOT REMOVE THIS.
testcase.put = lambda: None
if (output.uworker_input.variant_task_input.original_job_type ==
output.uworker_input.job_type):
# This case happens when someone clicks 'Update last tested stacktrace using
# trunk build' button.
testcase.last_tested_crash_stacktrace = (
data_handler.filter_stacktrace(output.crash_stacktrace_output))
testcase.set_metadata(
'last_tested_crash_revision',
output.variant_task_output.revision,
update_testcase=True)
else:
# Explicitly skipping crash stacktrace for now as it make entities larger
# and we plan to use only crash paramaters in UI.
variant = data_handler.get_or_create_testcase_variant(
output.uworker_input.testcase_id, output.uworker_input.job_type)
variant_task_output = output.variant_task_output
variant.status = variant_task_output.status
variant.revision = variant_task_output.revision
if variant_task_output.HasField('crash_type'):
variant.crash_type = variant_task_output.crash_type
else:
variant.crash_type = None
if variant_task_output.HasField('crash_state'):
variant.crash_state = variant_task_output.crash_state
else:
variant.crash_state = None
variant.security_flag = variant_task_output.security_flag
variant.is_similar = variant_task_output.is_similar
variant.platform = variant_task_output.platform
variant.put() | Handle the output from utask_main. |
157,219 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def _save_current_fixed_range_indices(testcase, uworker_output):
"""Save current fixed range indices in case we die in middle of task."""
task_output = uworker_output.progression_task_output
last_progression_min = None
last_progression_max = None
if task_output.HasField('last_progression_min'):
last_progression_min = task_output.last_progression_min
if task_output.HasField('last_progression_max'):
last_progression_max = task_output.last_progression_max
testcase.set_metadata(
'last_progression_min', last_progression_min, update_testcase=False)
testcase.set_metadata(
'last_progression_max', last_progression_max, update_testcase=False)
The provided code snippet includes necessary dependencies for implementing the `handle_progression_timeout` function. Write a Python function `def handle_progression_timeout(uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Job has exceeded the deadline. Recreate the task to pick up where we left off.
Here is the function:
def handle_progression_timeout(uworker_output: uworker_msg_pb2.Output):
"""Job has exceeded the deadline. Recreate the task to pick up where we left
off."""
testcase_id = uworker_output.uworker_input.testcase_id
job_type = uworker_output.uworker_input.job_type
testcase = data_handler.get_testcase_by_id(testcase_id)
_save_current_fixed_range_indices(testcase, uworker_output)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
uworker_output.error_message)
tasks.add_task('progression', testcase_id, job_type) | Job has exceeded the deadline. Recreate the task to pick up where we left off. |
157,220 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `handle_progression_build_not_found` function. Write a Python function `def handle_progression_build_not_found(uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Handles an expected build that no longer exists, we can't continue. Also, clears progression_pending testcase metadata
Here is the function:
def handle_progression_build_not_found(uworker_output: uworker_msg_pb2.Output):
"""Handles an expected build that no longer exists, we can't continue. Also,
clears progression_pending testcase metadata"""
testcase_id = uworker_output.uworker_input.testcase_id
testcase = data_handler.get_testcase_by_id(testcase_id)
testcase.fixed = 'NA'
testcase.open = False
data_handler.clear_progression_pending(testcase)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
uworker_output.error_message) | Handles an expected build that no longer exists, we can't continue. Also, clears progression_pending testcase metadata |
157,221 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `handle_progression_revision_list_error` function. Write a Python function `def handle_progression_revision_list_error( uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Handles revision list errors, in which case the testcase is closed with error.
Here is the function:
def handle_progression_revision_list_error(
uworker_output: uworker_msg_pb2.Output):
"""Handles revision list errors, in which case the testcase is closed with
error."""
testcase_id = uworker_output.uworker_input.testcase_id
testcase = data_handler.get_testcase_by_id(testcase_id)
data_handler.close_testcase_with_error(testcase,
'Failed to fetch revision list') | Handles revision list errors, in which case the testcase is closed with error. |
157,222 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def _save_current_fixed_range_indices(testcase, uworker_output):
"""Save current fixed range indices in case we die in middle of task."""
task_output = uworker_output.progression_task_output
last_progression_min = None
last_progression_max = None
if task_output.HasField('last_progression_min'):
last_progression_min = task_output.last_progression_min
if task_output.HasField('last_progression_max'):
last_progression_max = task_output.last_progression_max
testcase.set_metadata(
'last_progression_min', last_progression_min, update_testcase=False)
testcase.set_metadata(
'last_progression_max', last_progression_max, update_testcase=False)
The provided code snippet includes necessary dependencies for implementing the `handle_progression_bad_state_min_max` function. Write a Python function `def handle_progression_bad_state_min_max( uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Handles when we end up in a state having min and max versions the same during a progression.
Here is the function:
def handle_progression_bad_state_min_max(
uworker_output: uworker_msg_pb2.Output):
"""Handles when we end up in a state having min and max versions the same
during a progression."""
testcase = data_handler.get_testcase_by_id(
uworker_output.uworker_input.testcase_id)
_save_current_fixed_range_indices(testcase, uworker_output)
testcase.fixed = 'NA'
testcase.open = False
message = ('Fixed testing errored out (min and max revisions are both '
f'{uworker_output.progression_task_output.min_revision}')
data_handler.update_progression_completion_metadata(
testcase,
uworker_output.progression_task_output.max_revision,
message=message)
# Let the bisection service know about the NA status.
bisection.request_bisection(testcase) | Handles when we end up in a state having min and max versions the same during a progression. |
157,223 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `handle_progression_no_crash` function. Write a Python function `def handle_progression_no_crash(uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Expected crash version doesn't crash. Retries once to confirm the result otherwise marks unreproducible if the testcase is flaky.
Here is the function:
def handle_progression_no_crash(uworker_output: uworker_msg_pb2.Output):
"""Expected crash version doesn't crash. Retries once to confirm the result
otherwise marks unreproducible if the testcase is flaky."""
testcase_id = uworker_output.uworker_input.testcase_id
job_type = uworker_output.uworker_input.job_type
testcase = data_handler.get_testcase_by_id(testcase_id)
# Retry once on another bot to confirm our result.
if data_handler.is_first_attempt_for_task(
'progression', testcase, reset_after_retry=True):
tasks.add_task('progression', testcase_id, job_type)
error_message = (
uworker_output.error_message +
', will retry on another bot to confirm result.')
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
error_message)
data_handler.update_progression_completion_metadata(
testcase, uworker_output.progression_task_output.crash_revision)
return
data_handler.clear_progression_pending(testcase)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
uworker_output.error_message)
task_creation.mark_unreproducible_if_flaky(testcase, 'progression', True)
return | Expected crash version doesn't crash. Retries once to confirm the result otherwise marks unreproducible if the testcase is flaky. |
157,224 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `handle_progression_build_setup_error` function. Write a Python function `def handle_progression_build_setup_error( uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Handles errors for scenarios where build setup fails.
Here is the function:
def handle_progression_build_setup_error(
uworker_output: uworker_msg_pb2.Output):
"""Handles errors for scenarios where build setup fails."""
# If we failed to setup a build, it is likely a bot error. We can retry
# the task in this case.
testcase_id = uworker_output.uworker_input.testcase_id
job_type = uworker_output.uworker_input.job_type
testcase = data_handler.get_testcase_by_id(testcase_id)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
uworker_output.error_message)
build_fail_wait = environment.get_value('FAIL_WAIT')
tasks.add_task(
'progression', testcase_id, job_type, wait_time=build_fail_wait) | Handles errors for scenarios where build setup fails. |
157,225 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `handle_progression_bad_build` function. Write a Python function `def handle_progression_bad_build(uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Handles unrecoverable bad build errors.
Here is the function:
def handle_progression_bad_build(uworker_output: uworker_msg_pb2.Output):
"""Handles unrecoverable bad build errors."""
# Though bad builds when narrowing the range are recoverable, certain builds
# being marked as bad may be unrecoverable. Recoverable ones should not
# reach this point.
testcase_id = uworker_output.uworker_input.testcase_id
testcase = data_handler.get_testcase_by_id(testcase_id)
error_message = 'Unable to recover from bad build'
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
error_message) | Handles unrecoverable bad build errors. |
157,226 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def _set_regression_testcase_upload_url(
progression_input: uworker_msg_pb2.ProgressionTaskInput,
testcase: data_types.Testcase):
"""Determines and sets the signed regression_testcase_url (if any) in
the progression task input.
Raises RuntimeError in case of UUID collision on the generated filename.
"""
fuzz_target = data_handler.get_fuzz_target(testcase.overridden_fuzzer_name)
if not fuzz_target:
# No work to do, only applicable for engine fuzzers.
return
if not testcase.trusted:
logs.log_warn('Not saving untrusted testcase to regression corpus.')
return
# We probably don't need these checks, but do them anyway since it is
# important not to mess this up.
if testcase.uploader_email:
logs.log_error(
'Not saving uploaded testcase to regression corpus (uploaded not set).')
return
upload_metadata = data_types.TestcaseUploadMetadata.query(
data_types.TestcaseUploadMetadata.testcase_id == testcase.key.id()).get()
if upload_metadata:
logs.log_error('Not saving uploaded testcase to regression corpus '
'(uploaded and email not set).')
return
progression_input.regression_testcase_url = (
corpus_manager.get_regressions_signed_upload_url(
fuzz_target.engine, fuzz_target.project_qualified_name()))
The provided code snippet includes necessary dependencies for implementing the `utask_preprocess` function. Write a Python function `def utask_preprocess(testcase_id, job_type, uworker_env)` to solve the following problem:
Runs preprocessing for progression task.
Here is the function:
def utask_preprocess(testcase_id, job_type, uworker_env):
"""Runs preprocessing for progression task."""
testcase = data_handler.get_testcase_by_id(testcase_id)
if not testcase:
return None
if testcase.fixed:
logs.log_error(f'Fixed range is already set as {testcase.fixed}, skip.')
return None
# Set a flag to indicate we are running progression task. This shows pending
# status on testcase report page and avoid conflicting testcase updates by
# triage cron.
testcase.set_metadata('progression_pending', True)
data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED)
blob_name, blob_upload_url = blobs.get_blob_signed_upload_url()
progression_input = uworker_msg_pb2.ProgressionTaskInput(
custom_binary=build_manager.is_custom_binary(),
bad_revisions=build_manager.get_job_bad_revisions(),
blob_name=blob_name,
stacktrace_upload_url=blob_upload_url)
# Setup testcase and its dependencies.
setup_input = setup.preprocess_setup_testcase(testcase, uworker_env)
_set_regression_testcase_upload_url(progression_input, testcase)
uworker_input = uworker_msg_pb2.Input(
job_type=job_type,
testcase_id=str(testcase_id),
uworker_env=uworker_env,
progression_task_input=progression_input,
testcase=uworker_io.entity_to_protobuf(testcase),
setup_input=setup_input)
testcase_manager.preprocess_testcase_manager(testcase, uworker_input)
return uworker_input | Runs preprocessing for progression task. |
157,227 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def find_fixed_range(uworker_input):
"""Attempt to find the revision range where a testcase was fixed."""
deadline = tasks.get_task_completion_deadline()
testcase = uworker_io.entity_from_protobuf(uworker_input.testcase,
data_types.Testcase)
job_type = uworker_input.job_type
setup_input = uworker_input.setup_input
fuzz_target = testcase_manager.get_fuzz_target_from_input(uworker_input)
_, testcase_file_path, error = setup.setup_testcase(testcase, job_type,
setup_input)
if error:
return error
# Custom binaries are handled as special cases.
if build_manager.is_custom_binary():
return _check_fixed_for_custom_binary(testcase, testcase_file_path,
uworker_input)
build_bucket_path = build_manager.get_primary_bucket_path()
bad_revisions = uworker_input.progression_task_input.bad_revisions
revision_list = build_manager.get_revisions_list(
build_bucket_path, bad_revisions, testcase=testcase)
if not revision_list:
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.PROGRESSION_REVISION_LIST_ERROR)
# Use min, max_index to mark the start and end of revision list that is used
# for bisecting the progression range. Set start to the revision where noticed
# the crash. Set end to the trunk revision. Also, use min, max from past run
# if it timed out.
min_revision = testcase.get_metadata('last_progression_min')
max_revision = testcase.get_metadata('last_progression_max')
progression_task_output = uworker_msg_pb2.ProgressionTaskOutput(
clear_min_max_metadata=False, build_data_list=[])
if min_revision or max_revision:
# Clear these to avoid using them in next run. If this run fails, then we
# should try next run without them to see it succeeds. If this run succeeds,
# we should still clear them to avoid capping max revision in next run.
progression_task_output.clear_min_max_metadata = True
last_tested_revision = testcase.get_metadata('last_tested_crash_revision')
known_crash_revision = last_tested_revision or testcase.crash_revision
if not min_revision:
min_revision = known_crash_revision
if not max_revision:
max_revision = revisions.get_last_revision_in_list(revision_list)
min_index = revisions.find_min_revision_index(revision_list, min_revision)
if min_index is None:
error_message = f'Build {min_revision} no longer exists.'
return uworker_msg_pb2.Output(
error_message=error_message,
progression_task_output=progression_task_output,
error_type=uworker_msg_pb2.ErrorType.PROGRESSION_BUILD_NOT_FOUND)
max_index = revisions.find_max_revision_index(revision_list, max_revision)
if max_index is None:
error_message = f'Build {max_revision} no longer exists.'
return uworker_msg_pb2.Output(
error_message=error_message,
progression_task_output=progression_task_output,
error_type=uworker_msg_pb2.ErrorType.PROGRESSION_BUILD_NOT_FOUND)
# Check to see if this testcase is still crashing now. If it is, then just
# bail out.
result, error = _testcase_reproduces_in_revision(
testcase, testcase_file_path, job_type, max_revision, fuzz_target,
progression_task_output)
issue_metadata = engine_common.get_fuzz_target_issue_metadata(fuzz_target)
issue_metadata = issue_metadata or {}
if error is not None:
return error
if result.is_crash():
logs.log(f'Found crash with same signature on latest'
f' revision r{max_revision}.')
app_path = environment.get_value('APP_PATH')
command = testcase_manager.get_command_line_for_application(
testcase_file_path, app_path=app_path, needs_http=testcase.http_flag)
symbolized_crash_stacktrace = result.get_stacktrace(symbolized=True)
unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False)
stacktrace = utils.get_crash_stacktrace_output(
command, symbolized_crash_stacktrace, unsymbolized_crash_stacktrace)
last_tested_crash_stacktrace = data_handler.filter_stacktrace(
stacktrace, uworker_input.progression_task_input.blob_name,
uworker_input.progression_task_input.stacktrace_upload_url)
crash_on_latest_message = ('Still crashes on latest'
f' revision r{max_revision}.')
progression_task_output.crash_on_latest = True
progression_task_output.crash_on_latest_message = crash_on_latest_message
progression_task_output.crash_revision = int(max_revision)
progression_task_output.last_tested_crash_stacktrace = (
last_tested_crash_stacktrace)
return uworker_msg_pb2.Output(
progression_task_output=progression_task_output,
issue_metadata=issue_metadata)
# Verify that we do crash in the min revision. This is assumed to be true
# while we are doing the bisect.
result, error = _testcase_reproduces_in_revision(
testcase, testcase_file_path, job_type, min_revision, fuzz_target,
progression_task_output)
if error is not None:
return error
if result and not result.is_crash():
error_message = f'Minimum revision r{min_revision} did not crash.'
progression_task_output.crash_revision = int(min_revision)
return uworker_msg_pb2.Output(
progression_task_output=progression_task_output,
issue_metadata=issue_metadata,
error_message=error_message,
error_type=uworker_msg_pb2.ErrorType.PROGRESSION_NO_CRASH)
last_progression_min = None
last_progression_max = None
# Start a binary search to find last non-crashing revision. At this point, we
# know that we do crash in the min_revision, and do not crash in max_revision.
while time.time() < deadline:
min_revision = revision_list[min_index]
max_revision = revision_list[max_index]
# If the min and max revisions are one apart this is as much as we can
# narrow the range.
if max_index - min_index == 1:
testcase.open = False
_store_testcase_for_regression_testing(
testcase, testcase_file_path, uworker_input.progression_task_input)
progression_task_output.min_revision = int(min_revision)
progression_task_output.max_revision = int(max_revision)
return uworker_msg_pb2.Output(
progression_task_output=progression_task_output,
issue_metadata=issue_metadata)
# Occasionally, we get into this bad state. It seems to be related to test
# cases with flaky stacks, but the exact cause is unknown.
if max_index - min_index < 1:
progression_task_output.min_revision = int(min_revision)
progression_task_output.max_revision = int(max_revision)
# We could be in a bad state from the beginning of this loop. In that
# case, both last_progression_min and last_progression_max would be None.
if last_progression_min:
progression_task_output.last_progression_min = int(last_progression_min)
if last_progression_max:
progression_task_output.last_progression_max = int(last_progression_max)
return uworker_msg_pb2.Output(
progression_task_output=progression_task_output,
issue_metadata=issue_metadata,
error_type=uworker_msg_pb2.ErrorType.PROGRESSION_BAD_STATE_MIN_MAX)
# Test the middle revision of our range.
middle_index = (min_index + max_index) // 2
middle_revision = revision_list[middle_index]
result, error = _testcase_reproduces_in_revision(
testcase, testcase_file_path, job_type, middle_revision, fuzz_target,
progression_task_output)
if error is not None:
if error.error_type == uworker_msg_pb2.ErrorType.PROGRESSION_BAD_BUILD:
# Skip this revision.
del revision_list[middle_index]
max_index -= 1
continue
# Only bad build errors are recoverable.
progression_task_output.last_progression_min = int(last_progression_min)
progression_task_output.last_progression_max = int(last_progression_max)
error.progression_task_output.CopyFrom(progression_task_output)
return error
if result.is_crash():
min_index = middle_index
else:
max_index = middle_index
last_progression_min = int(revision_list[min_index])
last_progression_max = int(revision_list[max_index])
# If we've broken out of the loop, we've exceeded the deadline. Recreate the
# task to pick up where we left off.
error_message = (f'Timed out, current range '
f'r{revision_list[min_index]}:r{revision_list[max_index]}')
if last_progression_min is not None:
progression_task_output.last_progression_min = last_progression_min
if last_progression_max is not None:
progression_task_output.last_progression_max = last_progression_max
return uworker_msg_pb2.Output(
error_message=error_message,
issue_metadata=issue_metadata,
progression_task_output=progression_task_output,
error_type=uworker_msg_pb2.ErrorType.PROGRESSION_TIMEOUT)
The provided code snippet includes necessary dependencies for implementing the `utask_main` function. Write a Python function `def utask_main(uworker_input)` to solve the following problem:
Executes the untrusted part of progression_task.
Here is the function:
def utask_main(uworker_input):
"""Executes the untrusted part of progression_task."""
testcase = uworker_io.entity_from_protobuf(uworker_input.testcase,
data_types.Testcase)
uworker_io.check_handling_testcase_safe(testcase)
return find_fixed_range(uworker_input) | Executes the untrusted part of progression_task. |
157,228 | import time
from typing import List
from clusterfuzz._internal.base import bisection
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
def _maybe_clear_progression_last_min_max_metadata(
testcase: data_types.Testcase, uworker_output: uworker_msg_pb2.Output):
"""Clears last_progression_min and last_progression_max when
clear_min_max_metadata is set to True"""
if not uworker_output.HasField('progression_task_output'):
return
task_output = uworker_output.progression_task_output
if task_output.clear_min_max_metadata:
testcase.delete_metadata('last_progression_min', update_testcase=False)
testcase.delete_metadata('last_progression_max', update_testcase=False)
testcase.put()
def _update_build_metadata(job_type: str,
build_data_list: List[uworker_msg_pb2.BuildData]):
"""A helper method to update the build metadata corresponding to a
job_type."""
for build_data in build_data_list:
testcase_manager.update_build_metadata(job_type, build_data)
def _cleanup_stacktrace_blob_from_storage(output: uworker_msg_pb2.Output):
"""Cleanup the blob created in preprocess if it wasn't used to store the
filterd stacktrace."""
if output.HasField('progression_task_output'):
stacktrace = output.progression_task_output.last_tested_crash_stacktrace
if stacktrace.startswith(data_types.BLOBSTORE_STACK_PREFIX):
return
if not output.uworker_input.progression_task_input.blob_name:
raise ValueError('blob_name should not be empty here.')
blob_name = output.uworker_input.progression_task_input.blob_name
blobs.delete_blob(blob_name)
def crash_on_latest(uworker_output: uworker_msg_pb2.Output):
"""Handles crash on latest revision, or custom binary crashes. Saves the crash
info for non-custom binaries."""
testcase_id = uworker_output.uworker_input.testcase_id
progression_task_output = uworker_output.progression_task_output
testcase = data_handler.get_testcase_by_id(testcase_id)
testcase.last_tested_crash_stacktrace = (
progression_task_output.last_tested_crash_stacktrace)
data_handler.update_progression_completion_metadata(
testcase,
progression_task_output.crash_revision,
is_crash=True,
message=progression_task_output.crash_on_latest_message)
# This means we are in a custom binary crash, we do not upload crash info.
if uworker_output.uworker_input.progression_task_input.custom_binary:
return
# Since we've verified that the test case is still crashing, clear out any
# metadata indicating potential flake from previous runs.
task_creation.mark_unreproducible_if_flaky(testcase, 'progression', False)
def _update_issue_metadata(testcase, metadata):
if not metadata:
return
for key, value in metadata.items():
old_value = testcase.get_metadata(key)
if old_value != value:
logs.log('Updating issue metadata for {} from {} to {}.'.format(
key, old_value, value))
testcase.set_metadata(key, value)
def _save_fixed_range(testcase_id, min_revision, max_revision):
"""Update a test case and other metadata with a fixed range."""
testcase = data_handler.get_testcase_by_id(testcase_id)
testcase.fixed = f'{min_revision}:{max_revision}'
testcase.open = False
data_handler.update_progression_completion_metadata(
testcase, max_revision, message=f'fixed in range r{testcase.fixed}')
_write_to_bigquery(testcase, min_revision, max_revision)
_ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({
uworker_msg_pb2.ErrorType.PROGRESSION_BAD_BUILD:
handle_progression_bad_build,
uworker_msg_pb2.ErrorType.PROGRESSION_BAD_STATE_MIN_MAX:
handle_progression_bad_state_min_max,
uworker_msg_pb2.ErrorType.PROGRESSION_BUILD_NOT_FOUND:
handle_progression_build_not_found,
uworker_msg_pb2.ErrorType.PROGRESSION_BUILD_SETUP_ERROR:
handle_progression_build_setup_error,
uworker_msg_pb2.ErrorType.PROGRESSION_NO_CRASH:
handle_progression_no_crash,
uworker_msg_pb2.ErrorType.PROGRESSION_REVISION_LIST_ERROR:
handle_progression_revision_list_error,
uworker_msg_pb2.ErrorType.PROGRESSION_TIMEOUT:
handle_progression_timeout,
}).compose_with(
setup.ERROR_HANDLER,
uworker_handle_errors.UNHANDLED_ERROR_HANDLER,
)
The provided code snippet includes necessary dependencies for implementing the `utask_postprocess` function. Write a Python function `def utask_postprocess(output: uworker_msg_pb2.Output)` to solve the following problem:
Trusted: Cleans up after a uworker execute_task, writing anything needed to the db.
Here is the function:
def utask_postprocess(output: uworker_msg_pb2.Output):
"""Trusted: Cleans up after a uworker execute_task, writing anything needed to
the db."""
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
_maybe_clear_progression_last_min_max_metadata(testcase, output)
_cleanup_stacktrace_blob_from_storage(output)
task_output = None
if output.issue_metadata:
_update_issue_metadata(testcase, output.issue_metadata)
if output.HasField('progression_task_output'):
task_output = output.progression_task_output
_update_build_metadata(output.uworker_input.job_type,
task_output.build_data_list)
if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR:
_ERROR_HANDLER.handle(output)
return
if task_output and task_output.crash_on_latest:
crash_on_latest(output)
return
if output.uworker_input.progression_task_input.custom_binary:
# Retry once on another bot to confirm our results and in case this bot is
# in a bad state which we didn't catch through our usual means.
if data_handler.is_first_attempt_for_task(
'progression', testcase, reset_after_retry=True):
tasks.add_task('progression', output.uworker_input.testcase_id,
output.uworker_input.job_type)
data_handler.update_progression_completion_metadata(
testcase, task_output.crash_revision)
return
# The bug is fixed.
testcase.fixed = 'Yes'
testcase.open = False
data_handler.update_progression_completion_metadata(
testcase,
task_output.crash_revision,
message='fixed on latest custom build')
return
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
if task_output.HasField('min_revision'):
_save_fixed_range(output.uworker_input.testcase_id,
task_output.min_revision, task_output.max_revision)
# If there is a fine grained bisection service available, request it. Both
# regression and fixed ranges are requested once. Regression is also requested
# here as the bisection service may require details that are not yet available
# (e.g. issue ID) at the time regress_task completes.
bisection.request_bisection(testcase) | Trusted: Cleans up after a uworker execute_task, writing anything needed to the db. |
157,229 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _get_minimize_task_input(testcase):
testcase_blob_name, testcase_upload_url = blobs.get_blob_signed_upload_url()
(stacktrace_blob_name,
stacktrace_upload_url) = blobs.get_blob_signed_upload_url()
arguments = data_handler.get_arguments(testcase).split()
return uworker_msg_pb2.MinimizeTaskInput(
testcase_upload_url=testcase_upload_url,
testcase_blob_name=testcase_blob_name,
stacktrace_blob_name=stacktrace_blob_name,
stacktrace_upload_url=stacktrace_upload_url,
arguments=arguments)
def _skip_minimization(testcase: data_types.Testcase,
message: str,
crash_result_dict: Dict[str, str] = None):
"""Skip minimization for a testcase, only called during postrocess."""
testcase.minimized_keys = testcase.fuzzed_keys
if crash_result_dict:
_update_crash_result(testcase, crash_result_dict)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
message)
task_creation.create_postminimize_tasks(testcase)
The provided code snippet includes necessary dependencies for implementing the `utask_preprocess` function. Write a Python function `def utask_preprocess(testcase_id, job_type, uworker_env)` to solve the following problem:
Preprocess in a trusted bot.
Here is the function:
def utask_preprocess(testcase_id, job_type, uworker_env):
"""Preprocess in a trusted bot."""
# Locate the testcase associated with the id.
testcase = data_handler.get_testcase_by_id(testcase_id)
# Allow setting up a different fuzzer.
minimize_fuzzer_override = environment.get_value('MINIMIZE_FUZZER_OVERRIDE')
setup_input = setup.preprocess_setup_testcase(
testcase, uworker_env, fuzzer_override=minimize_fuzzer_override)
# TODO(metzman): This should be removed.
if not environment.is_minimization_supported():
# TODO(ochang): More robust check for engine minimization support.
_skip_minimization(testcase, 'Engine does not support minimization.')
return None
# Update comments to reflect bot information.
data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED)
uworker_input = uworker_msg_pb2.Input(
job_type=job_type,
testcase_id=str(testcase_id),
testcase=uworker_io.entity_to_protobuf(testcase),
setup_input=setup_input,
minimize_task_input=_get_minimize_task_input(testcase),
uworker_env=uworker_env)
testcase_manager.preprocess_testcase_manager(testcase, uworker_input)
return uworker_input | Preprocess in a trusted bot. |
157,230 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
class MinimizationPhase:
"""Effectively an enum to represent the current phase of minimization."""
GESTURES = 0
MAIN_FILE = 1
FILE_LIST = 2
RESOURCES = 3
ARGUMENTS = 4
class TestRunner:
"""Helper class for running the same test multiple times."""
def __init__(self, testcase, file_path, files, input_directory, arguments,
required_arguments, threads, deadline):
self.testcase = testcase
self.file_path = file_path
self.files = files
self.input_directory = input_directory
self.gestures = testcase.gestures
self.arguments = arguments
self.threads = threads
self.deadline = deadline
self.cleanup_interval = environment.get_value(
'TESTCASES_BEFORE_STALE_PROCESS_CLEANUP', 1)
self.timeout = environment.get_value('TEST_TIMEOUT', 10)
self.full_timeout = self.timeout
self.last_failing_result = None
self.required_arguments = set(required_arguments.split())
self.expected_security_flag = False
self.is_flaky = False
self.expected_state = None
self._profile_lock = threading.Lock()
self._available_profiles = [True] * threads
self._result_lock = threading.Lock()
self._results = []
self._previous_arguments = None
def _get_profile_index(self):
"""Get the first available profile directory index."""
with self._profile_lock:
for index, is_available in enumerate(self._available_profiles):
if is_available:
self._available_profiles[index] = False
return index
# Raise an exception rather than running in a bad state.
raise errors.BadStateError('No profile directories available.')
def _release_profile(self, index):
"""Mark the specified profile as available."""
with self._profile_lock:
self._available_profiles[index] = True
def _handle_test_result(self, result):
"""Handle a test result, return True on pass (no crash), False on fail."""
if not result.is_crash():
return True
# If we have no crash state, we should not consider this a crash.
state = result.get_state(symbolized=False)
if not state:
return True
# Even though this was a crash, we want to ignore it if the stack does not
# have the expected security flag (e.g. expected UAF but got NULL deref).
if result.is_security_issue() != self.expected_security_flag:
return True
# Ignore failures that do not appear to be caused by this issue.
if not self.is_flaky and state != self.expected_state:
return True
self.last_failing_result = result
return False
def _repopulate_required_arguments(self, arguments):
"""Add required arguments back to the argument list."""
fixed_arguments = []
original_arguments = self.arguments.split()
original_argument_index = 0
argument_index = 0
while original_argument_index < len(original_arguments):
original_argument = original_arguments[original_argument_index]
if (argument_index < len(arguments) and
original_argument == arguments[argument_index]):
argument_index += 1
fixed_arguments.append(original_argument)
elif (original_argument in self.required_arguments or
original_argument.split('=')[0] in self.required_arguments or
'"' in original_argument or "'" in original_argument):
fixed_arguments.append(original_argument)
original_argument_index += 1
return fixed_arguments
def get_argument_string(self, arguments):
"""Convert a list of argument tokens to a usable value."""
fixed_arguments = self._repopulate_required_arguments(arguments)
return ' '.join(fixed_arguments)
def test_with_defaults(self, _):
"""Run a test with all default values."""
result = self.run()
return self._handle_test_result(result)
def test_with_files(self, files):
"""Run the test with the specified file list."""
files_to_rename = list(set(self.files) - set(files))
files_to_skip = []
# Generate a unique suffix to append to files we want to ignore.
index = 0
file_rename_suffix = '___%d' % index
while any([f.endswith(file_rename_suffix) for f in files_to_rename]):
index += 1
file_rename_suffix = '___%d' % index
# Rename all files in the test case's file list but not the specified one.
for file_to_rename in files_to_rename:
absolute_file_to_rename = os.path.join(self.input_directory,
file_to_rename)
try:
os.rename(absolute_file_to_rename,
f'{absolute_file_to_rename}{file_rename_suffix}')
except OSError:
# This can happen if we have already renamed a directory with files
# under it. In this case, make sure we don't try to change the name
# back later.
files_to_skip.append(file_to_rename)
# Clean up any issues with modifications of resources in subdirectories.
for file_to_skip in files_to_skip:
files_to_rename.remove(file_to_skip)
files_to_rename.reverse()
result = self.run()
# Restore previously renamed files to their original locations.
for file_to_rename in files_to_rename:
absolute_file_to_rename = os.path.join(self.input_directory,
file_to_rename)
os.rename(f'{absolute_file_to_rename}{file_rename_suffix}',
absolute_file_to_rename)
return self._handle_test_result(result)
def test_with_file(self, file_path):
"""Run the test with the specified contents for a particular file."""
result = self.run(file_path=file_path)
return self._handle_test_result(result)
def test_with_gestures(self, gestures):
"""Run the test with the specified gesture list."""
result = self.run(gestures=gestures)
return self._handle_test_result(result)
def test_with_command_line_arguments(self, arguments):
"""Run the test with the specified command line."""
fixed_arguments = self.get_argument_string(arguments)
result = self.run(
arguments=fixed_arguments,
timeout=self.full_timeout,
use_fresh_profile=True)
return self._handle_test_result(result)
def set_test_expectations(self, security_flag, is_flaky,
unsymbolized_crash_state):
"""Set expectations when using this runner for tests."""
self.expected_security_flag = security_flag
self.is_flaky = is_flaky
self.expected_state = unsymbolized_crash_state
def run(self,
file_path=None,
gestures=None,
arguments=None,
timeout=None,
log_command=False,
use_fresh_profile=False):
"""Run the test."""
if file_path is None:
file_path = self.file_path
if gestures is None:
gestures = self.gestures
if arguments is None:
arguments = self.arguments
# TODO(mbarbella): Dynamic timeout adjustment.
if timeout is None:
timeout = self.timeout
needs_http = self.testcase.http_flag
profile_index = self._get_profile_index()
if use_fresh_profile and environment.get_value('USER_PROFILE_ARG'):
shell.remove_directory(
testcase_manager.get_user_profile_directory(profile_index))
# For Android, we need to sync our local testcases directory with the one on
# the device.
if environment.is_android():
android.device.push_testcases_to_device()
elif environment.is_trusted_host():
from clusterfuzz._internal.bot.untrusted_runner import file_host
file_host.push_testcases_to_worker()
# If we need to write a command line file, only do so if the arguments have
# changed.
arguments_changed = arguments != self._previous_arguments
self._previous_arguments = arguments
command = testcase_manager.get_command_line_for_application(
file_to_run=file_path,
app_args=arguments,
needs_http=needs_http,
user_profile_index=profile_index,
write_command_line_file=arguments_changed)
if log_command:
logs.log(f'Executing command: {command}')
return_code, crash_time, output = process_handler.run_process(
command, timeout=timeout, gestures=gestures)
self._release_profile(profile_index)
return CrashResult(return_code, crash_time, output)
def store_result_from_run(self, result):
"""Run and store the result for later processing."""
with self._result_lock:
self._results.append(result)
# A race here isn't problematic. Better not to hold the lock during an
# is_crash call.
if not self.last_failing_result and result.is_crash():
self.last_failing_result = result
def execute_parallel_runs(self, runs, instances=None):
"""Run multiple instances of this test in parallel."""
if not instances:
instances = self.threads
# TODO(mbarbella): Hack for Android. If we are running single-threaded, it
# is safe to call a cleanup function on each thread. Ideally, the minimizer
# would like to assume that when it finishes running a process it cleans
# itself up properly.
cleanup_function = None
if self.threads == 1:
cleanup_function = process_handler.cleanup_stale_processes
run_queue = minimizer.TestQueue(
instances, per_thread_cleanup_function=cleanup_function)
for _ in range(runs):
run_queue.push(self.file_path, self.run, self.store_result_from_run)
run_queue.process()
# At timeout, we send SIGTERM. Wait for 2 seconds before sending SIGKILL.
time.sleep(2)
process_handler.cleanup_stale_processes()
with self._result_lock:
results = self._results
self._results = []
return results
def should_attempt_phase(testcase, phase):
"""Return true if we should we attempt a minimization phase."""
if (phase == MinimizationPhase.ARGUMENTS and
environment.is_engine_fuzzer_job()):
# Should not minimize arguments list for engine based fuzzer jobs.
return False
current_phase = testcase.get_metadata(
'minimization_phase', default=MinimizationPhase.GESTURES)
return phase >= current_phase
def minimize_gestures(test_runner, testcase):
"""Minimize the gesture list for a test case."""
gestures = testcase.gestures
if gestures:
gesture_minimizer = delta_minimizer.DeltaMinimizer(
test_runner.test_with_gestures,
max_threads=test_runner.threads,
tokenize=False,
deadline=test_runner.deadline,
cleanup_function=process_handler.cleanup_stale_processes,
single_thread_cleanup_interval=test_runner.cleanup_interval,
progress_report_function=functools.partial(logs.log))
gestures = gesture_minimizer.minimize(gestures)
logs.log(f'Minimized gestures: {str(gestures)}')
return gestures
def minimize_main_file(test_runner, testcase_file_path, data):
"""Minimize the main test case file."""
if not can_minimize_file(testcase_file_path):
return data
get_random_file = functools.partial(get_temporary_file, testcase_file_path)
data = (
minimize_file(testcase_file_path, test_runner.test_with_file,
get_random_file, data, test_runner.deadline,
test_runner.threads, test_runner.cleanup_interval))
logs.log('Minimized main test file.')
return data
def minimize_file_list(test_runner, file_list, input_directory, main_file):
"""Minimize the test case files."""
if len(file_list) <= 1:
return file_list
# TODO(mbarbella): Simplify this with refactoring of setup_testcase.
offset = len(input_directory) + len(os.path.sep)
fixed_testcase_file_path = main_file[offset:]
# As of now, this must be single-threaded.
file_list_minimizer = basic_minimizers.SinglePassMinimizer(
test_runner.test_with_files,
tokenize=False,
deadline=test_runner.deadline,
cleanup_function=process_handler.cleanup_stale_processes,
single_thread_cleanup_interval=test_runner.cleanup_interval,
progress_report_function=functools.partial(logs.log))
file_list = file_list_minimizer.minimize(file_list)
if fixed_testcase_file_path not in file_list:
file_list.append(fixed_testcase_file_path)
logs.log(f'Minimized file list: {str(file_list)}')
return file_list
def minimize_resource(test_runner, dependency, input_directory, main_file):
"""Minimize a resource for the test case."""
# TODO(mbarbella): Simplify this with refactoring of setup_testcase.
offset = len(input_directory) + len(os.path.sep)
fixed_testcase_file_path = main_file[offset:]
dependency_absolute_path = os.path.join(input_directory, dependency)
if (dependency == fixed_testcase_file_path or dependency == main_file or
not can_minimize_file(dependency_absolute_path)):
return
get_temp_file = functools.partial(
get_temporary_file, dependency_absolute_path, no_modifications=True)
original_data = utils.get_file_contents_with_fatal_error_on_failure(
dependency_absolute_path)
dependency_data = (
minimize_file(
dependency,
test_runner.test_with_defaults,
get_temp_file,
original_data,
test_runner.deadline,
1,
test_runner.cleanup_interval,
delete_temp_files=False))
utils.write_data_to_file(dependency_data, dependency_absolute_path)
logs.log(f'Minimized dependency file: {dependency}')
def minimize_arguments(test_runner, app_arguments):
"""Minimize the argument list for a test case."""
argument_minimizer = delta_minimizer.DeltaMinimizer(
test_runner.test_with_command_line_arguments,
max_threads=test_runner.threads,
tokenize=False,
deadline=test_runner.deadline,
cleanup_function=process_handler.cleanup_stale_processes,
single_thread_cleanup_interval=test_runner.cleanup_interval,
progress_report_function=functools.partial(logs.log))
reduced_args = argument_minimizer.minimize(app_arguments.split())
reduced_arg_string = test_runner.get_argument_string(reduced_args)
return reduced_arg_string
def store_minimized_testcase(
testcase: data_types.Testcase, base_directory: str, file_list: List[str],
file_to_run_data: str, file_to_run: str,
minimize_task_input: uworker_msg_pb2.MinimizeTaskInput,
minimize_task_output: uworker_msg_pb2.MinimizeTaskOutput):
"""Store all files that make up this testcase."""
# Write the main file data.
utils.write_data_to_file(file_to_run_data, file_to_run)
# Prepare the file.
zip_path = None
if testcase.archive_state:
if len(file_list) > 1:
testcase.archive_state |= data_types.ArchiveStatus.MINIMIZED
minimize_task_output.archive_state = testcase.archive_state
zip_path = os.path.join(
environment.get_value('INPUT_DIR'), '%d.zip' % testcase.key.id())
zip_file = zipfile.ZipFile(zip_path, 'w')
count = 0
filtered_file_list = []
for file_name in file_list:
absolute_filename = os.path.join(base_directory, file_name)
is_file = os.path.isfile(absolute_filename)
if file_to_run_data and is_file and os.path.getsize(
absolute_filename) == 0 and (os.path.basename(
absolute_filename).encode('utf-8') not in file_to_run_data):
continue
if not os.path.exists(absolute_filename):
continue
zip_file.write(absolute_filename, file_name, zipfile.ZIP_DEFLATED)
if is_file:
count += 1
filtered_file_list.append(absolute_filename)
zip_file.close()
try:
if count > 1:
file_handle = open(zip_path, 'rb')
else:
if not filtered_file_list:
# We minimized everything. The only thing needed to reproduce is the
# interaction gesture.
file_path = file_list[0]
file_handle = open(file_path, 'wb')
file_handle.close()
else:
file_path = filtered_file_list[0]
file_handle = open(file_path, 'rb')
testcase.absolute_path = os.path.join(base_directory,
os.path.basename(file_path))
minimize_task_output.absolute_path = testcase.absolute_path
testcase.archive_state &= ~data_types.ArchiveStatus.MINIMIZED
minimize_task_output.archive_state = testcase.archive_state
except OSError:
logs.log_error('Unable to open archive for blobstore write.')
return
else:
absolute_filename = os.path.join(base_directory, file_list[0])
file_handle = open(absolute_filename, 'rb')
testcase.archive_state &= ~data_types.ArchiveStatus.MINIMIZED
minimize_task_output.archive_state = testcase.archive_state
else:
file_handle = open(file_list[0], 'rb')
testcase.archive_state &= ~data_types.ArchiveStatus.MINIMIZED
minimize_task_output.archive_state = testcase.archive_state
# Store the testcase.
data = file_handle.read()
storage.upload_signed_url(data, minimize_task_input.testcase_upload_url)
minimized_keys = minimize_task_input.testcase_blob_name
file_handle.close()
testcase.minimized_keys = minimized_keys
minimize_task_output.minimized_keys = minimized_keys
if zip_path:
shell.remove_file(zip_path)
def check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase: data_types.Testcase, input_directory: str, file_list,
file_to_run_data, main_file_path: str,
minimize_task_input: uworker_msg_pb2.MinimizeTaskInput,
minimize_task_output: uworker_msg_pb2.MinimizeTaskOutput) -> bool:
"""Store the partially minimized test and check the deadline."""
store_minimized_testcase(testcase, input_directory, file_list,
file_to_run_data, main_file_path,
minimize_task_input, minimize_task_output)
return time.time() > deadline
def check_for_initial_crash(test_runner, crash_retries, testcase):
"""Initial check to see how long it takes to reproduce a crash."""
crash_times = []
flaky_stack = False
saved_crash_state = None
saved_security_flag = None
saved_unsymbolized_crash_state = None
results = test_runner.execute_parallel_runs(crash_retries)
for result in results:
if not result.is_crash():
continue
if result.should_ignore():
continue
crash_state = result.get_state(symbolized=True)
security_flag = result.is_security_issue()
unsymbolized_crash_state = result.get_state(symbolized=False)
if not unsymbolized_crash_state:
continue
if security_flag != testcase.security_flag:
continue
crash_times.append(result.crash_time)
if not saved_crash_state:
saved_crash_state = crash_state
saved_security_flag = security_flag
saved_unsymbolized_crash_state = unsymbolized_crash_state
continue
crash_comparer = CrashComparer(crash_state, saved_crash_state)
if not crash_comparer.is_similar():
flaky_stack = True
logs.log(f'Total crash count: {len(crash_times)}/{crash_retries}.'
f'Flaky: {flaky_stack}. Security: {saved_security_flag}.'
f'State:\n{saved_crash_state}')
return saved_unsymbolized_crash_state, flaky_stack, crash_times
def _extract_crash_result(crash_result, command, minimize_task_input):
"""Extract necessary data from CrashResult."""
if not crash_result:
raise errors.BadStateError(
'No crash result was provided to _extract_crash_result')
min_state = crash_result.get_symbolized_data()
min_unsymbolized_crash_stacktrace = crash_result.get_stacktrace(
symbolized=False)
min_crash_stacktrace = utils.get_crash_stacktrace_output(
command, min_state.crash_stacktrace, min_unsymbolized_crash_stacktrace)
return {
'crash_type':
min_state.crash_type,
'crash_address':
min_state.crash_address,
'crash_state':
min_state.crash_state,
'crash_stacktrace':
data_handler.filter_stacktrace(
min_crash_stacktrace, minimize_task_input.stacktrace_blob_name,
minimize_task_input.stacktrace_upload_url),
}
def do_libfuzzer_minimization(
fuzz_target: Optional[data_types.FuzzTarget],
minimize_task_input: uworker_msg_pb2.MinimizeTaskInput,
testcase: data_types.Testcase,
testcase_file_path: str) -> uworker_msg_pb2.Output:
"""Use libFuzzer's built-in minimizer where appropriate."""
timeout = environment.get_value('LIBFUZZER_MINIMIZATION_TIMEOUT', 600)
rounds = environment.get_value('LIBFUZZER_MINIMIZATION_ROUNDS', 5)
current_testcase_path = testcase_file_path
last_crash_result = None
# Get initial crash state.
initial_crash_result = _run_libfuzzer_testcase(
fuzz_target, testcase, testcase_file_path,
crash_retries=None) # Use default retries.
if not initial_crash_result.is_crash():
logs.log_warn('Did not crash. Output:\n' +
initial_crash_result.get_stacktrace(symbolized=True))
return uworker_msg_pb2.Output(error_type=uworker_msg_pb2.ErrorType.
LIBFUZZER_MINIMIZATION_UNREPRODUCIBLE)
if testcase.security_flag != initial_crash_result.is_security_issue():
logs.log_warn('Security flag does not match.')
return uworker_msg_pb2.Output(error_type=uworker_msg_pb2.ErrorType.
LIBFUZZER_MINIMIZATION_UNREPRODUCIBLE)
expected_state = initial_crash_result.get_symbolized_data()
logs.log(f'Initial crash state: {expected_state.crash_state}\n')
# Minimize *_OPTIONS env variable first.
env = {}
# A Dict[str, str] potentially containing options_env_var strings and the
# corresponding minimized_options_string to be parsed and set in testcase
# metadata during postprocess.
memory_tool_options = {}
for tool in environment.SUPPORTED_MEMORY_TOOLS_FOR_OPTIONS:
options_env_var = tool + '_OPTIONS'
options = environment.get_memory_tool_options(options_env_var)
if not options:
continue
minimized_options = options.copy()
for options_name, options_value in options.items():
if utils.is_oss_fuzz() and options_name in MANDATORY_OSS_FUZZ_OPTIONS:
continue
minimized_options.pop(options_name)
environment.set_memory_tool_options(options_env_var, minimized_options)
reproduced = False
for _ in range(MINIMIZE_SANITIZER_OPTIONS_RETRIES):
crash_result = _run_libfuzzer_testcase(fuzz_target, testcase,
testcase_file_path)
if (crash_result.is_crash() and crash_result.is_security_issue() ==
initial_crash_result.is_security_issue() and
crash_result.get_type() == initial_crash_result.get_type() and
crash_result.get_state() == initial_crash_result.get_state()):
reproduced = True
break
if reproduced:
logs.log(
'Removed unneeded {options_env_var} option: {options_name}'.format(
options_env_var=options_env_var, options_name=options_name))
else:
minimized_options[options_name] = options_value
logs.log(
'Skipped needed {options_env_var} option: {options_name}'.format(
options_env_var=options_env_var, options_name=options_name),
crash_type=crash_result.get_type(),
crash_state=crash_result.get_state(),
security_flag=crash_result.is_security_issue())
environment.set_memory_tool_options(options_env_var, minimized_options)
env[options_env_var] = environment.get_memory_tool_options(options_env_var)
memory_tool_options[options_env_var] = environment.join_memory_tool_options(
minimized_options)
if env:
testcase.set_metadata('env', env, False)
minimized_keys = None
# We attempt minimization multiple times in case one round results in an
# incorrect state, or runs into another issue such as a slow unit.
for round_number in range(1, rounds + 1):
logs.log(f'Minimizing round {round_number}.')
output_file_path, crash_result, minimized_keys = _run_libfuzzer_tool(
'minimize',
testcase,
current_testcase_path,
timeout,
expected_state.crash_state,
minimize_task_input,
fuzz_target,
set_dedup_flags=True)
if output_file_path:
last_crash_result = crash_result
current_testcase_path = output_file_path
if not last_crash_result:
repro_command = testcase_manager.get_command_line_for_application(
file_to_run=testcase_file_path, needs_http=testcase.http_flag)
crash_result_dict = _extract_crash_result(
initial_crash_result, repro_command, minimize_task_input)
minimize_task_output = uworker_msg_pb2.MinimizeTaskOutput(
last_crash_result_dict=crash_result_dict,
memory_tool_options=memory_tool_options)
if minimized_keys:
minimize_task_output.minimized_keys = str(minimized_keys)
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.LIBFUZZER_MINIMIZATION_FAILED,
minimize_task_output=minimize_task_output)
logs.log('LibFuzzer minimization succeeded.')
if utils.is_oss_fuzz():
# Scrub the testcase of non-essential data.
cleansed_testcase_path, minimized_keys = do_libfuzzer_cleanse(
fuzz_target, testcase, current_testcase_path,
expected_state.crash_state, minimize_task_input)
if cleansed_testcase_path:
current_testcase_path = cleansed_testcase_path
# Finalize the test case if we were able to reproduce it.
repro_command = testcase_manager.get_command_line_for_application(
file_to_run=current_testcase_path, needs_http=testcase.http_flag)
last_crash_result_dict = _extract_crash_result(
last_crash_result, repro_command, minimize_task_input)
# Clean up after we're done.
shell.clear_testcase_directories()
minimize_task_output = uworker_msg_pb2.MinimizeTaskOutput(
last_crash_result_dict=last_crash_result_dict,
memory_tool_options=memory_tool_options)
if minimized_keys:
minimize_task_output.minimized_keys = str(minimized_keys)
return uworker_msg_pb2.Output(minimize_task_output=minimize_task_output)
The provided code snippet includes necessary dependencies for implementing the `utask_main` function. Write a Python function `def utask_main(uworker_input: uworker_msg_pb2.Input)` to solve the following problem:
Attempt to minimize a given testcase.
Here is the function:
def utask_main(uworker_input: uworker_msg_pb2.Input):
"""Attempt to minimize a given testcase."""
testcase = uworker_io.entity_from_protobuf(uworker_input.testcase,
data_types.Testcase)
uworker_io.check_handling_testcase_safe(testcase)
minimize_task_input = uworker_input.minimize_task_input
# Setup testcase and its dependencies.
file_list, testcase_file_path, uworker_error_output = setup.setup_testcase(
testcase, uworker_input.job_type, uworker_input.setup_input)
if uworker_error_output:
return uworker_error_output
# Initialize variables.
max_timeout = environment.get_value('TEST_TIMEOUT', 10)
app_arguments = environment.get_value('APP_ARGS')
# Set up a custom or regular build based on revision.
last_tested_crash_revision = testcase.get_metadata(
'last_tested_crash_revision')
crash_revision = last_tested_crash_revision or testcase.crash_revision
build_manager.setup_build(crash_revision)
# Check if we have an application path. If not, our build failed
# to setup correctly.
if not build_manager.check_app_path():
logs.log_error('Unable to setup build for minimization.')
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_SETUP)
if environment.is_libfuzzer_job():
fuzz_target = testcase_manager.get_fuzz_target_from_input(uworker_input)
return do_libfuzzer_minimization(fuzz_target, minimize_task_input, testcase,
testcase_file_path)
if environment.is_engine_fuzzer_job():
logs.log_error(
'Engine does not support minimization. Something went wrong as this'
' should have been detected in preprocess.')
return None
max_threads = utils.maximum_parallel_processes_allowed()
# Prepare the test case runner.
crash_retries = environment.get_value('CRASH_RETRIES')
warmup_timeout = environment.get_value('WARMUP_TIMEOUT')
required_arguments = environment.get_value('REQUIRED_APP_ARGS', '')
# Add any testcase-specific required arguments if needed.
additional_required_arguments = testcase.get_metadata(
'additional_required_app_args')
if additional_required_arguments:
required_arguments = f'{required_arguments} {additional_required_arguments}'
input_directory = environment.get_value('FUZZ_INPUTS')
# Get deadline to finish this task.
deadline = tasks.get_task_completion_deadline()
test_runner = TestRunner(testcase, testcase_file_path, file_list,
input_directory, app_arguments, required_arguments,
max_threads, deadline)
# Verify the crash with a long timeout.
warmup_crash_occurred = False
result = test_runner.run(timeout=warmup_timeout, log_command=True)
if result.is_crash():
warmup_crash_occurred = True
logs.log(f'Warmup crash occurred in {result.crash_time} seconds.')
saved_unsymbolized_crash_state, flaky_stack, crash_times = (
check_for_initial_crash(test_runner, crash_retries, testcase))
# If the warmup crash occurred but we couldn't reproduce this in with
# multiple processes running in parallel, try to minimize single threaded.
reproducible_crash_count = (
testcase_manager.REPRODUCIBILITY_FACTOR * crash_retries)
if (len(crash_times) < reproducible_crash_count and warmup_crash_occurred and
max_threads > 1):
logs.log('Attempting to continue single-threaded.')
max_threads = 1
test_runner = TestRunner(testcase, testcase_file_path, file_list,
input_directory, app_arguments, required_arguments,
max_threads, deadline)
saved_unsymbolized_crash_state, flaky_stack, crash_times = (
check_for_initial_crash(test_runner, crash_retries, testcase))
if not crash_times:
# We didn't crash at all. This might be a legitimately unreproducible
# test case, so it will get marked as such after being retried on other
# bots.
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_UNREPRODUCIBLE_CRASH)
minimize_task_output = uworker_msg_pb2.MinimizeTaskOutput()
if flaky_stack:
testcase.flaky_stack = flaky_stack
minimize_task_output.flaky_stack = flaky_stack
is_redo = testcase.get_metadata('redo_minimize')
if not is_redo and len(crash_times) < reproducible_crash_count:
error_message = (
'Crash occurs, but not too consistently. Skipping minimization '
f'(crashed {len(crash_times)}/{crash_retries})')
return uworker_msg_pb2.Output(
error_message=error_message,
minimize_task_output=minimize_task_output,
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_CRASH_TOO_FLAKY)
test_runner.set_test_expectations(testcase.security_flag, flaky_stack,
saved_unsymbolized_crash_state)
# Use the max crash time unless this would be greater than the max timeout.
test_timeout = min(max(crash_times), max_timeout) + 1
logs.log(f'Using timeout {test_timeout} (was {max_timeout})')
test_runner.timeout = test_timeout
logs.log('Starting minimization.')
if should_attempt_phase(testcase, MinimizationPhase.GESTURES):
gestures = minimize_gestures(test_runner, testcase)
# We can't call check_deadline_exceeded_and_store_partial_minimized_testcase
# at this point because we do not have a test case to store.
if testcase.security_flag and len(testcase.gestures) != len(gestures):
# Re-run security severity analysis since gestures affect the severity.
testcase.security_severity = severity_analyzer.get_security_severity(
testcase.crash_type, data_handler.get_stacktrace(testcase),
uworker_input.job_type, bool(gestures))
minimize_task_output.security_severity_updated = True
if testcase.security_severity is not None:
minimize_task_output.security_severity = testcase.security_severity
testcase.gestures = gestures
del minimize_task_output.gestures[:]
minimize_task_output.gestures.extend(gestures)
testcase.set_metadata('minimization_phase', MinimizationPhase.MAIN_FILE,
False)
minimize_task_output.minimization_phase = MinimizationPhase.MAIN_FILE
if time.time() > test_runner.deadline:
return uworker_msg_pb2.Output(
minimize_task_output=minimize_task_output,
error_type=uworker_msg_pb2.ErrorType.
MINIMIZE_DEADLINE_EXCEEDED_IN_MAIN_FILE_PHASE)
# Minimize the main file.
data = utils.get_file_contents_with_fatal_error_on_failure(testcase_file_path)
if should_attempt_phase(testcase, MinimizationPhase.MAIN_FILE):
data = minimize_main_file(test_runner, testcase_file_path, data)
if check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase, input_directory, file_list, data,
testcase_file_path, minimize_task_input, minimize_task_output):
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_DEADLINE_EXCEEDED,
minimize_task_output=minimize_task_output)
testcase.set_metadata('minimization_phase', MinimizationPhase.FILE_LIST,
False)
minimize_task_output.minimization_phase = MinimizationPhase.FILE_LIST
# Minimize the file list.
if should_attempt_phase(testcase, MinimizationPhase.FILE_LIST):
if environment.get_value('MINIMIZE_FILE_LIST', True):
file_list = minimize_file_list(test_runner, file_list, input_directory,
testcase_file_path)
if check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase, input_directory, file_list, data,
testcase_file_path, minimize_task_input, minimize_task_output):
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_DEADLINE_EXCEEDED,
minimize_task_output=minimize_task_output)
else:
logs.log('Skipping minimization of file list.')
testcase.set_metadata('minimization_phase', MinimizationPhase.RESOURCES,
False)
minimize_task_output.minimization_phase = MinimizationPhase.RESOURCES
# Minimize any files remaining in the file list.
if should_attempt_phase(testcase, MinimizationPhase.RESOURCES):
if environment.get_value('MINIMIZE_RESOURCES', True):
for dependency in file_list:
minimize_resource(test_runner, dependency, input_directory,
testcase_file_path)
if check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase, input_directory, file_list, data,
testcase_file_path, minimize_task_input, minimize_task_output):
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_DEADLINE_EXCEEDED,
minimize_task_output=minimize_task_output)
else:
logs.log('Skipping minimization of resources.')
testcase.set_metadata('minimization_phase', MinimizationPhase.ARGUMENTS,
False)
minimize_task_output.minimization_phase = MinimizationPhase.ARGUMENTS
if should_attempt_phase(testcase, MinimizationPhase.ARGUMENTS):
app_arguments = minimize_arguments(test_runner, app_arguments)
# Arguments must be stored here in case we time out below.
testcase.minimized_arguments = app_arguments
minimize_task_output.minimized_arguments = app_arguments
if check_deadline_exceeded_and_store_partial_minimized_testcase(
deadline, testcase, input_directory, file_list, data,
testcase_file_path, minimize_task_input, minimize_task_output):
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.MINIMIZE_DEADLINE_EXCEEDED,
minimize_task_output=minimize_task_output)
command = testcase_manager.get_command_line_for_application(
testcase_file_path, app_args=app_arguments, needs_http=testcase.http_flag)
last_crash_result = test_runner.last_failing_result
store_minimized_testcase(testcase, input_directory, file_list, data,
testcase_file_path, minimize_task_input,
minimize_task_output)
minimize_task_output.last_crash_result_dict.clear()
minimize_task_output.last_crash_result_dict.update(
_extract_crash_result(last_crash_result, command, minimize_task_input))
return uworker_msg_pb2.Output(minimize_task_output=minimize_task_output) | Attempt to minimize a given testcase. |
157,231 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _skip_minimization(testcase: data_types.Testcase,
message: str,
crash_result_dict: Dict[str, str] = None):
"""Skip minimization for a testcase, only called during postrocess."""
testcase.minimized_keys = testcase.fuzzed_keys
if crash_result_dict:
_update_crash_result(testcase, crash_result_dict)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
message)
task_creation.create_postminimize_tasks(testcase)
The provided code snippet includes necessary dependencies for implementing the `handle_minimize_setup_error` function. Write a Python function `def handle_minimize_setup_error(output)` to solve the following problem:
Handles errors occuring during setup.
Here is the function:
def handle_minimize_setup_error(output):
"""Handles errors occuring during setup."""
build_fail_wait = environment.get_value('FAIL_WAIT')
if environment.get_value('ORIGINAL_JOB_NAME'):
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
_skip_minimization(testcase, 'Failed to setup build for overridden job.')
else:
# Only recreate task if this isn't an overriden job. It's possible that a
# revision exists for the original job, but doesn't exist for the
# overriden job.
build_fail_wait = environment.get_value('FAIL_WAIT')
tasks.add_task(
'minimize',
output.uworker_input.testcase_id,
output.uworker_input.job_type,
wait_time=build_fail_wait) | Handles errors occuring during setup. |
157,232 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `handle_minimize_unreproducible_crash` function. Write a Python function `def handle_minimize_unreproducible_crash(output)` to solve the following problem:
Handles unreproducible crashes.
Here is the function:
def handle_minimize_unreproducible_crash(output):
"""Handles unreproducible crashes."""
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
'Unable to reproduce crash')
task_creation.mark_unreproducible_if_flaky(testcase, 'minimize', True) | Handles unreproducible crashes. |
157,233 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `handle_minimize_crash_too_flaky` function. Write a Python function `def handle_minimize_crash_too_flaky(output)` to solve the following problem:
Schedules postminimize tasks when the crash is too flaky.
Here is the function:
def handle_minimize_crash_too_flaky(output):
"""Schedules postminimize tasks when the crash is too flaky."""
# We reproduced this crash at least once. It's too flaky to minimize, but
# maybe we'll have more luck in the other jobs.
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
testcase.minimized_keys = 'NA'
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
output.error_message)
task_creation.create_postminimize_tasks(testcase) | Schedules postminimize tasks when the crash is too flaky. |
157,234 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `handle_minimize_deadline_exceeded_in_main_file_phase` function. Write a Python function `def handle_minimize_deadline_exceeded_in_main_file_phase(output)` to solve the following problem:
Reschedules the minimize task when the deadline is exceeded just before starting the main file phase.
Here is the function:
def handle_minimize_deadline_exceeded_in_main_file_phase(output):
"""Reschedules the minimize task when the deadline is exceeded just before
starting the main file phase."""
tasks.add_task('minimize', output.uworker_input.testcase_id,
output.uworker_input.job_type) | Reschedules the minimize task when the deadline is exceeded just before starting the main file phase. |
157,235 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
MAX_DEADLINE_EXCEEDED_ATTEMPTS = 3
def _skip_minimization(testcase: data_types.Testcase,
message: str,
crash_result_dict: Dict[str, str] = None):
"""Skip minimization for a testcase, only called during postrocess."""
testcase.minimized_keys = testcase.fuzzed_keys
if crash_result_dict:
_update_crash_result(testcase, crash_result_dict)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
message)
task_creation.create_postminimize_tasks(testcase)
The provided code snippet includes necessary dependencies for implementing the `handle_minimize_deadline_exceeded` function. Write a Python function `def handle_minimize_deadline_exceeded(output: uworker_msg_pb2.Output)` to solve the following problem:
Reschedules a minimize task when minimization deadline is exceeded or calls _skip_minimization when the number of reattempts is surpassed.
Here is the function:
def handle_minimize_deadline_exceeded(output: uworker_msg_pb2.Output):
"""Reschedules a minimize task when minimization deadline is exceeded or
calls _skip_minimization when the number of reattempts is surpassed."""
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
attempts = testcase.get_metadata(
'minimization_deadline_exceeded_attempts', default=0)
if attempts >= MAX_DEADLINE_EXCEEDED_ATTEMPTS:
_skip_minimization(testcase,
'Exceeded minimization deadline too many times.')
else:
testcase.set_metadata('minimization_deadline_exceeded_attempts',
attempts + 1)
tasks.add_task('minimize', output.uworker_input.testcase_id,
output.uworker_input.job_type) | Reschedules a minimize task when minimization deadline is exceeded or calls _skip_minimization when the number of reattempts is surpassed. |
157,236 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _skip_minimization(testcase: data_types.Testcase,
message: str,
crash_result_dict: Dict[str, str] = None):
"""Skip minimization for a testcase, only called during postrocess."""
testcase.minimized_keys = testcase.fuzzed_keys
if crash_result_dict:
_update_crash_result(testcase, crash_result_dict)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
message)
task_creation.create_postminimize_tasks(testcase)
The provided code snippet includes necessary dependencies for implementing the `handle_libfuzzer_minimization_unreproducible` function. Write a Python function `def handle_libfuzzer_minimization_unreproducible( output: uworker_msg_pb2.Output)` to solve the following problem:
Handles libfuzzer minimization task's failure to reproduce the issue.
Here is the function:
def handle_libfuzzer_minimization_unreproducible(
output: uworker_msg_pb2.Output):
"""Handles libfuzzer minimization task's failure to reproduce the issue."""
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
# Be more lenient with marking testcases as unreproducible when this is a
# job override.
is_overriden_job = bool(environment.get_value('ORIGINAL_JOB_NAME'))
if is_overriden_job:
_skip_minimization(testcase, 'Unreproducible on overridden job')
else:
task_creation.mark_unreproducible_if_flaky(testcase, 'minimize', True) | Handles libfuzzer minimization task's failure to reproduce the issue. |
157,237 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _skip_minimization(testcase: data_types.Testcase,
message: str,
crash_result_dict: Dict[str, str] = None):
"""Skip minimization for a testcase, only called during postrocess."""
testcase.minimized_keys = testcase.fuzzed_keys
if crash_result_dict:
_update_crash_result(testcase, crash_result_dict)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
message)
task_creation.create_postminimize_tasks(testcase)
The provided code snippet includes necessary dependencies for implementing the `handle_libfuzzer_minimization_failed` function. Write a Python function `def handle_libfuzzer_minimization_failed(output: uworker_msg_pb2.Output)` to solve the following problem:
Handles libfuzzer minimization task failure.
Here is the function:
def handle_libfuzzer_minimization_failed(output: uworker_msg_pb2.Output):
"""Handles libfuzzer minimization task failure."""
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
_skip_minimization(
testcase,
'LibFuzzer minimization failed',
crash_result_dict=output.minimize_task_output.last_crash_result_dict) | Handles libfuzzer minimization task failure. |
157,238 | import binascii
import functools
import os
import threading
import time
from typing import Dict
from typing import List
from typing import Optional
import zipfile
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers.libFuzzer import \
engine as libfuzzer_engine
from clusterfuzz._internal.bot.minimizer import basic_minimizers
from clusterfuzz._internal.bot.minimizer import delta_minimizer
from clusterfuzz._internal.bot.minimizer import errors as minimizer_errors
from clusterfuzz._internal.bot.minimizer import html_minimizer
from clusterfuzz._internal.bot.minimizer import js_minimizer
from clusterfuzz._internal.bot.minimizer import minimizer
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer
from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \
JavaScriptLexer
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import severity_analyzer
from clusterfuzz._internal.crash_analysis.crash_comparer import CrashComparer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _cleanup_unused_blobs_from_storage(output: uworker_msg_pb2.Output):
"""Cleanup the blobs created in preprocess if they weren't used during
utask_main."""
delete_testcase_blob = True
delete_stacktrace_blob = True
if output.HasField('minimize_task_output'):
# If minimized_keys was set, we should not cleanup the corresponding blob.
if output.minimize_task_output.HasField("minimized_keys"):
delete_testcase_blob = False
stacktrace_blob_key = output.minimize_task_output.last_crash_result_dict[
'crash_stacktrace']
if stacktrace_blob_key.startswith(data_types.BLOBSTORE_STACK_PREFIX):
delete_stacktrace_blob = False
testcase_blob_name = (
output.uworker_input.minimize_task_input.testcase_blob_name)
stacktrace_blob_name = (
output.uworker_input.minimize_task_input.stacktrace_blob_name)
if delete_testcase_blob:
blobs.delete_blob(testcase_blob_name)
if delete_stacktrace_blob:
blobs.delete_blob(stacktrace_blob_name)
def update_testcase(output: uworker_msg_pb2.Output):
"""Updates the tescase using the values passed from utask_main. This is done
at the beginning of utask_postprocess and before error handling is called."""
if not output.HasField('minimize_task_output'):
return
minimize_task_output = output.minimize_task_output
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
_update_testcase_memory_tool_options(testcase,
minimize_task_output.memory_tool_options)
if minimize_task_output.security_severity_updated:
if minimize_task_output.HasField('security_severity'):
testcase.security_severity = minimize_task_output.security_severity
else:
testcase.security_severity = None
if minimize_task_output.HasField('minimization_phase'):
testcase.set_metadata('minimization_phase',
minimize_task_output.minimization_phase)
if minimize_task_output.flaky_stack:
testcase.flaky_stack = minimize_task_output.flaky_stack
if minimize_task_output.HasField('minimized_arguments'):
testcase.minimized_arguments = minimize_task_output.minimized_arguments
if minimize_task_output.HasField('archive_state'):
testcase.archive_state = minimize_task_output.archive_state
if minimize_task_output.HasField('absolute_path'):
testcase.absolute_path = minimize_task_output.absolute_path
if minimize_task_output.gestures:
# One must convert repeated fields to lists in order to save them using ndb.
testcase.gestures = list(minimize_task_output.gestures)
if minimize_task_output.HasField('minimized_keys'):
testcase.minimized_keys = minimize_task_output.minimized_keys
testcase.put()
_ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({
uworker_msg_pb2.ErrorType.LIBFUZZER_MINIMIZATION_FAILED:
handle_libfuzzer_minimization_failed,
uworker_msg_pb2.ErrorType.LIBFUZZER_MINIMIZATION_UNREPRODUCIBLE:
handle_libfuzzer_minimization_unreproducible,
uworker_msg_pb2.ErrorType.MINIMIZE_CRASH_TOO_FLAKY:
handle_minimize_crash_too_flaky,
uworker_msg_pb2.ErrorType.MINIMIZE_DEADLINE_EXCEEDED:
handle_minimize_deadline_exceeded,
uworker_msg_pb2.ErrorType.MINIMIZE_DEADLINE_EXCEEDED_IN_MAIN_FILE_PHASE:
handle_minimize_deadline_exceeded_in_main_file_phase,
uworker_msg_pb2.ErrorType.MINIMIZE_SETUP:
handle_minimize_setup_error,
uworker_msg_pb2.ErrorType.MINIMIZE_UNREPRODUCIBLE_CRASH:
handle_minimize_unreproducible_crash,
}).compose_with(
setup.ERROR_HANDLER,
uworker_handle_errors.UNHANDLED_ERROR_HANDLER,
)
def finalize_testcase(testcase_id, last_crash_result_dict, flaky_stack=False):
"""Perform final updates on a test case and prepare it for other tasks."""
# Symbolize crash output if we have it.
testcase = data_handler.get_testcase_by_id(testcase_id)
if last_crash_result_dict:
_update_crash_result(testcase, last_crash_result_dict)
testcase.delete_metadata('redo_minimize', update_testcase=False)
# Update remaining test case information.
testcase.flaky_stack = flaky_stack
if build_manager.is_custom_binary():
testcase.set_impacts_as_na()
testcase.regression = 'NA'
data_handler.update_testcase_comment(testcase, data_types.TaskState.FINISHED)
# We might have updated the crash state. See if we need to marked as duplicate
# based on other testcases.
data_handler.handle_duplicate_entry(testcase)
task_creation.create_postminimize_tasks(testcase)
The provided code snippet includes necessary dependencies for implementing the `utask_postprocess` function. Write a Python function `def utask_postprocess(output)` to solve the following problem:
Postprocess in a trusted bot.
Here is the function:
def utask_postprocess(output):
"""Postprocess in a trusted bot."""
update_testcase(output)
_cleanup_unused_blobs_from_storage(output)
if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR:
_ERROR_HANDLER.handle(output)
return
finalize_testcase(
output.uworker_input.testcase_id,
output.minimize_task_output.last_crash_result_dict,
flaky_stack=output.minimize_task_output.flaky_stack) | Postprocess in a trusted bot. |
157,239 | import os
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
def handle_build_setup_error(output):
testcase_id = output.uworker_input.testcase_id
job_type = output.uworker_input.job_type
testcase = data_handler.get_testcase_by_id(testcase_id)
build_fail_wait = environment.get_value('FAIL_WAIT')
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
'Build setup failed')
tasks.add_task('symbolize', testcase_id, job_type, wait_time=build_fail_wait) | null |
157,240 | import os
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
The provided code snippet includes necessary dependencies for implementing the `utask_preprocess` function. Write a Python function `def utask_preprocess(testcase_id, job_type, uworker_env)` to solve the following problem:
Runs preprocessing for symbolize task.
Here is the function:
def utask_preprocess(testcase_id, job_type, uworker_env):
"""Runs preprocessing for symbolize task."""
# Locate the testcase associated with the id.
testcase = data_handler.get_testcase_by_id(testcase_id)
# We should atleast have a symbolized debug or release build.
if not build_manager.has_symbolized_builds():
return None
data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED)
# Setup testcase and its dependencies.
setup_input = setup.preprocess_setup_testcase(testcase, uworker_env)
old_crash_stacktrace = data_handler.get_stacktrace(testcase)
return uworker_msg_pb2.Input(
job_type=job_type,
testcase_id=testcase_id,
uworker_env=uworker_env,
setup_input=setup_input,
testcase=uworker_io.entity_to_protobuf(testcase),
symbolize_task_input=uworker_msg_pb2.SymbolizeTaskInput(
old_crash_stacktrace=old_crash_stacktrace)) | Runs preprocessing for symbolize task. |
157,241 | import os
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
DEFAULT_REDZONE = 128
MAX_REDZONE = 1024
MIN_REDZONE = 16
STACK_FRAME_COUNT = 128
def get_symbolized_stacktraces(testcase_file_path, testcase,
old_crash_stacktrace, expected_state):
"""Use the symbolized builds to generate an updated stacktrace."""
# Initialize variables.
app_path = environment.get_value('APP_PATH')
app_path_debug = environment.get_value('APP_PATH_DEBUG')
long_test_timeout = environment.get_value('WARMUP_TIMEOUT')
retry_limit = environment.get_value('FAIL_RETRIES')
symbolized = False
debug_build_stacktrace = ''
release_build_stacktrace = old_crash_stacktrace
# Symbolize using the debug build first so that the debug build stacktrace
# comes after the more important release build stacktrace.
if app_path_debug:
for _ in range(retry_limit):
process_handler.terminate_stale_application_instances()
command = testcase_manager.get_command_line_for_application(
testcase_file_path,
app_path=app_path_debug,
needs_http=testcase.http_flag)
return_code, crash_time, output = (
process_handler.run_process(
command, timeout=long_test_timeout, gestures=testcase.gestures))
crash_result = CrashResult(return_code, crash_time, output)
if crash_result.is_crash():
state = crash_result.get_symbolized_data()
if crash_analyzer.ignore_stacktrace(state.crash_stacktrace):
continue
unsymbolized_crash_stacktrace = crash_result.get_stacktrace(
symbolized=False)
debug_build_stacktrace = utils.get_crash_stacktrace_output(
command,
state.crash_stacktrace,
unsymbolized_crash_stacktrace,
build_type='debug')
symbolized = True
break
# Symbolize using the release build.
if app_path:
for _ in range(retry_limit):
process_handler.terminate_stale_application_instances()
command = testcase_manager.get_command_line_for_application(
testcase_file_path, app_path=app_path, needs_http=testcase.http_flag)
return_code, crash_time, output = (
process_handler.run_process(
command, timeout=long_test_timeout, gestures=testcase.gestures))
crash_result = CrashResult(return_code, crash_time, output)
if crash_result.is_crash():
state = crash_result.get_symbolized_data()
if crash_analyzer.ignore_stacktrace(state.crash_stacktrace):
continue
if state.crash_state != expected_state:
continue
# Release stack's security flag has to match the symbolized release
# stack's security flag.
security_flag = crash_result.is_security_issue()
if security_flag != testcase.security_flag:
continue
unsymbolized_crash_stacktrace = crash_result.get_stacktrace(
symbolized=False)
release_build_stacktrace = utils.get_crash_stacktrace_output(
command,
state.crash_stacktrace,
unsymbolized_crash_stacktrace,
build_type='release')
symbolized = True
break
stacktrace = release_build_stacktrace
if debug_build_stacktrace:
stacktrace += '\n\n' + debug_build_stacktrace
return symbolized, stacktrace
class CrashResult:
"""Represents a crash result from a test run."""
def __init__(self, return_code, crash_time, output, unexpected_crash=False):
self.return_code = return_code
self.crash_time = crash_time
self.output = utils.decode_to_unicode(output) if output else 'No output!'
# For crashes against an expected state, this indicates whether if there
# was a crash that didn't match.
self.unexpected_crash = unexpected_crash
self._symbolized_crash_data = None
self._unsymbolized_crash_data = None
def get_crash_time(self):
"""Return the crash time."""
return self.crash_time
def get_symbolized_data(self) -> CrashInfo:
"""Compute symbolized crash data if necessary or return cached result."""
if self._symbolized_crash_data:
return self._symbolized_crash_data
self._symbolized_crash_data = stack_analyzer.get_crash_data(
self.output, symbolize_flag=True)
return self._symbolized_crash_data
def get_unsymbolized_data(self) -> CrashInfo:
"""Compute unsymbolized crash data if necessary or return cached result."""
if self._unsymbolized_crash_data:
return self._unsymbolized_crash_data
self._unsymbolized_crash_data = stack_analyzer.get_crash_data(
self.output, symbolize_flag=False)
return self._unsymbolized_crash_data
def get_state(self, symbolized=True):
"""Return the crash state."""
if symbolized:
state = self.get_symbolized_data()
else:
state = self.get_unsymbolized_data()
return state.crash_state
def get_stacktrace(self, symbolized=True):
"""Return the crash stacktrace."""
if symbolized:
state = self.get_symbolized_data()
else:
state = self.get_unsymbolized_data()
return state.crash_stacktrace
def get_type(self):
"""Return the crash type."""
# It does not matter whether we use symbolized or unsymbolized data.
state = self.get_unsymbolized_data()
return state.crash_type
def is_crash(self, ignore_state=False):
"""Return True if this result was a crash."""
crashed = crash_analyzer.is_crash(self.return_code, self.output)
if not crashed:
return False
state = self.get_state(symbolized=False)
if not state.strip() and not ignore_state:
return False
return True
def should_ignore(self):
"""Return True if this crash should be ignored."""
state = self.get_symbolized_data()
return crash_analyzer.ignore_stacktrace(state.crash_stacktrace)
def is_security_issue(self):
"""Return True if this crash is a security issue."""
state = self.get_unsymbolized_data()
return crash_analyzer.is_security_issue(
state.crash_stacktrace, state.crash_type, state.crash_address)
The provided code snippet includes necessary dependencies for implementing the `utask_main` function. Write a Python function `def utask_main(uworker_input)` to solve the following problem:
Execute the untrusted part of a symbolize command.
Here is the function:
def utask_main(uworker_input):
"""Execute the untrusted part of a symbolize command."""
job_type = uworker_input.job_type
testcase = uworker_io.entity_from_protobuf(uworker_input.testcase,
data_types.Testcase)
uworker_io.check_handling_testcase_safe(testcase)
job_type = uworker_input.job_type
setup_input = uworker_input.setup_input
_, testcase_file_path, error = setup.setup_testcase(testcase, job_type,
setup_input)
if error:
return error
# Initialize variables.
old_crash_stacktrace = (
uworker_input.symbolize_task_input.old_crash_stacktrace)
sym_crash_type = testcase.crash_type
sym_crash_address = testcase.crash_address
sym_crash_state = testcase.crash_state
sym_redzone = DEFAULT_REDZONE
warmup_timeout = environment.get_value('WARMUP_TIMEOUT')
# Decide which build revision to use.
if testcase.crash_stacktrace == 'Pending':
# This usually happen when someone clicked the 'Update stacktrace from
# trunk' button on the testcase details page. In this case, we are forced
# to use trunk. No revision -> trunk build.
build_revision = None
else:
build_revision = testcase.crash_revision
# Set up a custom or regular build based on revision.
build_manager.setup_build(build_revision)
# Get crash revision used in setting up build.
crash_revision = environment.get_value('APP_REVISION')
if not build_manager.check_app_path():
return uworker_msg_pb2.Output(
error_message='Build setup failed',
error_type=uworker_msg_pb2.ErrorType.SYMBOLIZE_BUILD_SETUP_ERROR)
# ASAN tool settings (if the tool is used).
# See if we can get better stacks with higher redzone sizes.
# A UAF might actually turn out to be OOB read/write with a bigger redzone.
if environment.tool_matches('ASAN', job_type) and testcase.security_flag:
redzone = MAX_REDZONE
while redzone >= MIN_REDZONE:
environment.reset_current_memory_tool_options(
redzone_size=testcase.redzone, disable_ubsan=testcase.disable_ubsan)
process_handler.terminate_stale_application_instances()
command = testcase_manager.get_command_line_for_application(
testcase_file_path, needs_http=testcase.http_flag)
return_code, crash_time, output = (
process_handler.run_process(
command, timeout=warmup_timeout, gestures=testcase.gestures))
crash_result = CrashResult(return_code, crash_time, output)
if crash_result.is_crash() and 'AddressSanitizer' in output:
state = crash_result.get_symbolized_data()
security_flag = crash_result.is_security_issue()
if (not crash_analyzer.ignore_stacktrace(state.crash_stacktrace) and
security_flag == testcase.security_flag and
state.crash_type == testcase.crash_type and
(state.crash_type != sym_crash_type or
state.crash_state != sym_crash_state)):
logs.log('Changing crash parameters.\nOld : %s, %s, %s' %
(sym_crash_type, sym_crash_address, sym_crash_state))
sym_crash_type = state.crash_type
sym_crash_address = state.crash_address
sym_crash_state = state.crash_state
sym_redzone = redzone
old_crash_stacktrace = state.crash_stacktrace
logs.log('\nNew : %s, %s, %s' % (sym_crash_type, sym_crash_address,
sym_crash_state))
break
redzone /= 2
# We should have atleast a symbolized debug or a release build.
symbolized_builds = build_manager.setup_symbolized_builds(crash_revision)
if (not symbolized_builds or
(not build_manager.check_app_path() and
not build_manager.check_app_path('APP_PATH_DEBUG'))):
return uworker_msg_pb2.Output(
error_message='Build setup failed',
error_type=uworker_msg_pb2.ErrorType.SYMBOLIZE_BUILD_SETUP_ERROR)
# Increase malloc_context_size to get all stack frames. Default is 30.
environment.reset_current_memory_tool_options(
redzone_size=sym_redzone,
malloc_context_size=STACK_FRAME_COUNT,
symbolize_inline_frames=True,
disable_ubsan=testcase.disable_ubsan)
# TSAN tool settings (if the tool is used).
if environment.tool_matches('TSAN', job_type):
environment.set_tsan_max_history_size()
# Do the symbolization if supported by this application.
result, sym_crash_stacktrace = (
get_symbolized_stacktraces(testcase_file_path, testcase,
old_crash_stacktrace, sym_crash_state))
symbolize_task_output = uworker_msg_pb2.SymbolizeTaskOutput(
crash_type=sym_crash_type,
crash_address=sym_crash_address,
crash_state=sym_crash_state,
crash_stacktrace=(data_handler.filter_stacktrace(sym_crash_stacktrace)),
symbolized=result,
crash_revision=int(crash_revision))
if result:
build_url = environment.get_value('BUILD_URL')
if build_url:
symbolize_task_output.build_url = str(build_url)
# Switch current directory before builds cleanup.
root_directory = environment.get_value('ROOT_DIR')
os.chdir(root_directory)
# Cleanup symbolized builds which are space-heavy.
symbolized_builds.delete()
return uworker_msg_pb2.Output(symbolize_task_output=symbolize_task_output) | Execute the untrusted part of a symbolize command. |
157,242 | import os
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.crash_result import CrashResult
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
_ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({
uworker_msg_pb2.ErrorType.SYMBOLIZE_BUILD_SETUP_ERROR:
handle_build_setup_error,
}).compose_with(
setup.ERROR_HANDLER,
uworker_handle_errors.UNHANDLED_ERROR_HANDLER,
)
The provided code snippet includes necessary dependencies for implementing the `utask_postprocess` function. Write a Python function `def utask_postprocess(output)` to solve the following problem:
Handle the output from utask_main.
Here is the function:
def utask_postprocess(output):
"""Handle the output from utask_main."""
if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR:
_ERROR_HANDLER.handle(output)
return
symbolize_task_output = output.symbolize_task_output
# Update crash parameters.
testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id)
testcase.crash_type = symbolize_task_output.crash_type
testcase.crash_address = symbolize_task_output.crash_address
testcase.crash_state = symbolize_task_output.crash_state
testcase.crash_stacktrace = symbolize_task_output.crash_stacktrace
if not symbolize_task_output.symbolized:
data_handler.update_testcase_comment(
testcase, data_types.TaskState.ERROR,
'Unable to reproduce crash, skipping '
'stacktrace update')
else:
# Switch build url to use the less-optimized symbolized build with better
# stacktrace.
if symbolize_task_output.build_url:
testcase.set_metadata(
'build_url', symbolize_task_output.build_url, update_testcase=False)
data_handler.update_testcase_comment(testcase,
data_types.TaskState.FINISHED)
testcase.symbolized = True
testcase.crash_revision = symbolize_task_output.crash_revision
testcase.put()
# We might have updated the crash state. See if we need to marked as duplicate
# based on other testcases.
data_handler.handle_duplicate_entry(testcase)
task_creation.create_blame_task_if_needed(testcase) | Handle the output from utask_main. |
157,243 | import collections
import datetime
import os
import random
import shutil
from typing import List
from google.cloud import ndb
from google.protobuf import timestamp_pb2
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_symbolizer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import fuzz_target_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `_get_corpus_file_paths` function. Write a Python function `def _get_corpus_file_paths(corpus_path)` to solve the following problem:
Return full paths to corpus files in |corpus_path|.
Here is the function:
def _get_corpus_file_paths(corpus_path):
"""Return full paths to corpus files in |corpus_path|."""
return [
os.path.join(corpus_path, filename)
for filename in os.listdir(corpus_path)
] | Return full paths to corpus files in |corpus_path|. |
157,244 | import collections
import datetime
import os
import random
import shutil
from typing import List
from google.cloud import ndb
from google.protobuf import timestamp_pb2
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_symbolizer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import fuzz_target_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
class Context:
"""Pruning state."""
def __init__(self, uworker_input, fuzz_target, cross_pollinate_fuzzers):
self.fuzz_target = fuzz_target
self.cross_pollinate_fuzzers = cross_pollinate_fuzzers
self.merge_tmp_dir = None
self.engine = engine.get(self.fuzz_target.engine)
if not self.engine:
raise CorpusPruningError('Engine {} not found'.format(engine))
self._created_directories = []
# Set up temporary directories where corpora will be synced to.
# Initial synced corpus.
self.initial_corpus_path = self._create_temp_corpus_directory(
'%s_initial_corpus' % self.fuzz_target.project_qualified_name())
# Minimized corpus.
self.minimized_corpus_path = self._create_temp_corpus_directory(
'%s_minimized_corpus' % self.fuzz_target.project_qualified_name())
# Synced quarantine corpus.
self.quarantine_corpus_path = self._create_temp_corpus_directory(
'%s_quarantine' % self.fuzz_target.project_qualified_name())
# Synced shared corpus.
self.shared_corpus_path = self._create_temp_corpus_directory(
'%s_shared' % self.fuzz_target.project_qualified_name())
# Bad units.
self.bad_units_path = self._create_temp_corpus_directory(
'%s_bad_units' % self.fuzz_target.project_qualified_name())
self.merge_tmp_dir = self._create_temp_corpus_directory('merge_workdir')
if uworker_input is not None:
self.corpus = corpus_manager.ProtoFuzzTargetCorpus(
self.fuzz_target.engine, self.fuzz_target.project_qualified_name(),
uworker_input.corpus_pruning_task_input.corpus)
self.quarantine_corpus = corpus_manager.ProtoFuzzTargetCorpus(
self.fuzz_target.engine, self.fuzz_target.project_qualified_name(),
uworker_input.corpus_pruning_task_input.quarantine_corpus)
else:
# Delete this branch after we get rid of untrusted runnner.
self.corpus = corpus_manager.FuzzTargetCorpus(
self.fuzz_target.engine,
self.fuzz_target.project_qualified_name(),
include_regressions=True)
self.quarantine_corpus = corpus_manager.FuzzTargetCorpus(
self.fuzz_target.engine,
self.fuzz_target.project_qualified_name(),
quarantine=True)
def restore_quarantined_units(self):
"""Restore units from the quarantine."""
logs.log('Restoring units from quarantine.')
# Limit the number of quarantine units to restore, in case there are a lot.
quarantine_unit_paths = _get_corpus_file_paths(self.quarantine_corpus_path)
if len(quarantine_unit_paths) > MAX_QUARANTINE_UNITS_TO_RESTORE:
quarantine_unit_paths = random.sample(quarantine_unit_paths,
MAX_QUARANTINE_UNITS_TO_RESTORE)
for unit_path in quarantine_unit_paths:
unit_filename = os.path.basename(unit_path)
shutil.move(unit_path,
os.path.join(self.initial_corpus_path, unit_filename))
def _create_temp_corpus_directory(self, name):
"""Create temporary corpus directory. Returns path to the created
directory."""
testcases_directory = environment.get_value('FUZZ_INPUTS_DISK')
directory_path = os.path.join(testcases_directory, name)
shell.create_directory(directory_path)
self._created_directories.append(directory_path)
return directory_path
def sync_to_disk(self):
"""Sync required corpora to disk."""
if not self.corpus.rsync_to_disk(self.initial_corpus_path):
raise CorpusPruningError('Failed to sync corpus to disk.')
if not self.quarantine_corpus.rsync_to_disk(self.initial_corpus_path):
logs.log_error(
'Failed to sync quarantine corpus to disk.',
fuzz_target=self.fuzz_target)
self._cross_pollinate_other_fuzzer_corpuses()
def sync_to_gcs(self):
"""Sync corpora to GCS post merge."""
if not self.corpus.rsync_from_disk(self.minimized_corpus_path):
raise CorpusPruningError('Failed to sync minimized corpus to gcs.')
def cleanup(self):
"""Cleanup state."""
for path in self._created_directories:
shell.remove_directory(path)
def _cross_pollinate_other_fuzzer_corpuses(self):
"""Add other fuzzer corpuses to shared corpus path for cross-pollination."""
corpus_backup_date = utils.utcnow().date() - datetime.timedelta(
days=data_types.CORPUS_BACKUP_PUBLIC_LOOKBACK_DAYS)
for cross_pollinate_fuzzer in self.cross_pollinate_fuzzers:
project_qualified_name = (
cross_pollinate_fuzzer.fuzz_target.project_qualified_name())
backup_bucket_name = cross_pollinate_fuzzer.backup_bucket_name
corpus_engine_name = cross_pollinate_fuzzer.corpus_engine_name
corpus_backup_url = corpus_manager.gcs_url_for_backup_file(
backup_bucket_name, corpus_engine_name, project_qualified_name,
corpus_backup_date)
corpus_backup_local_filename = '%s-%s' % (
project_qualified_name, os.path.basename(corpus_backup_url))
corpus_backup_local_path = os.path.join(self.shared_corpus_path,
corpus_backup_local_filename)
if not storage.exists(corpus_backup_url, ignore_errors=True):
# This can happen in cases when a new fuzz target is checked in or if
# missed to capture a backup for a particular day (for OSS-Fuzz, this
# will result in a 403 instead of 404 since that GCS path belongs to
# other project). So, just log a warning for debugging purposes only.
logs.log_warn(
'Corpus backup does not exist, ignoring: %s.' % corpus_backup_url)
continue
if not storage.copy_file_from(corpus_backup_url,
corpus_backup_local_path):
continue
corpus_backup_output_directory = os.path.join(self.shared_corpus_path,
project_qualified_name)
shell.create_directory(corpus_backup_output_directory)
with archive.open(corpus_backup_local_path) as reader:
result = reader.extract_all(corpus_backup_output_directory)
shell.remove_file(corpus_backup_local_path)
if result:
logs.log(
'Corpus backup url %s successfully unpacked into shared corpus.' %
corpus_backup_url)
else:
logs.log_error(
'Failed to unpack corpus backup from url %s.' % corpus_backup_url)
def _fill_cross_pollination_stats(stats, output):
"""Fills the cross pollination statistics in the corpus pruning output."""
if not stats:
return
statistics = uworker_msg_pb2.CrossPollinationStatistics(
project_qualified_name=stats.project_qualified_name,
sources=stats.sources,
initial_corpus_size=stats.initial_corpus_size,
corpus_size=stats.corpus_size,
initial_edge_coverage=stats.initial_edge_coverage,
edge_coverage=stats.edge_coverage,
initial_feature_coverage=stats.initial_feature_coverage,
feature_coverage=stats.feature_coverage)
output.corpus_pruning_task_output.cross_pollination_stats.CopyFrom(statistics)
def do_corpus_pruning(context, revision):
"""Run corpus pruning."""
# Set |FUZZ_TARGET| environment variable to help with unarchiving only fuzz
# target and its related files.
environment.set_value('FUZZ_TARGET', context.fuzz_target.binary)
if environment.is_trusted_host():
from clusterfuzz._internal.bot.untrusted_runner import tasks_host
return tasks_host.do_corpus_pruning(context, revision)
if not build_manager.setup_build(revision=revision):
raise CorpusPruningError('Failed to setup build.')
build_directory = environment.get_value('BUILD_DIR')
start_time = datetime.datetime.utcnow()
runner = Runner(build_directory, context)
pruner = CorpusPruner(runner)
fuzzer_binary_name = os.path.basename(runner.target_path)
# Get initial corpus to process from GCS.
context.sync_to_disk()
initial_corpus_size = shell.get_directory_file_count(
context.initial_corpus_path)
# Restore a small batch of quarantined units back to corpus.
context.restore_quarantined_units()
# Shrink to a minimized corpus using corpus merge.
pruner_stats = pruner.run(context.initial_corpus_path,
context.minimized_corpus_path,
context.bad_units_path)
# Sync minimized corpus back to GCS.
context.sync_to_gcs()
logs.log('Saved minimize corpus.')
# Create corpus backup.
# Temporarily copy the past crash regressions folder into the minimized corpus
# so that corpus backup archive can have both.
regressions_input_dir = os.path.join(context.initial_corpus_path,
'regressions')
regressions_output_dir = os.path.join(context.minimized_corpus_path,
'regressions')
if shell.get_directory_file_count(regressions_input_dir):
shutil.copytree(regressions_input_dir, regressions_output_dir)
backup_bucket = environment.get_value('BACKUP_BUCKET')
corpus_backup_url = corpus_manager.backup_corpus(
backup_bucket, context.corpus, context.minimized_corpus_path)
shell.remove_directory(regressions_output_dir)
minimized_corpus_size_units = shell.get_directory_file_count(
context.minimized_corpus_path)
minimized_corpus_size_bytes = shell.get_directory_size(
context.minimized_corpus_path)
logs.log('Corpus pruned from %d to %d units.' % (initial_corpus_size,
minimized_corpus_size_units))
# Process bad units found during merge.
# Mapping of crash state -> CorpusCrash
crashes = {}
pruner.process_bad_units(context.bad_units_path,
context.quarantine_corpus_path, crashes)
context.quarantine_corpus.rsync_from_disk(context.quarantine_corpus_path)
# Store corpus stats into CoverageInformation entity.
project_qualified_name = context.fuzz_target.project_qualified_name()
today = datetime.datetime.utcnow()
coverage_info = data_types.CoverageInformation(
fuzzer=project_qualified_name, date=today)
quarantine_corpus_size = shell.get_directory_file_count(
context.quarantine_corpus_path)
quarantine_corpus_dir_size = shell.get_directory_size(
context.quarantine_corpus_path)
# Save the minimize corpus size before cross pollination to put in BigQuery.
pre_pollination_corpus_size = minimized_corpus_size_units
# Populate coverage stats.
coverage_info.corpus_size_units = minimized_corpus_size_units
coverage_info.corpus_size_bytes = minimized_corpus_size_bytes
coverage_info.quarantine_size_units = quarantine_corpus_size
coverage_info.quarantine_size_bytes = quarantine_corpus_dir_size
coverage_info.corpus_backup_location = corpus_backup_url
coverage_info.corpus_location = context.corpus.get_gcs_url()
coverage_info.quarantine_location = context.quarantine_corpus.get_gcs_url()
# Calculate remaining time to use for shared corpus merging.
time_remaining = _get_time_remaining(start_time)
if time_remaining <= 0:
logs.log_warn('Not enough time for shared corpus merging.')
return None
cross_pollinator = CrossPollinator(runner)
pollinator_stats = cross_pollinator.run(time_remaining)
context.sync_to_gcs()
# Update corpus size stats.
minimized_corpus_size_units = shell.get_directory_file_count(
context.minimized_corpus_path)
minimized_corpus_size_bytes = shell.get_directory_size(
context.minimized_corpus_path)
coverage_info.corpus_size_units = minimized_corpus_size_units
coverage_info.corpus_size_bytes = minimized_corpus_size_bytes
logs.log('Finished.')
sources = ','.join([
fuzzer.fuzz_target.project_qualified_name()
for fuzzer in context.cross_pollinate_fuzzers
])
cross_pollination_stats = None
if pruner_stats and pollinator_stats:
cross_pollination_stats = CrossPollinationStats(
project_qualified_name, sources, initial_corpus_size,
pre_pollination_corpus_size, pruner_stats['edge_coverage'],
pollinator_stats['edge_coverage'], pruner_stats['feature_coverage'],
pollinator_stats['feature_coverage'])
return CorpusPruningResult(
coverage_info=coverage_info,
crashes=list(crashes.values()),
fuzzer_binary_name=fuzzer_binary_name,
revision=environment.get_value('APP_REVISION'),
cross_pollination_stats=cross_pollination_stats)
def _process_corpus_crashes(context, result):
"""Process crashes found in the corpus."""
# Default Testcase entity values.
crash_revision = result.revision
job_type = environment.get_value('JOB_NAME')
minimized_arguments = '%TESTCASE% ' + context.fuzz_target.binary
project_name = data_handler.get_project_name(job_type)
comment = 'Fuzzer %s generated corpus testcase crashed (r%s)' % (
context.fuzz_target.project_qualified_name(), crash_revision)
# Generate crash reports.
for crash in result.crashes:
existing_testcase = data_handler.find_testcase(
project_name,
crash.crash_type,
crash.crash_state,
crash.security_flag,
fuzz_target=context.fuzz_target.project_qualified_name())
if existing_testcase:
continue
# Upload/store testcase.
if environment.is_trusted_host():
from clusterfuzz._internal.bot.untrusted_runner import file_host
unit_path = os.path.join(context.bad_units_path,
os.path.basename(crash.unit_path))
# Prevent the worker from escaping out of |context.bad_units_path|.
if not file_host.is_directory_parent(unit_path, context.bad_units_path):
raise CorpusPruningError('Invalid units path from worker.')
file_host.copy_file_from_worker(crash.unit_path, unit_path)
else:
unit_path = crash.unit_path
with open(unit_path, 'rb') as f:
key = blobs.write_blob(f)
# Set the absolute_path property of the Testcase to a file in FUZZ_INPUTS
# instead of the local quarantine directory.
absolute_testcase_path = os.path.join(
environment.get_value('FUZZ_INPUTS'), 'testcase')
# TODO(https://b.corp.google.com/issues/328691756): Set trusted based on the
# job when we start doing untrusted fuzzing.
testcase_id = data_handler.store_testcase(
crash=crash,
fuzzed_keys=key,
minimized_keys='',
regression='',
fixed='',
one_time_crasher_flag=False,
crash_revision=crash_revision,
comment=comment,
absolute_path=absolute_testcase_path,
fuzzer_name=context.fuzz_target.engine,
fully_qualified_fuzzer_name=context.fuzz_target.fully_qualified_name(),
job_type=job_type,
archived=False,
archive_filename='',
http_flag=False,
gestures=None,
redzone=DEFAULT_REDZONE,
disable_ubsan=False,
window_argument=None,
timeout_multiplier=1.0,
minimized_arguments=minimized_arguments,
trusted=True)
# Set fuzzer_binary_name in testcase metadata.
testcase = data_handler.get_testcase_by_id(testcase_id)
testcase.set_metadata('fuzzer_binary_name', result.fuzzer_binary_name)
# TODO(alhijazi): This should be added to Output.
issue_metadata = engine_common.get_fuzz_target_issue_metadata(
context.fuzz_target)
if issue_metadata:
for key, value in issue_metadata.items():
testcase.set_metadata(key, value, update_testcase=False)
testcase.put()
# Create additional tasks for testcase (starting with minimization).
testcase = data_handler.get_testcase_by_id(testcase_id)
task_creation.create_tasks(testcase)
def _get_cross_pollinate_fuzzers_from_protos(cross_pollinate_fuzzers_protos):
return [
CrossPollinateFuzzer(
uworker_io.entity_from_protobuf(proto.fuzz_target,
data_types.FuzzTarget),
proto.backup_bucket_name,
proto.corpus_engine_name,
) for proto in cross_pollinate_fuzzers_protos
]
def _extract_coverage_information(context, result):
"""Extracts and stores the coverage information in a proto."""
coverage_info = uworker_msg_pb2.CoverageInformation()
coverage_info.project_name = context.fuzz_target.project_qualified_name()
timestamp = timestamp_pb2.Timestamp() # pylint: disable=no-member
timestamp.FromDatetime(result.coverage_info.date)
coverage_info.timestamp.CopyFrom(timestamp)
# Intentionally skip edge and function coverage values as those would come
# from fuzzer coverage cron task.
coverage_info.corpus_size_units = result.coverage_info.corpus_size_units
coverage_info.corpus_size_bytes = result.coverage_info.corpus_size_bytes
coverage_info.corpus_location = result.coverage_info.corpus_location
coverage_info.corpus_backup_location = (
result.coverage_info.corpus_backup_location)
coverage_info.quarantine_size_units = (
result.coverage_info.quarantine_size_units)
coverage_info.quarantine_size_bytes = (
result.coverage_info.quarantine_size_bytes)
coverage_info.quarantine_location = result.coverage_info.quarantine_location
return coverage_info
The provided code snippet includes necessary dependencies for implementing the `utask_main` function. Write a Python function `def utask_main(uworker_input)` to solve the following problem:
Execute corpus pruning task.
Here is the function:
def utask_main(uworker_input):
"""Execute corpus pruning task."""
fuzz_target = uworker_io.entity_from_protobuf(
uworker_input.corpus_pruning_task_input.fuzz_target,
data_types.FuzzTarget)
revision = 0 # Trunk revision
if not setup.update_fuzzer_and_data_bundles(uworker_input.setup_input):
error_message = f'Failed to set up fuzzer {fuzz_target.engine}.'
logs.log_error(error_message)
return uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.ErrorType.CORPUS_PRUNING_FUZZER_SETUP_FAILED)
cross_pollinate_fuzzers = _get_cross_pollinate_fuzzers_from_protos(
uworker_input.corpus_pruning_task_input.cross_pollinate_fuzzers)
context = Context(uworker_input, fuzz_target, cross_pollinate_fuzzers)
if uworker_input.global_blacklisted_functions:
leak_blacklist.copy_global_to_local_blacklist(
uworker_input.corpus_task_input.global_blacklisted_functions)
uworker_output = None
try:
result = do_corpus_pruning(context, revision)
uworker_output = uworker_msg_pb2.Output(
corpus_pruning_task_output=uworker_msg_pb2.CorpusPruningTaskOutput(
coverage_info=_extract_coverage_information(context, result)))
_fill_cross_pollination_stats(result.cross_pollination_stats,
uworker_output)
_process_corpus_crashes(context, result)
except Exception as e:
# TODO(metzman): Don't catch every exception, it makes testing almost
# impossible.
logs.log_error(f'Corpus pruning failed: {e}')
uworker_output = uworker_msg_pb2.Output(
error_type=uworker_msg_pb2.CORPUS_PRUNING_ERROR)
finally:
context.cleanup()
return uworker_output | Execute corpus pruning task. |
157,245 | import collections
import datetime
import os
import random
import shutil
from typing import List
from google.cloud import ndb
from google.protobuf import timestamp_pb2
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_symbolizer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import fuzz_target_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def handle_corpus_pruning_failures(output: uworker_msg_pb2.Output):
task_name = (f'corpus_pruning_{output.uworker_input.fuzzer_name}_'
f'{output.uworker_input.job_type}')
data_handler.update_task_status(task_name, data_types.TaskState.ERROR) | null |
157,246 | import collections
import datetime
import os
import random
import shutil
from typing import List
from google.cloud import ndb
from google.protobuf import timestamp_pb2
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_symbolizer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import fuzz_target_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _limit_corpus_size(corpus_url):
"""Limit number of files and size of a corpus."""
corpus_count = 0
corpus_size = 0
deleted_corpus_count = 0
bucket, _ = storage.get_bucket_name_and_path(corpus_url)
for corpus_file in storage.get_blobs(corpus_url):
corpus_count += 1
corpus_size += corpus_file['size']
if (corpus_count > CORPUS_FILES_LIMIT_FOR_FAILURES or
corpus_size > CORPUS_SIZE_LIMIT_FOR_FAILURES):
path_to_delete = storage.get_cloud_storage_file_path(
bucket, corpus_file['name'])
storage.delete(path_to_delete)
deleted_corpus_count += 1
if deleted_corpus_count:
logs.log('Removed %d files from oversized corpus: %s.' %
(deleted_corpus_count, corpus_url))
def _get_cross_pollinate_fuzzers(
engine_name: str, current_fuzzer_name: str
) -> List[uworker_msg_pb2.CrossPollinateFuzzerProto]:
"""Return a list of fuzzer objects to use for cross pollination."""
cross_pollinate_fuzzers = []
selected_targets_and_jobs = _select_targets_and_jobs_for_pollination(
engine_name, current_fuzzer_name)
default_backup_bucket = utils.default_backup_bucket()
for target, target_job in selected_targets_and_jobs:
job = data_types.Job.query(data_types.Job.name == target_job.job).get()
if not job:
continue
job_environment = job.get_environment()
backup_bucket_name = job_environment.get('BACKUP_BUCKET',
default_backup_bucket)
if not backup_bucket_name:
continue
corpus_engine_name = job_environment.get('CORPUS_FUZZER_NAME_OVERRIDE',
engine_name)
cross_pollinate_fuzzers.append(
uworker_msg_pb2.CrossPollinateFuzzerProto(
fuzz_target=uworker_io.entity_to_protobuf(target),
backup_bucket_name=backup_bucket_name,
corpus_engine_name=corpus_engine_name,
))
return cross_pollinate_fuzzers
The provided code snippet includes necessary dependencies for implementing the `utask_preprocess` function. Write a Python function `def utask_preprocess(fuzzer_name, job_type, uworker_env)` to solve the following problem:
Runs preprocessing for corpus pruning task.
Here is the function:
def utask_preprocess(fuzzer_name, job_type, uworker_env):
"""Runs preprocessing for corpus pruning task."""
fuzz_target = data_handler.get_fuzz_target(fuzzer_name)
task_name = f'corpus_pruning_{fuzzer_name}_{job_type}'
# Get status of last execution.
last_execution_metadata = data_handler.get_task_status(task_name)
last_execution_failed = bool(
last_execution_metadata and
last_execution_metadata.status == data_types.TaskState.ERROR)
# Make sure we're the only instance running for the given fuzzer and
# job_type.
if not data_handler.update_task_status(task_name,
data_types.TaskState.STARTED):
logs.log('A previous corpus pruning task is still running, exiting.')
return None
setup_input = (
setup.preprocess_update_fuzzer_and_data_bundles(fuzz_target.engine))
# TODO(unassigned): Use coverage information for better selection here.
cross_pollinate_fuzzers = _get_cross_pollinate_fuzzers(
fuzz_target.engine, fuzzer_name)
# If our last execution failed, shrink to a randomized corpus of usable size
# to prevent corpus from growing unbounded and recurring failures when trying
# to minimize it.
if last_execution_failed:
# TODO(metzman): Is this too expensive to do in preprocess?
corpus_urls = corpus_manager.get_pruning_corpora_urls(
fuzz_target.engine, fuzz_target.project_qualified_name())
for corpus_url in corpus_urls:
_limit_corpus_size(corpus_url)
corpus, quarantine_corpus = corpus_manager.get_corpuses_for_pruning(
fuzz_target.engine, fuzz_target.project_qualified_name())
corpus_pruning_task_input = uworker_msg_pb2.CorpusPruningTaskInput(
fuzz_target=uworker_io.entity_to_protobuf(fuzz_target),
last_execution_failed=last_execution_failed,
cross_pollinate_fuzzers=cross_pollinate_fuzzers,
corpus=corpus.proto_corpus,
quarantine_corpus=quarantine_corpus.proto_corpus)
if environment.get_value('LSAN'):
# Copy global blacklist into local suppressions file if LSan is enabled.
setup_input.global_blacklisted_functions.extend(
leak_blacklist.get_global_blacklisted_functions())
return uworker_msg_pb2.Input(
job_type=job_type,
fuzzer_name=fuzzer_name,
uworker_env=uworker_env,
setup_input=setup_input,
corpus_pruning_task_input=corpus_pruning_task_input) | Runs preprocessing for corpus pruning task. |
157,247 | import collections
import datetime
import os
import random
import shutil
from typing import List
from google.cloud import ndb
from google.protobuf import timestamp_pb2
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.tasks import setup
from clusterfuzz._internal.bot.tasks import task_creation
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.crash_analysis import crash_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_analyzer
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_symbolizer
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import fuzz_target_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import big_query
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
def _record_cross_pollination_stats(output):
"""Log stats about cross pollination in BigQuery."""
# If no stats were gathered due to a timeout or lack of corpus, return.
if not output.corpus_pruning_task_output.HasField('cross_pollination_stats'):
return
stats = output.corpus_pruning_task_output.cross_pollination_stats
bigquery_row = {
'project_qualified_name': stats.project_qualified_name,
'sources': stats.sources,
'initial_corpus_size': stats.initial_corpus_size,
'corpus_size': stats.corpus_size,
'initial_edge_coverage': stats.initial_edge_coverage,
'edge_coverage': stats.edge_coverage,
'initial_feature_coverage': stats.initial_feature_coverage,
'feature_coverage': stats.feature_coverage
}
# BigQuery not available in local development. This is necessary because the
# untrusted runner is in a separate process and can't be easily mocked.
# Check here instead of earlier to test as much of the function as we can.
if environment.get_value('LOCAL_DEVELOPMENT') or environment.get_value(
'PY_UNITTESTS'):
return
client = big_query.Client(
dataset_id='main', table_id='cross_pollination_statistics')
client.insert([big_query.Insert(row=bigquery_row, insert_id=None)])
def _save_coverage_information(output):
"""Saves coverage information in datastore using an atomic transaction."""
if not output.corpus_pruning_task_output.HasField('coverage_info'):
return
cov_info = output.corpus_pruning_task_output.coverage_info
# Use ndb.transaction with retries below to mitigate risk of a race condition.
def _try_save_coverage_information():
"""Implements save_coverage_information function."""
coverage_info = data_handler.get_coverage_information(
cov_info.project_name,
cov_info.timestamp.ToDatetime().date(),
create_if_needed=True)
# Intentionally skip edge and function coverage values as those would come
# from fuzzer coverage cron task (see src/go/server/cron/coverage.go).
coverage_info.corpus_size_units = cov_info.corpus_size_units
coverage_info.corpus_size_bytes = cov_info.corpus_size_bytes
coverage_info.corpus_location = cov_info.corpus_location
coverage_info.corpus_backup_location = cov_info.corpus_backup_location
coverage_info.quarantine_size_units = cov_info.quarantine_size_units
coverage_info.quarantine_size_bytes = cov_info.quarantine_size_bytes
coverage_info.quarantine_location = cov_info.quarantine_location
coverage_info.put()
try:
ndb.transaction(
_try_save_coverage_information,
retries=data_handler.DEFAULT_FAIL_RETRIES)
except Exception as e:
# TODO(metzman): Don't catch every exception, it makes testing almost
# impossible.
raise CorpusPruningError(
'Failed to save corpus pruning result: %s.' % repr(e))
_ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({
uworker_msg_pb2.ErrorType.CORPUS_PRUNING_FUZZER_SETUP_FAILED:
uworker_handle_errors.noop_handler,
uworker_msg_pb2.ErrorType.CORPUS_PRUNING_ERROR:
handle_corpus_pruning_failures,
})
The provided code snippet includes necessary dependencies for implementing the `utask_postprocess` function. Write a Python function `def utask_postprocess(output)` to solve the following problem:
Trusted: Handles errors and writes anything needed to the db.
Here is the function:
def utask_postprocess(output):
"""Trusted: Handles errors and writes anything needed to the db."""
if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR:
_ERROR_HANDLER.handle(output)
return
task_name = (f'corpus_pruning_{output.uworker_input.fuzzer_name}_'
f'{output.uworker_input.job_type}')
_record_cross_pollination_stats(output)
_save_coverage_information(output)
data_handler.update_task_status(task_name, data_types.TaskState.FINISHED) | Trusted: Handles errors and writes anything needed to the db. |
157,248 | import datetime
import os
import shlex
import time
from typing import Optional
import zipfile
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import task_utils
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `handle_setup_testcase_error` function. Write a Python function `def handle_setup_testcase_error(uworker_output: uworker_msg_pb2.Output)` to solve the following problem:
Error handler for setup_testcase that is called by uworker_postprocess.
Here is the function:
def handle_setup_testcase_error(uworker_output: uworker_msg_pb2.Output):
"""Error handler for setup_testcase that is called by uworker_postprocess."""
# Get the testcase again because it is too hard to set the testcase for
# partially migrated tasks.
# TODO(metzman): Experiment with making this unnecessary.
# First update comment.
testcase = data_handler.get_testcase_by_id(
uworker_output.uworker_input.testcase_id)
data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR,
uworker_output.error_message)
# Then reschedule the task.
command = task_utils.get_command_from_module(
uworker_output.uworker_input.module_name)
testcase_fail_wait = environment.get_value('FAIL_WAIT')
tasks.add_task(
command,
uworker_output.uworker_input.testcase_id,
uworker_output.uworker_input.job_type,
wait_time=testcase_fail_wait) | Error handler for setup_testcase that is called by uworker_postprocess. |
157,249 | import datetime
import os
import shlex
import time
from typing import Optional
import zipfile
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import task_utils
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `_get_data_bundle_update_lock_name` function. Write a Python function `def _get_data_bundle_update_lock_name(data_bundle_name)` to solve the following problem:
Return the lock key name for the given data bundle.
Here is the function:
def _get_data_bundle_update_lock_name(data_bundle_name):
"""Return the lock key name for the given data bundle."""
return f'update:data_bundle:{data_bundle_name}' | Return the lock key name for the given data bundle. |
157,250 | import datetime
import os
import shlex
import time
from typing import Optional
import zipfile
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import task_utils
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
def get_data_bundle_directory(fuzzer, data_bundle):
"""Return data bundle data directory."""
# Store corpora for built-in fuzzers like libFuzzer in the same directory
# as other local data bundles. This makes it easy to clear them when we run
# out of disk space.
local_data_bundles_directory = environment.get_value('DATA_BUNDLES_DIR')
if fuzzer.builtin:
return local_data_bundles_directory
if not data_bundle:
# Generic data bundle directory. Available to all fuzzers if they don't
# have their own data bundle.
return environment.get_value('FUZZ_DATA')
local_data_bundle_directory = os.path.join(local_data_bundles_directory,
data_bundle.name)
return local_data_bundle_directory
The provided code snippet includes necessary dependencies for implementing the `trusted_get_data_bundle_directory` function. Write a Python function `def trusted_get_data_bundle_directory(fuzzer)` to solve the following problem:
For fuzz_task which doesn't get data bundles in an untrusted manner.
Here is the function:
def trusted_get_data_bundle_directory(fuzzer):
"""For fuzz_task which doesn't get data bundles in an untrusted manner."""
# TODO(metzman): Delete this when fuzz_task is migrated.
# Check if we have a fuzzer-specific data bundle. Use it to calculate the
# data directory we will fetch our testcases from.
data_bundle = data_types.DataBundle.query(
data_types.DataBundle.name == fuzzer.data_bundle_name).get()
return get_data_bundle_directory(fuzzer, data_bundle) | For fuzz_task which doesn't get data bundles in an untrusted manner. |
157,251 | import datetime
import os
import shlex
import time
from typing import Optional
import zipfile
from clusterfuzz._internal.base import dates
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import task_utils
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.tasks.utasks import uworker_handle_errors
from clusterfuzz._internal.bot.tasks.utasks import uworker_io
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.datastore import ndb_utils
from clusterfuzz._internal.fuzzing import corpus_manager
from clusterfuzz._internal.fuzzing import leak_blacklist
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import fuzzer_logs
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.protos import uworker_msg_pb2
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
_TESTCASE_ARCHIVE_EXTENSION = '.zip'
The provided code snippet includes necessary dependencies for implementing the `archive_testcase_and_dependencies_in_gcs` function. Write a Python function `def archive_testcase_and_dependencies_in_gcs(resource_list, testcase_path)` to solve the following problem:
Archive testcase and its dependencies, and store in blobstore.
Here is the function:
def archive_testcase_and_dependencies_in_gcs(resource_list, testcase_path):
"""Archive testcase and its dependencies, and store in blobstore."""
if not os.path.exists(testcase_path):
logs.log_error('Unable to find testcase %s.' % testcase_path)
return None, None, None, None
absolute_filename = testcase_path
archived = False
zip_filename = None
zip_path = None
if not resource_list:
resource_list = []
# Add resource dependencies based on testcase path. These include
# stuff like extensions directory, dependency files, etc.
resource_list.extend(
testcase_manager.get_resource_dependencies(testcase_path))
# Filter out duplicates, directories, and files that do not exist.
resource_list = utils.filter_file_list(resource_list)
logs.log('Testcase and related files :\n%s' % str(resource_list))
if len(resource_list) <= 1:
# If this does not have any resources, just save the testcase.
# TODO(flowerhack): Update this when we teach CF how to download testcases.
try:
file_handle = open(testcase_path, 'rb')
except OSError:
logs.log_error('Unable to open testcase %s.' % testcase_path)
return None, None, None, None
else:
# If there are resources, create an archive.
# Find the common root directory for all of the resources.
# Assumption: resource_list[0] is the testcase path.
base_directory_list = resource_list[0].split(os.path.sep)
for list_index in range(1, len(resource_list)):
current_directory_list = resource_list[list_index].split(os.path.sep)
length = min(len(base_directory_list), len(current_directory_list))
for directory_index in range(length):
if (current_directory_list[directory_index] !=
base_directory_list[directory_index]):
base_directory_list = base_directory_list[0:directory_index]
break
base_directory = os.path.sep.join(base_directory_list)
logs.log('Subresource common base directory: %s' % base_directory)
if base_directory:
# Common parent directory, archive sub-paths only.
base_len = len(base_directory) + len(os.path.sep)
else:
# No common parent directory, archive all paths as it-is.
base_len = 0
# Prepare the filename for the archive.
zip_filename, _ = os.path.splitext(os.path.basename(testcase_path))
zip_filename += _TESTCASE_ARCHIVE_EXTENSION
# Create the archive.
zip_path = os.path.join(environment.get_value('INPUT_DIR'), zip_filename)
zip_file = zipfile.ZipFile(zip_path, 'w')
for file_name in resource_list:
if os.path.exists(file_name):
relative_filename = file_name[base_len:]
zip_file.write(file_name, relative_filename, zipfile.ZIP_DEFLATED)
zip_file.close()
try:
file_handle = open(zip_path, 'rb')
except OSError:
logs.log_error('Unable to open testcase archive %s.' % zip_path)
return None, None, None, None
archived = True
absolute_filename = testcase_path[base_len:]
fuzzed_key = blobs.write_blob(file_handle)
file_handle.close()
# Don't need the archive after writing testcase to blobstore.
if zip_path:
shell.remove_file(zip_path)
return fuzzed_key, archived, absolute_filename, zip_filename | Archive testcase and its dependencies, and store in blobstore. |
157,252 | import functools
import sys
import time
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.tasks import blame_task
from clusterfuzz._internal.bot.tasks import impact_task
from clusterfuzz._internal.bot.tasks import task_types
from clusterfuzz._internal.bot.tasks import unpack_task
from clusterfuzz._internal.bot.tasks.utasks import analyze_task
from clusterfuzz._internal.bot.tasks.utasks import corpus_pruning_task
from clusterfuzz._internal.bot.tasks.utasks import fuzz_task
from clusterfuzz._internal.bot.tasks.utasks import minimize_task
from clusterfuzz._internal.bot.tasks.utasks import progression_task
from clusterfuzz._internal.bot.tasks.utasks import regression_task
from clusterfuzz._internal.bot.tasks.utasks import symbolize_task
from clusterfuzz._internal.bot.tasks.utasks import variant_task
from clusterfuzz._internal.bot.webserver import http_server
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import process_handler
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `set_task_payload` function. Write a Python function `def set_task_payload(func)` to solve the following problem:
Set TASK_PAYLOAD and unset TASK_PAYLOAD.
Here is the function:
def set_task_payload(func):
"""Set TASK_PAYLOAD and unset TASK_PAYLOAD."""
@functools.wraps(func)
def wrapper(task_name, task_argument, job_name, *args, **kwargs):
"""Wrapper."""
payload = tasks.construct_payload(task_name, task_argument, job_name)
environment.set_value('TASK_PAYLOAD', payload)
try:
return func(task_name, task_argument, job_name, *args, **kwargs)
except: # Truly catch *all* exceptions.
e = sys.exc_info()[1]
e.extras = {'task_payload': environment.get_value('TASK_PAYLOAD')}
raise
finally:
environment.remove_key('TASK_PAYLOAD')
return wrapper | Set TASK_PAYLOAD and unset TASK_PAYLOAD. |
157,253 | from clusterfuzz._internal.base import utils
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.chrome import build_info
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
def is_valid_regression_range(regression_range, job_type):
"""Return whether we have a valid regression range."""
start, end = get_start_and_end_revision(regression_range, job_type)
return start != 0 or end != 0
def get_impacts_from_url(regression_range, job_type, platform=None):
"""Gets impact string using the build information url."""
logs.log('Get component impacts from URL: range %s, '
'job type %s.' % (regression_range, str(job_type)))
component_name = data_handler.get_component_name(job_type)
if component_name:
return get_component_impacts_from_url(component_name, regression_range,
job_type, platform)
start_revision, end_revision = get_start_and_end_revision(
regression_range, job_type)
logs.log('Proceeding to calculate impacts as non-component based on '
'range %s-%s' % (str(start_revision), str(end_revision)))
if not end_revision:
return Impacts()
logs.log(f'Gathering build to revision mappings for {platform}')
build_revision_mappings = build_info.get_build_to_revision_mappings(platform)
if not build_revision_mappings:
return Impacts()
logs.log('Calculating impacts from URL')
extended_stable = get_impact(
build_revision_mappings.get('extended_stable'), start_revision,
end_revision)
stable = get_impact(
build_revision_mappings.get('stable'), start_revision, end_revision)
beta = get_impact(
build_revision_mappings.get('beta'), start_revision, end_revision)
head = get_head_impact(build_revision_mappings, start_revision, end_revision)
return Impacts(stable, beta, extended_stable, head)
def set_testcase_with_impacts(testcase, impacts):
"""Set testcase's impact-related fields given impacts."""
testcase.impact_extended_stable_version = impacts.extended_stable.version
testcase.impact_extended_stable_version_likely = \
impacts.extended_stable.likely
testcase.impact_stable_version = impacts.stable.version
testcase.impact_stable_version_likely = impacts.stable.likely
testcase.impact_beta_version = impacts.beta.version
testcase.impact_beta_version_likely = impacts.beta.likely
testcase.impact_head_version = impacts.head.version
testcase.impact_head_version_likely = impacts.head.likely
testcase.is_impact_set_flag = True
The provided code snippet includes necessary dependencies for implementing the `execute_task` function. Write a Python function `def execute_task(testcase_id, job_type)` to solve the following problem:
Attempt to find if the testcase affects release branches on Chromium.
Here is the function:
def execute_task(testcase_id, job_type):
"""Attempt to find if the testcase affects release branches on Chromium."""
# We don't need job_type but it's supplied to all tasks.
del job_type
# This shouldn't ever get scheduled, but check just in case.
if not utils.is_chromium():
return
# Locate the testcase associated with the id.
testcase = data_handler.get_testcase_by_id(testcase_id)
# If this testcase is fixed, we should no longer be doing impact testing.
if testcase.fixed and testcase.is_impact_set_flag:
return
# For testcases with status unreproducible, we just do impact analysis just
# once.
if testcase.is_status_unreproducible() and testcase.is_impact_set_flag:
return
# Update comments only after checking the above bailout conditions.
data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED)
# This task is not applicable to unreproducible testcases.
if testcase.one_time_crasher_flag:
data_handler.update_testcase_comment(
testcase, data_types.TaskState.ERROR,
'Not applicable for unreproducible testcases')
return
# This task is not applicable for custom binaries. We cannot remove the
# creation of such tasks specifically for custom binary testcase in cron,
# so exit gracefully.
if build_manager.is_custom_binary():
data_handler.update_testcase_comment(testcase,
data_types.TaskState.FINISHED,
'Not applicable for custom binaries')
return
logs.log('Preparing to calculate impact.')
# Formerly ClusterFuzz had buckets containing builds for stable,
# beta and dev builds, and attempted reproduction on them. That had
# the advantage that we would test against the exact thing shipped on each
# channel, including any backported features. In practice, though, we
# never noticed a difference from a bisection-based approach to determining
# impacted builds, and those production build buckets disappered, so we have
# switched to a purely bisection-based approach.
if not is_valid_regression_range(testcase.regression, testcase.job_type):
data_handler.update_testcase_comment(
testcase, data_types.TaskState.FINISHED,
'Cannot run without regression range, will re-run once regression '
'task finishes')
return
logs.log('Calculating impact from URL.')
impacts = get_impacts_from_url(testcase.regression, testcase.job_type)
testcase = data_handler.get_testcase_by_id(testcase_id)
set_testcase_with_impacts(testcase, impacts)
data_handler.update_testcase_comment(testcase, data_types.TaskState.FINISHED) | Attempt to find if the testcase affects release branches on Chromium. |
157,254 | import json
import re
from clusterfuzz._internal.build_management import build_manager
from clusterfuzz._internal.build_management import revisions
from clusterfuzz._internal.config import db_config
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import pubsub
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
def _prepare_predator_message(testcase):
"""Prepare the json sent to the Predator service for the given test case."""
result, error_message = _is_predator_testcase(testcase)
if not result:
_set_predator_result_with_error(testcase, error_message)
return None
crash_revisions_dict, crash_revision_hash = _prepare_component_revisions_dict(
testcase.crash_revision, testcase.job_type)
# Do a None check since we can return {} for revision = 0.
if crash_revisions_dict is None:
_set_predator_result_with_error(
testcase, 'Failed to fetch component revisions for revision %s.' %
testcase.crash_revision)
return None
dependency_rolls = []
start_revision_hash = end_revision_hash = None
if ':' in testcase.regression:
regression_parts = testcase.regression.split(':', 1)
start_revision = int(regression_parts[0])
end_revision = int(regression_parts[1])
start_revisions_dict, start_revision_hash = (
_prepare_component_revisions_dict(start_revision, testcase.job_type))
# Do a None check since we can return {} for revision = 0.
if start_revisions_dict is None:
_set_predator_result_with_error(
testcase, 'Failed to fetch component revisions for revision %s.' %
start_revision)
return None
end_revisions_dict, end_revision_hash = (
_prepare_component_revisions_dict(end_revision, testcase.job_type))
# Do a None check since we can return {} for revision = 0.
if end_revisions_dict is None:
_set_predator_result_with_error(
testcase,
'Failed to fetch component revisions for revision %s.' % end_revision)
return None
if start_revision != 0:
dependency_rolls = _compute_rolls(start_revisions_dict,
end_revisions_dict)
# Put the current revisions dictionary in the format predator expects.
crash_revision_component_revisions_list = (
_format_component_revisions_for_predator(crash_revisions_dict))
# In addition to the start and end revisions, Predator expects the regression
# range to include the dependency path and repository URL in the same way that
# they would be included in the dependency rolls. Note that we do not take
# this from the rolls dict directly as it may not be available.
src_entry = [
entry for entry in crash_revision_component_revisions_list
if entry['dep_path'] == 'src'
][0]
# TODO(mbarbella): This is a hack since ClusterFuzz relies on "src" as a
# special-cased path, but this is only going to be the correct repository
# root path some of the time. For certain cases, we must update it.
repo_url = src_entry['repo_url']
real_dep_path = SRC_COMPONENT_OVERRIDES.get(repo_url, 'src')
if real_dep_path != 'src':
for dependency_list in [
dependency_rolls, crash_revision_component_revisions_list
]:
for entry in dependency_list:
if entry['dep_path'] == 'src':
entry['dep_path'] = real_dep_path
break
regression_range = {
'dep_path': real_dep_path,
'repo_url': repo_url,
'old_revision': start_revision_hash,
'new_revision': end_revision_hash,
}
crash_stacktrace = _filter_stacktrace(data_handler.get_stacktrace(testcase))
return pubsub.Message(
data=json.dumps({
'stack_trace': crash_stacktrace,
'crash_revision': crash_revision_hash,
'customized_data': {
'regression_range': regression_range,
'dependency_rolls': dependency_rolls,
'dependencies': crash_revision_component_revisions_list,
'crash_type': testcase.crash_type,
'crash_address': testcase.crash_address,
'sanitizer': environment.get_memory_tool_name(testcase.job_type),
'security_flag': testcase.security_flag,
'job_type': testcase.job_type,
'testcase_id': testcase.key.id()
},
'platform': testcase.platform,
'client_id': 'clusterfuzz',
'signature': testcase.crash_state,
}).encode('utf-8'))
def _clear_blame_result_and_set_pending_flag(testcase):
"""Clear blame result and set pending bit."""
testcase.set_metadata('blame_pending', True, update_testcase=False)
testcase.set_metadata('predator_result', None, update_testcase=False)
testcase.put()
The provided code snippet includes necessary dependencies for implementing the `execute_task` function. Write a Python function `def execute_task(testcase_id, _)` to solve the following problem:
Attempt to find the CL introducing the bug associated with testcase_id.
Here is the function:
def execute_task(testcase_id, _):
"""Attempt to find the CL introducing the bug associated with testcase_id."""
# Locate the testcase associated with the id.
testcase = data_handler.get_testcase_by_id(testcase_id)
# Make sure that predator topic is configured. If not, nothing to do here.
topic = db_config.get_value('predator_crash_topic')
if not topic:
logs.log('Predator is not configured, skipping blame task.')
return
data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED)
# Prepare pubsub message to send to predator.
message = _prepare_predator_message(testcase)
if not message:
testcase = data_handler.get_testcase_by_id(testcase_id)
data_handler.update_testcase_comment(
testcase, data_types.TaskState.ERROR,
'Failed to generate request for Predator')
return
# Clear existing results and mark blame result as pending.
testcase = data_handler.get_testcase_by_id(testcase_id)
_clear_blame_result_and_set_pending_flag(testcase)
# Post request to pub sub.
client = pubsub.PubSubClient()
message_ids = client.publish(topic, [message])
logs.log('Successfully published testcase %s to Predator. Message IDs: %s.' %
(testcase_id, message_ids))
data_handler.update_testcase_comment(testcase, data_types.TaskState.FINISHED) | Attempt to find the CL introducing the bug associated with testcase_id. |
157,255 | import json
import os
from google.cloud import ndb
from clusterfuzz._internal.base import tasks
from clusterfuzz._internal.datastore import data_handler
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.google_cloud_utils import blobs
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `execute_task` function. Write a Python function `def execute_task(metadata_id, job_type)` to solve the following problem:
Unpack a bundled testcase archive and create analyze jobs for each item.
Here is the function:
def execute_task(metadata_id, job_type):
"""Unpack a bundled testcase archive and create analyze jobs for each item."""
metadata = ndb.Key(data_types.BundledArchiveMetadata, int(metadata_id)).get()
if not metadata:
logs.log_error('Invalid bundle metadata id %s.' % metadata_id)
return
bot_name = environment.get_value('BOT_NAME')
upload_metadata = data_types.TestcaseUploadMetadata.query(
data_types.TestcaseUploadMetadata.blobstore_key ==
metadata.blobstore_key).get()
if not upload_metadata:
logs.log_error('Invalid upload metadata key %s.' % metadata.blobstore_key)
return
job = data_types.Job.query(data_types.Job.name == metadata.job_type).get()
if not job:
logs.log_error('Invalid job_type %s.' % metadata.job_type)
return
# Update the upload metadata with this bot name.
upload_metadata.bot_name = bot_name
upload_metadata.put()
# We can't use FUZZ_INPUTS directory since it is constrained
# by tmpfs limits.
testcases_directory = environment.get_value('FUZZ_INPUTS_DISK')
# Retrieve multi-testcase archive.
archive_path = os.path.join(testcases_directory, metadata.archive_filename)
if not blobs.read_blob_to_disk(metadata.blobstore_key, archive_path):
logs.log_error('Could not retrieve archive for bundle %d.' % metadata_id)
tasks.add_task('unpack', metadata_id, job_type)
return
try:
with archive.open(archive_path) as reader:
reader.extract_all(testcases_directory)
except:
logs.log_error('Could not unpack archive for bundle %d.' % metadata_id)
tasks.add_task('unpack', metadata_id, job_type)
return
# Get additional testcase metadata (if any).
additional_metadata = None
if upload_metadata.additional_metadata_string:
additional_metadata = json.loads(upload_metadata.additional_metadata_string)
archive_state = data_types.ArchiveStatus.NONE
bundled = True
for f in reader.list_members():
absolute_file_path = os.path.join(testcases_directory, f.name)
filename = os.path.basename(absolute_file_path)
# Only files are actual testcases. Skip directories.
if not os.path.isfile(absolute_file_path):
continue
try:
file_handle = open(absolute_file_path, 'rb')
blob_key = blobs.write_blob(file_handle)
file_handle.close()
except:
blob_key = None
if not blob_key:
logs.log_error(
'Could not write testcase %s to blobstore.' % absolute_file_path)
continue
data_handler.create_user_uploaded_testcase(
blob_key, metadata.blobstore_key, archive_state,
metadata.archive_filename, filename, metadata.timeout, job,
metadata.job_queue, metadata.http_flag, metadata.gestures,
metadata.additional_arguments, metadata.bug_information,
metadata.crash_revision, metadata.uploader_email, metadata.platform_id,
metadata.app_launch_command, metadata.fuzzer_name,
metadata.overridden_fuzzer_name, metadata.fuzzer_binary_name, bundled,
upload_metadata.retries, upload_metadata.bug_summary_update_flag,
upload_metadata.quiet_flag, additional_metadata)
# The upload metadata for the archive is not needed anymore since we created
# one for each testcase.
upload_metadata.key.delete()
shell.clear_testcase_directories() | Unpack a bundled testcase archive and create analyze jobs for each item. |
157,256 | import http.server
import mimetypes
import os
import socket
import threading
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `get_absolute_testcase_file` function. Write a Python function `def get_absolute_testcase_file(request_path)` to solve the following problem:
Search the input directory and additional paths for the requested file.
Here is the function:
def get_absolute_testcase_file(request_path):
"""Search the input directory and additional paths for the requested file."""
# Gather the list of search path directories.
current_working_directory = os.getcwd()
data_directory = environment.get_value('FUZZ_DATA')
input_directory = environment.get_value('INPUT_DIR')
fuzzer_directory = environment.get_value('FUZZERS_DIR')
layout_tests_directory = os.path.join(data_directory, 'LayoutTests')
layout_tests_http_tests_directory = os.path.join(layout_tests_directory,
'http', 'tests')
layout_tests_wpt_tests_directory = os.path.join(layout_tests_directory,
'external', 'wpt')
# TODO(mbarbella): Add support for aliasing and directories from
# https://cs.chromium.org/chromium/src/third_party/blink/tools/blinkpy/web_tests/servers/apache_http.py?q=apache_http.py&sq=package:chromium&dr&l=60
# Check all search paths for the requested file.
search_paths = [
current_working_directory,
fuzzer_directory,
input_directory,
layout_tests_directory,
layout_tests_http_tests_directory,
layout_tests_wpt_tests_directory,
]
for search_path in search_paths:
base_string = search_path + os.path.sep
path = request_path.lstrip('/')
if not path or path.endswith('/'):
path += 'index.html'
absolute_path = os.path.abspath(os.path.join(search_path, path))
if (absolute_path.startswith(base_string) and
os.path.exists(absolute_path) and not os.path.isdir(absolute_path)):
return absolute_path
return None | Search the input directory and additional paths for the requested file. |
157,257 | import http.server
import mimetypes
import os
import socket
import threading
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
The provided code snippet includes necessary dependencies for implementing the `guess_mime_type` function. Write a Python function `def guess_mime_type(filename)` to solve the following problem:
Guess mime type based of file extension.
Here is the function:
def guess_mime_type(filename):
"""Guess mime type based of file extension."""
if not mimetypes.inited:
mimetypes.init()
return mimetypes.guess_type(filename)[0] | Guess mime type based of file extension. |
157,258 | import re
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz.stacktraces import constants as stacktrace_constants
LEAK_TESTCASE_REGEX = re.compile(r'.*ERROR: LeakSanitizer.*')
LIBFUZZER_BAD_INSTRUMENTATION_REGEX = re.compile(
r'.*ERROR:.*Is the code instrumented for coverage.*')
LIBFUZZER_CRASH_TESTCASE_REGEX = re.compile(
LIBFUZZER_CRASH_TYPE_REGEX.format(type='crash'))
LIBFUZZER_OOM_TESTCASE_REGEX = re.compile(
LIBFUZZER_CRASH_TYPE_REGEX.format(type='oom'))
LIBFUZZER_SLOW_UNIT_TESTCASE_REGEX = re.compile(
LIBFUZZER_CRASH_TYPE_REGEX.format(type='slow-unit'))
LIBFUZZER_TIMEOUT_TESTCASE_REGEX = re.compile(
LIBFUZZER_CRASH_TYPE_REGEX.format(type='timeout'))
LIBFUZZER_LOG_DICTIONARY_REGEX = re.compile(r'Dictionary: \d+ entries')
LIBFUZZER_LOG_SEED_CORPUS_INFO_REGEX = re.compile(
r'INFO:\s+seed corpus:\s+files:\s+(\d+).*rss:\s+(\d+)Mb.*')
LIBFUZZER_MODULES_LOADED_REGEX = re.compile(
r'^INFO:\s+Loaded\s+\d+\s+(modules|PC tables)\s+\((\d+)\s+.*\).*')
LIBFUZZER_LOG_MAX_LEN_REGEX = re.compile(
r'.*-max_len is not provided; libFuzzer will not generate inputs larger'
r' than (\d+) bytes.*')
def calculate_log_lines(log_lines):
"""Calculate number of logs lines of different kind in the given log."""
# Counters to be returned.
libfuzzer_lines_count = 0
other_lines_count = 0
ignored_lines_count = 0
lines_after_last_libfuzzer_line_count = 0
libfuzzer_inited = False
found_libfuzzer_crash = False
for line in log_lines:
if not libfuzzer_inited:
# Skip to start of libFuzzer log output.
if LIBFUZZER_LOG_START_INITED_REGEX.match(line):
libfuzzer_inited = True
else:
ignored_lines_count += 1
continue
if LIBFUZZER_LOG_IGNORE_REGEX.match(line):
# We should ignore lines like sanitizer warnings, etc.
ignored_lines_count += 1
continue
if LIBFUZZER_ANY_CRASH_TYPE_REGEX.match(line):
# We should ignore whole block if a libfuzzer crash is found.
# E.g. slow units.
found_libfuzzer_crash = True
elif LIBFUZZER_LOG_LINE_REGEX.match(line):
if found_libfuzzer_crash:
# Ignore previous block.
other_lines_count -= lines_after_last_libfuzzer_line_count
ignored_lines_count += lines_after_last_libfuzzer_line_count
libfuzzer_lines_count += 1
lines_after_last_libfuzzer_line_count = 0
found_libfuzzer_crash = False
elif LIBFUZZER_LOG_END_REGEX.match(line):
libfuzzer_lines_count += 1
break
else:
other_lines_count += 1
lines_after_last_libfuzzer_line_count += 1
# Ignore the lines after the last libfuzzer line.
other_lines_count -= lines_after_last_libfuzzer_line_count
ignored_lines_count += lines_after_last_libfuzzer_line_count
return other_lines_count, libfuzzer_lines_count, ignored_lines_count
def strategy_column_name(strategy_name):
"""Convert the strategy name into stats column name."""
return 'strategy_%s' % strategy_name
def parse_fuzzing_strategies(log_lines, strategies):
"""Extract stats for fuzzing strategies used."""
if not strategies:
# Extract strategies from the log.
for line in log_lines:
match = LIBFUZZER_FUZZING_STRATEGIES.match(line)
if match:
strategies = match.group(1).split(',')
break
return process_strategies(strategies)
The provided code snippet includes necessary dependencies for implementing the `parse_performance_features` function. Write a Python function `def parse_performance_features(log_lines, strategies, arguments)` to solve the following problem:
Extract stats for performance analysis.
Here is the function:
def parse_performance_features(log_lines, strategies, arguments):
"""Extract stats for performance analysis."""
# TODO(ochang): Remove include_strategies once refactor is complete.
# Initialize stats with default values.
stats = {
'bad_instrumentation': 0,
'corpus_crash_count': 0,
'corpus_size': 0,
'crash_count': 0,
'dict_used': 0,
'edge_coverage': 0,
'edges_total': 0,
'feature_coverage': 0,
'initial_edge_coverage': 0,
'initial_feature_coverage': 0,
'leak_count': 0,
'log_lines_unwanted': 0,
'log_lines_from_engine': 0,
'log_lines_ignored': 0,
'max_len': 0,
'manual_dict_size': 0,
'merge_edge_coverage': 0,
'new_edges': 0,
'new_features': 0,
'oom_count': 0,
'slow_unit_count': 0,
'slow_units_count': 0,
'startup_crash_count': 1,
'timeout_count': 0,
}
arguments = fuzzer_options.FuzzerArguments.from_list(arguments)
# Extract strategy selection method.
# TODO(ochang): Move to more general place?
stats['strategy_selection_method'] = environment.get_value(
'STRATEGY_SELECTION_METHOD', default_value='default')
# Initialize all strategy stats as disabled by default.
for strategy_type in strategy.LIBFUZZER_STRATEGY_LIST:
if strategy.LIBFUZZER_STRATEGIES_WITH_PREFIX_VALUE_TYPE.get(
strategy_type.name) == str:
stats[strategy_column_name(strategy_type.name)] = ''
else:
stats[strategy_column_name(strategy_type.name)] = 0
# Process fuzzing strategies used.
stats.update(parse_fuzzing_strategies(log_lines, strategies))
(stats['log_lines_unwanted'], stats['log_lines_from_engine'],
stats['log_lines_ignored']) = calculate_log_lines(log_lines)
if stats['log_lines_from_engine'] > 0:
stats['startup_crash_count'] = 0
# Extract '-max_len' value from arguments, if possible.
max_len = arguments.get(
constants.MAX_LEN_FLAGNAME, default=None, constructor=int)
stats['max_len'] = max_len if max_len is not None else int(stats['max_len'])
# Extract sizes of manual dictionary used for fuzzing.
dictionary_path = arguments.get(constants.DICT_FLAGNAME, constructor=str)
stats['manual_dict_size'] = dictionary_manager.get_stats_for_dictionary_file(
dictionary_path)
# Different crashes and other flags extracted via regexp match.
has_corpus = False
for line in log_lines:
if LIBFUZZER_BAD_INSTRUMENTATION_REGEX.match(line):
stats['bad_instrumentation'] = 1
continue
if LIBFUZZER_CRASH_TESTCASE_REGEX.match(line):
stats['crash_count'] = 1
continue
if LIBFUZZER_LOG_DICTIONARY_REGEX.match(line):
stats['dict_used'] = 1
continue
if LEAK_TESTCASE_REGEX.match(line):
stats['leak_count'] = 1
continue
if (LIBFUZZER_OOM_TESTCASE_REGEX.match(line) or
stacktrace_constants.OUT_OF_MEMORY_REGEX.match(line)):
stats['oom_count'] = 1
continue
if LIBFUZZER_SLOW_UNIT_TESTCASE_REGEX.match(line):
# Use |slow_unit_count| to track if this run had any slow units at all.
# and use |slow_units_count| to track the actual number of slow units in
# this run (used by performance analyzer).
stats['slow_unit_count'] = 1
stats['slow_units_count'] += 1
continue
match = LIBFUZZER_LOG_SEED_CORPUS_INFO_REGEX.match(line)
if match:
has_corpus = True
match = LIBFUZZER_MODULES_LOADED_REGEX.match(line)
if match:
stats['startup_crash_count'] = 0
stats['edges_total'] = int(match.group(2))
if (LIBFUZZER_TIMEOUT_TESTCASE_REGEX.match(line) or
stacktrace_constants.LIBFUZZER_TIMEOUT_REGEX.match(line)):
stats['timeout_count'] = 1
continue
if not stats['max_len']:
# Get "max_len" value from the log, if it has not been found in arguments.
match = LIBFUZZER_LOG_MAX_LEN_REGEX.match(line)
if match:
stats['max_len'] = int(match.group(1))
continue
if has_corpus and not stats['log_lines_from_engine']:
stats['corpus_crash_count'] = 1
return stats | Extract stats for performance analysis. |
157,259 | import re
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz.stacktraces import constants as stacktrace_constants
LIBFUZZER_MERGE_LOG_STATS_REGEX = re.compile(
r'MERGE-OUTER:\s+\d+\s+new files with'
r'\s+(\d+)\s+new features added;'
r'\s+(\d+)\s+new coverage edges.*')
The provided code snippet includes necessary dependencies for implementing the `parse_stats_from_merge_log` function. Write a Python function `def parse_stats_from_merge_log(log_lines)` to solve the following problem:
Extract stats from a log produced by libFuzzer run with -merge=1.
Here is the function:
def parse_stats_from_merge_log(log_lines):
"""Extract stats from a log produced by libFuzzer run with -merge=1."""
stats = {
'edge_coverage': 0,
'feature_coverage': 0,
}
# Reverse the list as an optimization. The line of our interest is the last.
for line in reversed(log_lines):
match = LIBFUZZER_MERGE_LOG_STATS_REGEX.match(line)
if match:
stats['edge_coverage'] = int(match.group(2))
stats['feature_coverage'] = int(match.group(1))
break
return stats | Extract stats from a log produced by libFuzzer run with -merge=1. |
157,260 | import psutil
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
The provided code snippet includes necessary dependencies for implementing the `get_grammar` function. Write a Python function `def get_grammar(fuzzer_path)` to solve the following problem:
Get grammar for a given fuzz target. Return none if there isn't one.
Here is the function:
def get_grammar(fuzzer_path):
"""Get grammar for a given fuzz target. Return none if there isn't one."""
fuzzer_options = options.get_fuzz_target_options(fuzzer_path)
if fuzzer_options:
grammar = fuzzer_options.get_grammar_options()
if grammar:
return grammar.get('grammar')
return None | Get grammar for a given fuzz target. Return none if there isn't one. |
157,261 | import psutil
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
The provided code snippet includes necessary dependencies for implementing the `get_extra_env` function. Write a Python function `def get_extra_env(fuzzer_path)` to solve the following problem:
Get environment variables for a given fuzz target if any (or None).
Here is the function:
def get_extra_env(fuzzer_path):
"""Get environment variables for a given fuzz target if any (or None)."""
fuzzer_options = options.get_fuzz_target_options(fuzzer_path)
if fuzzer_options:
return fuzzer_options.get_env()
return None | Get environment variables for a given fuzz target if any (or None). |
157,262 | import psutil
from clusterfuzz._internal.bot.fuzzers import builtin
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
The provided code snippet includes necessary dependencies for implementing the `get_arguments` function. Write a Python function `def get_arguments(fuzzer_path) -> options.FuzzerArguments` to solve the following problem:
Get arguments for a given fuzz target.
Here is the function:
def get_arguments(fuzzer_path) -> options.FuzzerArguments:
"""Get arguments for a given fuzz target."""
arguments = options.FuzzerArguments()
rss_limit_mb = None
timeout = None
fuzzer_options = options.get_fuzz_target_options(fuzzer_path)
if fuzzer_options:
arguments = fuzzer_options.get_engine_arguments('libfuzzer')
rss_limit_mb = arguments.get('rss_limit_mb', constructor=int)
timeout = arguments.get('timeout', constructor=int)
if timeout is None or timeout > constants.DEFAULT_TIMEOUT_LIMIT:
arguments[constants.TIMEOUT_FLAGNAME] = constants.DEFAULT_TIMEOUT_LIMIT
if not rss_limit_mb:
arguments[constants.RSS_LIMIT_FLAGNAME] = constants.DEFAULT_RSS_LIMIT_MB
else:
# psutil gives the total amount of memory in bytes, but we're only dealing
# with options that are counting memory space in MB, so we need to do the
# conversion first.
max_memory_limit_mb = (psutil.virtual_memory().total //
(1 << 20)) - constants.MEMORY_OVERHEAD
# Custom rss_limit_mb value shouldn't be greater than the actual memory
# allocated on the machine.
if rss_limit_mb > max_memory_limit_mb:
arguments[constants.RSS_LIMIT_FLAGNAME] = max_memory_limit_mb
return arguments | Get arguments for a given fuzz target. |
157,263 | import os
import re
import tempfile
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import libfuzzer
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import strategy_selection
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer import fuzzer
from clusterfuzz._internal.bot.fuzzers.libFuzzer import stats
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import profiler
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
MULTISTEP_MERGE_SUPPORT_TOKEN = b'fuzz target overwrites its const input'
The provided code snippet includes necessary dependencies for implementing the `_is_multistep_merge_supported` function. Write a Python function `def _is_multistep_merge_supported(target_path)` to solve the following problem:
Checks whether a particular binary support multistep merge.
Here is the function:
def _is_multistep_merge_supported(target_path):
"""Checks whether a particular binary support multistep merge."""
# TODO(Dor1s): implementation below a temporary workaround, do not tell any
# body that we are doing this. The real solution would be to execute a
# fuzz target with '-help=1' and check the output for the presence of
# multistep merge support added in https://reviews.llvm.org/D71423.
# The temporary implementation checks that the version of libFuzzer is at
# least https://github.com/llvm/llvm-project/commit/da3cf61, which supports
# multi step merge: https://github.com/llvm/llvm-project/commit/f054067.
if os.path.exists(target_path):
with open(target_path, 'rb') as file_handle:
return utils.search_bytes_in_file(MULTISTEP_MERGE_SUPPORT_TOKEN,
file_handle)
return False | Checks whether a particular binary support multistep merge. |
157,264 | import os
import re
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
DICTIONARY_FILE_EXTENSION = '.dict'
The provided code snippet includes necessary dependencies for implementing the `get_default_dictionary_path` function. Write a Python function `def get_default_dictionary_path(fuzz_target_path)` to solve the following problem:
Return default dictionary path.
Here is the function:
def get_default_dictionary_path(fuzz_target_path):
"""Return default dictionary path."""
return fuzzer_utils.get_supporting_file(fuzz_target_path,
DICTIONARY_FILE_EXTENSION) | Return default dictionary path. |
157,265 | import os
import re
from clusterfuzz._internal.base import errors
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
def _fix_dictionary_line(line, dict_path):
"""Correct a single dictionary line."""
# Ignore blank and comment lines.
if not line or line.strip().startswith('#'):
return line
match = DICTIONARY_PART_PATTERN.match(line)
# We expect this pattern to match even invalid dictionary entries. Failures
# to match should be treated as bugs in this function.
if not match:
raise errors.BadStateError(
'Failed to correct dictionary line "{line}" in {path}.'.format(
line=line, path=dict_path))
name_part = match.group(1) or ''
entry = match.group(2)
# In some cases, we'll detect the user's intended entry as a token name. This
# can happen if the user included unquoted tokens such as "!=" or ">=".
if not entry and name_part:
entry = name_part
name_part = ''
# Handle quote entries as a special case. This simplifies later logic.
if entry == '"':
entry = '"\\\""'
if entry.startswith('"') and entry.endswith('"'):
return name_part + entry
# In this case, we know the entry is invalid. Escape any unescaped quotes
# within it, then append quotes to the front and back.
new_entry = ''
prev_character = ''
for character in entry:
if character == '"' and prev_character != '\\':
new_entry += '\\'
new_entry += character
prev_character = character
new_entry = '"{entry}"'.format(entry=new_entry)
return name_part + new_entry
The provided code snippet includes necessary dependencies for implementing the `correct_if_needed` function. Write a Python function `def correct_if_needed(dict_path)` to solve the following problem:
Corrects obvious errors such as missing quotes in a dictionary.
Here is the function:
def correct_if_needed(dict_path):
"""Corrects obvious errors such as missing quotes in a dictionary."""
if not dict_path or not os.path.exists(dict_path):
return
content = utils.read_data_from_file(
dict_path, eval_data=False).decode('utf-8')
new_content = ''
for current_line in content.splitlines():
new_content += _fix_dictionary_line(current_line, dict_path) + '\n'
# End of file newlines are inconsistent in dictionaries.
if new_content.rstrip('\n') != content.rstrip('\n'):
utils.write_data_to_file(new_content, dict_path) | Corrects obvious errors such as missing quotes in a dictionary. |
157,266 | import os
import re
import stat
import tempfile
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
def get_fuzz_targets_local(path):
"""Get list of fuzz targets paths (local)."""
fuzz_target_paths = []
for root, _, files in shell.walk(path):
for filename in files:
if os.path.basename(root) == EXTRA_BUILD_DIR:
# Ignore extra binaries.
continue
file_path = os.path.join(root, filename)
if is_fuzz_target_local(file_path):
fuzz_target_paths.append(file_path)
return fuzz_target_paths
The provided code snippet includes necessary dependencies for implementing the `get_fuzz_targets` function. Write a Python function `def get_fuzz_targets(path)` to solve the following problem:
Get list of fuzz targets paths.
Here is the function:
def get_fuzz_targets(path):
"""Get list of fuzz targets paths."""
if environment.is_trusted_host():
from clusterfuzz._internal.bot.untrusted_runner import file_host
return file_host.get_fuzz_targets(path)
return get_fuzz_targets_local(path) | Get list of fuzz targets paths. |
157,267 | import os
import re
import stat
import tempfile
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `extract_argument` function. Write a Python function `def extract_argument(arguments, prefix, remove=True)` to solve the following problem:
Extract argument from arguments.
Here is the function:
def extract_argument(arguments, prefix, remove=True):
"""Extract argument from arguments."""
for argument in arguments[:]:
if argument.startswith(prefix):
if remove:
arguments.remove(argument)
return argument[len(prefix):]
return None | Extract argument from arguments. |
157,268 | import os
import re
import stat
import tempfile
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `normalize_target_name` function. Write a Python function `def normalize_target_name(target_path)` to solve the following problem:
Normalize target path, removing file extensions.
Here is the function:
def normalize_target_name(target_path):
"""Normalize target path, removing file extensions."""
target_name = os.path.basename(target_path)
if '@' in target_name:
# GFT target names often have periods in their name.
return target_name
return os.path.splitext(target_name)[0] | Normalize target path, removing file extensions. |
157,269 | import contextlib
import glob
import json
import os
import random
import re
import shlex
import shutil
import sys
import time
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
def get_testcase_run(stats, fuzzer_command):
"""Get testcase run for stats."""
build_revision = fuzzer_utils.get_build_revision()
job = environment.get_value('JOB_NAME')
# fuzzer name is filled by fuzz_task.
testcase_run = fuzzer_stats.TestcaseRun(None, job, build_revision,
current_timestamp())
testcase_run['command'] = fuzzer_command
if stats is not None:
testcase_run.update(stats)
return testcase_run
The provided code snippet includes necessary dependencies for implementing the `dump_big_query_data` function. Write a Python function `def dump_big_query_data(stats, testcase_file_path, fuzzer_command)` to solve the following problem:
Dump BigQuery stats.
Here is the function:
def dump_big_query_data(stats, testcase_file_path, fuzzer_command):
"""Dump BigQuery stats."""
testcase_run = get_testcase_run(stats, fuzzer_command)
fuzzer_stats.TestcaseRun.write_to_disk(testcase_run, testcase_file_path) | Dump BigQuery stats. |
157,270 | import contextlib
import glob
import json
import os
import random
import re
import shlex
import shutil
import sys
import time
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `get_project_qualified_fuzzer_name` function. Write a Python function `def get_project_qualified_fuzzer_name(target_path)` to solve the following problem:
Return project qualified fuzzer name for a given target path.
Here is the function:
def get_project_qualified_fuzzer_name(target_path):
"""Return project qualified fuzzer name for a given target path."""
return data_types.fuzz_target_project_qualified_name(
utils.current_project(), os.path.basename(target_path)) | Return project qualified fuzzer name for a given target path. |
157,271 | import contextlib
import glob
import json
import os
import random
import re
import shlex
import shutil
import sys
import time
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `strip_minijail_command` function. Write a Python function `def strip_minijail_command(command, fuzzer_path)` to solve the following problem:
Remove minijail arguments from a fuzzer command. Args: command: The command. fuzzer_path: Absolute path to the fuzzer. Returns: The stripped command.
Here is the function:
def strip_minijail_command(command, fuzzer_path):
"""Remove minijail arguments from a fuzzer command.
Args:
command: The command.
fuzzer_path: Absolute path to the fuzzer.
Returns:
The stripped command.
"""
try:
fuzzer_path_index = command.index(fuzzer_path)
return command[fuzzer_path_index:]
except ValueError:
return command | Remove minijail arguments from a fuzzer command. Args: command: The command. fuzzer_path: Absolute path to the fuzzer. Returns: The stripped command. |
157,272 | import contextlib
import glob
import json
import os
import random
import re
import shlex
import shutil
import sys
import time
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
def signal_term_handler(sig, frame): # pylint: disable=unused-argument
try:
print('SIGTERMed')
except OSError: # Pipe may already be closed and we may not be able to print.
pass
new_process.kill_process_tree(os.getpid())
sys.exit(0) | null |
157,273 | import contextlib
import glob
import json
import os
import random
import re
import shlex
import shutil
import sys
import time
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import fuzzer_stats
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
MAX_FILES_FOR_UNPACK = 5
def get_seed_corpus_path(fuzz_target_path):
"""Returns the path of the seed corpus if one exists. Otherwise returns None.
Logs an error if multiple seed corpora exist for the same target."""
archive_path_without_extension = fuzzer_utils.get_supporting_file(
fuzz_target_path, SEED_CORPUS_ARCHIVE_SUFFIX)
# Get all files that end with _seed_corpus.*
possible_archive_paths = set(glob.glob(archive_path_without_extension + '.*'))
# Now get a list of these that are valid seed corpus archives.
archive_paths = possible_archive_paths.intersection({
archive_path_without_extension + extension
for extension in archive.ARCHIVE_FILE_EXTENSIONS
})
archive_paths = list(archive_paths)
if not archive_paths:
return None
if len(archive_paths) > 1:
logs.log_error('Multiple seed corpuses exist for fuzz target %s: %s.' %
(fuzz_target_path, ', '.join(archive_paths)))
return archive_paths[0]
The provided code snippet includes necessary dependencies for implementing the `unpack_seed_corpus_if_needed` function. Write a Python function `def unpack_seed_corpus_if_needed(fuzz_target_path, corpus_directory, max_bytes=float('inf'), force_unpack=False, max_files_for_unpack=MAX_FILES_FOR_UNPACK)` to solve the following problem:
If seed corpus available, unpack it into the corpus directory if needed, ie: if corpus exists and either |force_unpack| is True, or the number of files in corpus_directory is less than |max_files_for_unpack|. Uses |fuzz_target_path| to find the seed corpus. If max_bytes is specified, then seed corpus files larger than |max_bytes| will not be unpacked.
Here is the function:
def unpack_seed_corpus_if_needed(fuzz_target_path,
corpus_directory,
max_bytes=float('inf'),
force_unpack=False,
max_files_for_unpack=MAX_FILES_FOR_UNPACK):
"""If seed corpus available, unpack it into the corpus directory if needed,
ie: if corpus exists and either |force_unpack| is True, or the number of files
in corpus_directory is less than |max_files_for_unpack|. Uses
|fuzz_target_path| to find the seed corpus. If max_bytes is specified, then
seed corpus files larger than |max_bytes| will not be unpacked.
"""
seed_corpus_archive_path = get_seed_corpus_path(fuzz_target_path)
if not seed_corpus_archive_path:
return
num_corpus_files = len(shell.get_files_list(corpus_directory))
if not force_unpack and num_corpus_files > max_files_for_unpack:
return
if force_unpack:
logs.log('Forced unpack: %s.' % seed_corpus_archive_path)
try:
reader = archive.open(seed_corpus_archive_path)
except:
logs.log_error(f'Failed reading archive: {seed_corpus_archive_path}')
return
idx = 0
with reader:
for file in reader.list_members():
if file.is_dir:
continue
if file.size_bytes > max_bytes:
continue
output_filename = '%016d' % idx
output_file_path = os.path.join(corpus_directory, output_filename)
with open(output_file_path, 'wb') as file_handle:
with reader.open(file.name) as file:
shutil.copyfileobj(file, file_handle)
idx += 1
logs.log('Unarchiving %d files from seed corpus %s.' %
(idx, seed_corpus_archive_path)) | If seed corpus available, unpack it into the corpus directory if needed, ie: if corpus exists and either |force_unpack| is True, or the number of files in corpus_directory is less than |max_files_for_unpack|. Uses |fuzz_target_path| to find the seed corpus. If max_bytes is specified, then seed corpus files larger than |max_bytes| will not be unpacked. |
157,274 | import copy
import fnmatch
import os
import re
import tempfile
import threading
import time
from typing import List
import requests
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.syzkaller import config
from clusterfuzz._internal.config import local_config
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms.android import kernel_utils
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
def get_work_dir():
"""Return work directory for Syzkaller."""
work_dir = os.path.join(
environment.get_value('FUZZ_INPUTS_DISK'), 'syzkaller')
os.makedirs(work_dir, exist_ok=True)
return work_dir
The provided code snippet includes necessary dependencies for implementing the `get_config` function. Write a Python function `def get_config()` to solve the following problem:
Get arguments for a given fuzz target.
Here is the function:
def get_config():
"""Get arguments for a given fuzz target."""
device_serial = environment.get_value('ANDROID_SERIAL')
build_dir = environment.get_value('BUILD_DIR')
temp_dir = fuzzer_utils.get_temp_dir()
binary_path = os.path.join(build_dir, 'syzkaller')
json_config_path = os.path.join(temp_dir, 'config.json')
default_vmlinux_path = os.path.join('/tmp', device_serial, 'vmlinux')
vmlinux_path = environment.get_value('VMLINUX_PATH', default_vmlinux_path)
syzhub_address = environment.get_value('SYZHUB_ADDRESS')
syzhub_client = environment.get_value('SYZHUB_CLIENT')
syzhub_key = environment.get_value('SYZHUB_KEY')
on_cuttlefish = environment.is_android_cuttlefish()
config.generate(
serial=device_serial,
work_dir_path=get_work_dir(),
binary_path=binary_path,
vmlinux_path=vmlinux_path,
config_path=json_config_path,
kcov=True,
reproduce=False,
syzhub_address=syzhub_address,
syzhub_client=syzhub_client,
syzhub_key=syzhub_key,
on_cuttlefish=on_cuttlefish)
return ['-config', json_config_path] | Get arguments for a given fuzz target. |
157,275 | import copy
import fnmatch
import os
import re
import tempfile
import threading
import time
from typing import List
import requests
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.syzkaller import config
from clusterfuzz._internal.config import local_config
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms.android import kernel_utils
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
def get_work_dir():
"""Return work directory for Syzkaller."""
work_dir = os.path.join(
environment.get_value('FUZZ_INPUTS_DISK'), 'syzkaller')
os.makedirs(work_dir, exist_ok=True)
return work_dir
The provided code snippet includes necessary dependencies for implementing the `get_cover_file_path` function. Write a Python function `def get_cover_file_path()` to solve the following problem:
Return location of coverage file for Syzkaller.
Here is the function:
def get_cover_file_path():
"""Return location of coverage file for Syzkaller."""
return os.path.join(get_work_dir(), 'coverfile') | Return location of coverage file for Syzkaller. |
157,276 | import copy
import fnmatch
import os
import re
import tempfile
import threading
import time
from typing import List
import requests
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.syzkaller import config
from clusterfuzz._internal.config import local_config
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms.android import kernel_utils
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
class AndroidSyzkallerRunner(new_process.UnicodeProcessRunner):
"""Syzkaller runner."""
def __init__(self, executable_path):
"""Inits the AndroidSyzkallerRunner.
Args:
executable_path: Path to the fuzzer executable.
"""
super().__init__(executable_path=executable_path)
self._port = None
def get_command(self, additional_args=None):
"""Process.get_command override."""
base_command = super().get_command(additional_args=additional_args)
return base_command
def get_port(self, pid: int) -> int or None:
"""Find localhost port where syzkaller is connected."""
if self._port is not None:
return self._port
import psutil # pylint: disable=g-import-not-at-top
for connection in psutil.net_connections():
if connection.pid != pid:
continue
local_address = connection.laddr
if (local_address.ip == LOCAL_HOST and
connection.status == psutil.CONN_LISTEN):
self._port = local_address.port
logs.log(f'Syzkaller listening at: http://localhost:{self._port}')
return self._port
# No connection found
return None
def _create_empty_testcase_file(self):
"""Create an empty testcase file in temporary directory."""
_, path = tempfile.mkstemp(dir=fuzzer_utils.get_temp_dir())
return path
def _crash_was_reproducible(self, output: str) -> bool:
search = REPRODUCE_DONE_PATTERN.search(output)
return search and int(search.group(1)) != 0
def repro(self, repro_timeout: int,
repro_args: List[str]) -> engine.ReproduceResult:
"""This is where crash repro'ing is done.
Args:
repro_timeout: The maximum time in seconds that repro job is allowed
to run for.
repro_args: A sequence of arguments to be passed to the executable.
"""
logs.log('Running Syzkaller (syz-crush) against testcase.')
additional_args = repro_args.copy()
for retry_count in range(REPRO_RETRY_MAX):
result = self.run_and_wait(additional_args, timeout=repro_timeout)
log_location = re.search(REPRODUCE_LOG_LOCATION_PATTERN, result.output)
# syz-crush stopped before capturing crash output
if not log_location:
continue
# syz-crush did not reproduce any crash
if not self._crash_was_reproducible(result.output):
continue
_type, log_index, log_dir = log_location.groups() # pylint: disable=invalid-name
try:
reproducer_log_path = os.path.join(log_dir, f'reproducer{log_index}')
with open(reproducer_log_path) as f:
logs.log('Successfully reproduced crash.')
return engine.ReproduceResult(
command=result.command,
return_code=1,
time_executed=result.time_executed,
output=f.read(),
)
except FileNotFoundError as e:
logs.log('Reproducer log was not found. Rerunning syz-crush', e)
continue
logs.log(f'Failed to reproduce crash after {retry_count} attempts.')
return engine.ReproduceResult(
command=result.command,
return_code=0,
time_executed=result.time_executed,
output=result.output,
)
def minimize(self, minimize_args: List[str]) -> engine.ReproduceResult:
"""Minimizing crash testcase.
Args:
minimize_args: list of arguments to be passed to syz-repro.
"""
logs.log('Running Syzkaller Minimization (syz-repro) against testcase.')
additional_args = minimize_args.copy()
result = self.run_and_wait(additional_args)
if result.return_code:
logs.log('Successfully minimized crash.')
else:
logs.log('Failed to minimize crash.')
logs.log('Syzkaller minimize testcase stopped.')
return engine.ReproduceResult(result.command, result.return_code,
result.time_executed, result.output)
def save_rawcover_output(self, pid: int):
"""Find syzkaller port and write rawcover data to a file."""
port = self.get_port(pid)
if port is None:
logs.log_warn('Could not find Syzkaller port')
return
try:
rawcover = requests.get(
f'http://localhost:{port}/rawcover', timeout=GET_TIMEOUT_SECONDS).text
except requests.exceptions.RequestException:
logs.log_warn('Connection to Syzkaller Failed')
return
if not rawcover or rawcover.startswith('coverage is not ready'):
logs.log_warn('Syzkaller rawcover not yet loaded')
return
file_path = get_cover_file_path()
with open(file_path, 'w+') as f:
f.write(rawcover)
logs.log(f'Writing syzkaller rawcover to {file_path}')
def run_and_loop(self, *args, timeout=None,
**kwargs) -> new_process.ProcessResult:
"""Adds looping call to run_and_wait method.
This method adds LoopingTimer() that continuously executes a function
that gets / saves rawcover data from Syzkaller.
Args:
*args: args for self.run()
timeout: timeout in seconds to stop Syzkaller
**kwargs: kwargs for self.run()
Returns:
new_process.ProcessResult from Syzkaller
"""
process = self.run(*args, **kwargs)
pid = process.popen.pid
logs.log(f'Syzkaller pid = {pid}')
looping_timer = LoopingTimer(
RAWCOVER_RETRIEVE_INTERVAL,
self.save_rawcover_output,
args=[pid],
)
looping_timer.start()
try:
if not timeout:
start_time = time.time()
output = process.communicate()[0]
return new_process.ProcessResult(process.command, process.poll(),
output,
time.time() - start_time, False)
result = new_process.wait_process(
process,
timeout=timeout,
input_data=None,
terminate_before_kill=False,
terminate_wait_time=None,
)
result.command = process.command
result.output = str(result.output, 'utf-8')
return result
finally:
looping_timer.cancel()
def _filter_log(self, content: str) -> str:
"""Remove unnecessary prefix from each line of log.
e.g
[ 565.723853] c4 8262 BUG: KASAN: use-after-free...
vs.
BUG: KASAN: use-after-free...
[ 1850.287295] KASAN: ...
vs.
KASAN: ...
Args:
content (str): log content
Returns:
filtered log with new lines (str)
"""
strip_regex = re.compile(r'^(\[.*?\]\s+)?(c\d+\s+\d+\s)?')
result = [strip_regex.sub('', line) for line in content.splitlines()]
return '\n'.join(result)
def fuzz(
self,
fuzz_timeout,
additional_args,
unused_additional_args=None,
unused_extra_env=None,
) -> engine.FuzzResult:
"""This is where actual syzkaller fuzzing is done.
Args:
fuzz_timeout (float): The maximum time in seconds that fuzz job is allowed
to run for.
additional_args: A sequence of additional arguments to be passed to
the executable.
Returns:
engine.FuzzResult
"""
logs.log('Running Syzkaller.')
additional_args = copy.copy(additional_args)
# Save kernel_bid for later in case the device is down.
_, kernel_bid = kernel_utils.get_kernel_hash_and_build_id()
fuzz_result = self.run_and_loop(additional_args, timeout=fuzz_timeout)
logs.log('Syzkaller stopped, fuzzing timed out: {}'.format(
fuzz_result.time_executed))
fuzz_logs = (fuzz_result.output or '') + '\n'
crashes = []
parsed_stats = {}
visited = set()
for subdir, _, files in os.walk(get_work_dir()):
for file in files:
# Each crash typically have 2 files: reportN and logN. Similar crashes
# are grouped together in subfolders. unique_crash puts together the
# subfolder name and reportN.
unique_crash = os.path.join(subdir, file)
if fnmatch.fnmatch(file, 'report*') and unique_crash not in visited:
visited.add(unique_crash)
log_content = self._filter_log(
utils.read_data_from_file(
os.path.join(subdir, file), eval_data=False).decode('utf-8'))
fuzz_logs += log_content + '\n'
# Since each crash (report file) has a corresponding log file
# that contains the syscalls that caused the crash. This file is
# located in the same subfolder and has the same number.
# E.g. ./439c37d288d4f26a33a6c7e5c57a97791453a447/report15 and
# ./439c37d288d4f26a33a6c7e5c57a97791453a447/log15.
crash_testcase_file_path = os.path.join(subdir,
'log' + file[len('report'):])
# TODO(hzawawy): Parse stats information and add them to FuzzResult.
if crash_testcase_file_path:
reproduce_arguments = [unique_crash]
actual_duration = int(fuzz_result.time_executed)
# Write the new testcase.
# Copy crash testcase contents into the main testcase path.
crashes.append(
engine.Crash(crash_testcase_file_path, log_content,
reproduce_arguments, actual_duration))
_upload_kernel_coverage_data(get_cover_file_path(), kernel_bid)
return engine.FuzzResult(fuzz_logs, fuzz_result.command, crashes,
parsed_stats, fuzz_result.time_executed)
The provided code snippet includes necessary dependencies for implementing the `get_runner` function. Write a Python function `def get_runner(fuzzer_path)` to solve the following problem:
Return a syzkaller runner object.
Here is the function:
def get_runner(fuzzer_path):
"""Return a syzkaller runner object."""
return AndroidSyzkallerRunner(fuzzer_path) | Return a syzkaller runner object. |
157,277 | import copy
import fnmatch
import os
import re
import tempfile
import threading
import time
from typing import List
import requests
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.syzkaller import config
from clusterfuzz._internal.config import local_config
from clusterfuzz._internal.google_cloud_utils import storage
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms.android import kernel_utils
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `_upload_kernel_coverage_data` function. Write a Python function `def _upload_kernel_coverage_data(kcov_path, kernel_bid)` to solve the following problem:
Upload kcov data to a cloud storage bucket.
Here is the function:
def _upload_kernel_coverage_data(kcov_path, kernel_bid):
"""Upload kcov data to a cloud storage bucket."""
bucket_name = local_config.ProjectConfig().get('coverage.reports.bucket')
if not bucket_name:
return
formatted_date = str(utils.utcnow().date().isoformat())
identifier = environment.get_value('BOT_NAME') + str(
utils.utcnow().isoformat())
gcs_url = (f'gs://{bucket_name}/syzkaller/{formatted_date}/{kernel_bid}/'
f'{identifier}')
if storage.copy_file_to(kcov_path, gcs_url):
logs.log(f'Copied kcov data to {gcs_url}.') | Upload kcov data to a cloud storage bucket. |
157,278 | FORK_SERVER_FLAGNAME = 'fork_server'
FORK_SERVER_DEFAULT = 1
RSS_LIMIT_MB_FLAGNAME = 'rss_limit_mb'
RSS_LIMIT_MB_DEFAULT = 4096
TIMEOUT_PER_INPUT_FLAGNAME = 'timeout_per_input'
TIMEOUT_PER_INPUT_DEFAULT = 25
ADDRESS_SPACE_LIMIT_FLAGNAME = 'address_space_limit_mb'
ADDRESS_SPACE_LIMIT_DEFAULT = 4096
EXIT_ON_CRASH_FLAGNAME = 'exit_on_crash'
def get_default_arguments():
return {
FORK_SERVER_FLAGNAME: FORK_SERVER_DEFAULT,
RSS_LIMIT_MB_FLAGNAME: RSS_LIMIT_MB_DEFAULT,
ADDRESS_SPACE_LIMIT_FLAGNAME: ADDRESS_SPACE_LIMIT_DEFAULT,
TIMEOUT_PER_INPUT_FLAGNAME: TIMEOUT_PER_INPUT_DEFAULT,
EXIT_ON_CRASH_FLAGNAME: 1,
} | null |
157,279 | from collections import namedtuple
import os
import pathlib
import re
import shutil
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.centipede import constants
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
class CentipedeError(Exception):
"""Base exception class."""
The provided code snippet includes necessary dependencies for implementing the `_get_runner` function. Write a Python function `def _get_runner(target_path)` to solve the following problem:
Gets the Centipede runner.
Here is the function:
def _get_runner(target_path):
"""Gets the Centipede runner."""
centipede_path = pathlib.Path(target_path).parent / 'centipede'
if not centipede_path.exists():
raise CentipedeError('Centipede not found in build')
centipede_path = str(centipede_path)
if environment.get_value('USE_UNSHARE'):
return new_process.UnicodeModifierRunner(centipede_path)
return new_process.UnicodeProcessRunner(centipede_path) | Gets the Centipede runner. |
157,280 | from collections import namedtuple
import os
import pathlib
import re
import shutil
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.centipede import constants
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
CRASH_REGEX = re.compile(r'[sS]aving input to:?\s*(.*)')
The provided code snippet includes necessary dependencies for implementing the `_get_reproducer_path` function. Write a Python function `def _get_reproducer_path(log, reproducers_dir)` to solve the following problem:
Gets the reproducer path, if any.
Here is the function:
def _get_reproducer_path(log, reproducers_dir):
"""Gets the reproducer path, if any."""
crash_match = CRASH_REGEX.search(log)
if not crash_match:
return None
tmp_crash_path = pathlib.Path(crash_match.group(1))
crash_path = pathlib.Path(reproducers_dir) / tmp_crash_path.name
shutil.copy(tmp_crash_path, crash_path)
return crash_path | Gets the reproducer path, if any. |
157,281 | from collections import namedtuple
import os
import pathlib
import re
import shutil
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.centipede import constants
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `_set_sanitizer_options` function. Write a Python function `def _set_sanitizer_options(fuzzer_path)` to solve the following problem:
Sets sanitizer options based on .options file overrides.
Here is the function:
def _set_sanitizer_options(fuzzer_path):
"""Sets sanitizer options based on .options file overrides."""
engine_common.process_sanitizer_options_overrides(fuzzer_path)
sanitizer_options_var = environment.get_current_memory_tool_var()
sanitizer_options = environment.get_memory_tool_options(
sanitizer_options_var, {})
environment.set_memory_tool_options(sanitizer_options_var, sanitizer_options) | Sets sanitizer options based on .options file overrides. |
157,282 | from collections import namedtuple
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
StrategyCombination = namedtuple('StrategyCombination',
'strategy_name probability')
class StrategyPool:
"""Object used to keep track of which strategies the launcher should attempt
to enable."""
def __init__(self):
"""Empty set representing empty strategy pool."""
self.strategy_names = set()
def add_strategy(self, strategy_tuple):
"""Add a strategy into our existing strategy pool unless it is disabled."""
if strategy_tuple.name not in environment.get_value('DISABLED_STRATEGIES',
'').split(','):
self.strategy_names.add(strategy_tuple.name)
def do_strategy(self, strategy_tuple):
"""Boolean value representing whether or not a strategy is in our strategy
pool."""
return strategy_tuple.name in self.strategy_names
def do_strategy(strategy_tuple):
"""Return whether or not to use a given strategy."""
return engine_common.decide_with_probability(
engine_common.get_strategy_probability(strategy_tuple.name,
strategy_tuple.probability))
def generate_default_strategy_pool(strategy_list, use_generator):
"""Return a strategy pool representing a selection of strategies for launcher
to consider.
Select strategies according to default strategy selection method."""
pool = StrategyPool()
# If use_generator is enabled, decide whether to include radamsa or no
# generator (mutually exclusive).
if use_generator:
choose_generator(pool)
# Decide whether or not to add non-generator strategies according to
# probability parameters.
for value in [
strategy_entry for strategy_entry in strategy_list
if strategy_entry not in GENERATORS
]:
if do_strategy(value):
pool.add_strategy(value)
logs.log('Strategy pool was generated according to default parameters. '
'Chosen strategies: ' + ', '.join(pool.strategy_names))
return pool
The provided code snippet includes necessary dependencies for implementing the `generate_weighted_strategy_pool` function. Write a Python function `def generate_weighted_strategy_pool(strategy_list, use_generator, engine_name)` to solve the following problem:
Generate a strategy pool based on probability distribution from multi armed bandit experimentation.
Here is the function:
def generate_weighted_strategy_pool(strategy_list, use_generator, engine_name):
"""Generate a strategy pool based on probability distribution from multi armed
bandit experimentation."""
# If weighted strategy selection is enabled, there will be a distribution
# stored in the environment.
distribution = environment.get_value('STRATEGY_SELECTION_DISTRIBUTION')
selection_method = environment.get_value(
'STRATEGY_SELECTION_METHOD', default_value='default')
# Otherwise if weighted strategy selection is not enabled (strategy selection
# method is default) or if we cannot query properly, generate strategy
# pool according to default parameters. We pass the combined list of
# multi-armed bandit strategies and manual strategies for consideration in
# the default strategy selection process.
if not distribution or selection_method == 'default':
return generate_default_strategy_pool(strategy_list, use_generator)
# Change the distribution to a list of named tuples rather than a list of
# dictionaries so that we can use the random_weighted_choice function. Filter
# out probability entries from other engines.
distribution_tuples = [
StrategyCombination(
strategy_name=elem['strategy_name'], probability=elem['probability'])
for elem in distribution
if elem['engine'] == engine_name
]
if not distribution_tuples:
logs.log_warn('Tried to generate a weighted strategy pool, but do not have '
'strategy probabilities for %s fuzzing engine.' % engine_name)
return generate_default_strategy_pool(strategy_list, use_generator)
strategy_selection = utils.random_weighted_choice(distribution_tuples,
'probability')
strategy_name = strategy_selection.strategy_name
chosen_strategies = strategy_name.split(',')
pool = StrategyPool()
for strategy_tuple in strategy_list:
if strategy_tuple.name in chosen_strategies:
pool.add_strategy(strategy_tuple)
# We consider certain strategies separately as those are only supported by a
# small number of fuzz targets and should be used heavily when available.
for value in [
strategy_entry for strategy_entry in strategy_list
if strategy_entry.manually_enable
]:
if do_strategy(value):
pool.add_strategy(value)
logs.log('Strategy pool was generated according to weighted distribution. '
'Chosen strategies: ' + ', '.join(pool.strategy_names))
return pool | Generate a strategy pool based on probability distribution from multi armed bandit experimentation. |
157,283 | import os
import random
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `get_corpus_directory` function. Write a Python function `def get_corpus_directory(input_directory, project_qualified_name)` to solve the following problem:
Get the corpus directory given a project qualified fuzz target name.
Here is the function:
def get_corpus_directory(input_directory, project_qualified_name):
"""Get the corpus directory given a project qualified fuzz target name."""
corpus_directory = os.path.join(input_directory, project_qualified_name)
if environment.is_trusted_host():
from clusterfuzz._internal.bot.untrusted_runner import file_host
corpus_directory = file_host.rebase_to_worker_root(corpus_directory)
# Create corpus directory if it does not exist already.
if environment.is_trusted_host():
from clusterfuzz._internal.bot.untrusted_runner import file_host
file_host.create_directory(corpus_directory, create_intermediates=True)
else:
shell.create_directory(corpus_directory)
return corpus_directory | Get the corpus directory given a project qualified fuzz target name. |
157,284 | import os
import random
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils
from clusterfuzz._internal.datastore import data_types
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import shell
class BuiltinFuzzerError(Exception):
"""Exception that should be thrown when there is an issue preventing a builtin
fuzzer from running, or if there is a very unusual exception encountered
during a run."""
The provided code snippet includes necessary dependencies for implementing the `_get_fuzzer_path` function. Write a Python function `def _get_fuzzer_path(target_list, fuzzer_name)` to solve the following problem:
Return the full fuzzer path and actual binary name of |fuzzer_name|.
Here is the function:
def _get_fuzzer_path(target_list, fuzzer_name):
"""Return the full fuzzer path and actual binary name of |fuzzer_name|."""
fuzzer_filename = environment.get_executable_filename(fuzzer_name)
for path in target_list:
if os.path.basename(path) == fuzzer_filename:
return path
raise BuiltinFuzzerError('Failed to find chosen target ' + fuzzer_name) | Return the full fuzzer path and actual binary name of |fuzzer_name|. |
157,285 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
class LibFuzzerRunner(new_process.ModifierProcessRunnerMixin,
new_process.UnicodeProcessRunner, LibFuzzerCommon):
"""libFuzzer runner (when minijail is not used)."""
def __init__(self, executable_path, default_args=None):
"""Inits the LibFuzzerRunner.
Args:
executable_path: Path to the fuzzer executable.
default_args: Default arguments to always pass to the fuzzer.
"""
super().__init__(executable_path=executable_path, default_args=default_args)
def fuzz(self,
corpus_directories,
fuzz_timeout,
artifact_prefix=None,
additional_args=None,
extra_env=None):
"""LibFuzzerCommon.fuzz override."""
additional_args = copy.copy(additional_args)
if additional_args is None:
additional_args = []
return LibFuzzerCommon.fuzz(self, corpus_directories, fuzz_timeout,
artifact_prefix, additional_args, extra_env)
class FuchsiaUndercoatLibFuzzerRunner(new_process.UnicodeProcessRunner,
LibFuzzerCommon):
"""libFuzzer runner (when Fuchsia is the target platform, and undercoat
is used)."""
# Unfortunately the time to transfer corpora cannot be distinguished from time
# to run the fuzzer, so we need to pad the timeouts we enforce here by an
# upper limit on typical corpora transfer times to avoid prematurely killing a
# perfectly healthy fuzz run. For some typical stats, see fxbug.dev/94029; we
# go much higher than that to account for variability in the virtualized
# environment, and because this is after all intended solely as a second line
# of defense.
TIMEOUT_PADDING = 30 * 60
def __init__(self, executable_path, instance_handle, default_args=None):
# An instance_handle from undercoat is required, and should be set up by the
# build_manager.
# Note: In this case executable_path is simply `package/fuzzer`
super().__init__(executable_path=executable_path, default_args=default_args)
self.handle = instance_handle
def _corpus_directories_libfuzzer(self, corpus_directories):
"""Returns the corpus directory paths expected by libfuzzer itself."""
return [
self._target_corpus_path(os.path.basename(corpus_dir))
for corpus_dir in corpus_directories
]
def _new_corpus_dir_host(self, corpus_directories):
"""Returns the path of the 'new' corpus directory on the host."""
return corpus_directories[0]
def _new_corpus_dir_target(self, corpus_directories):
"""Returns the path of the 'new' corpus directory on the target."""
return self._target_corpus_path(
os.path.basename(self._new_corpus_dir_host(corpus_directories)))
def _target_corpus_path(self, corpus_name):
"""Returns the path of a given corpus directory on the target."""
return 'data/corpus/' + corpus_name
def _push_corpora_from_host_to_target(self, corpus_directories):
# Push corpus directories to the device.
self._clear_all_target_corpora()
logs.log('Push corpora from host to target.')
for corpus_dir in corpus_directories:
undercoat.put_data(self.handle, self.executable_path, corpus_dir,
'data/corpus')
def _pull_new_corpus_from_target_to_host(self, corpus_directories):
"""Pull corpus directories from device to host."""
# Appending '/*' indicates we want all the *files* in the target's
# directory, rather than the directory itself.
logs.log('Fuzzer ran; pulling down corpus')
new_corpus_files_target = self._new_corpus_dir_target(
corpus_directories) + '/*'
undercoat.get_data(self.handle, self.executable_path,
new_corpus_files_target,
self._new_corpus_dir_host(corpus_directories))
def _clear_all_target_corpora(self):
"""Clears out all the corpora on the target."""
logs.log('Clearing corpora on target')
# prepare_fuzzer resets the data/ directory
undercoat.prepare_fuzzer(self.handle, self.executable_path)
def _ensure_target_exists(self):
"""Check that the target fuzzer exists, raising an error if it does not.
We do this check by looking at the list of fuzzers, instead of relying on
an error from undercoat, because in some cases (e.g. regression tasks) it
is an expected error that we wish to recover from. Additionally, we can't
do this check earlier because we need an online target system to query."""
targets = undercoat.list_fuzzers(self.handle)
# These fuzzers are used for integration tests but not returned by
# list_fuzzers because we don't want them to be run in production.
targets += [
'example-fuzzers/crash_fuzzer', 'example-fuzzers/overflow_fuzzer'
]
if self.executable_path not in targets:
raise testcase_manager.TargetNotFoundError(
f'Failed to find target {self.executable_path}')
def get_total_timeout(self, timeout):
"""LibFuzzerCommon.fuzz override."""
return super().get_total_timeout(timeout) + self.TIMEOUT_PADDING
def fuzz(self,
corpus_directories,
fuzz_timeout,
artifact_prefix=None,
additional_args=None,
extra_env=None):
"""LibFuzzerCommon.fuzz override."""
arguments = fuzzer_options.FuzzerArguments.from_list(additional_args)
assert arguments is not None
undercoat.prepare_fuzzer(self.handle, self.executable_path)
self._push_corpora_from_host_to_target(corpus_directories)
max_total_time = fuzz_timeout
if constants.FORK_FLAGNAME in arguments:
max_total_time -= self.LIBFUZZER_FORK_MODE_CLEAN_EXIT_TIME
assert max_total_time > 0
arguments[constants.MAX_TOTAL_TIME_FLAGNAME] = int(max_total_time)
arguments[constants.PRINT_FINAL_STATS_FLAGNAME] = 1
# Run the fuzzer.
# TODO(eep): Clarify comment from previous implementation: "actually we want
# new_corpus_relative_dir_target for *each* corpus"
result = undercoat.run_fuzzer(
self.handle,
self.executable_path,
artifact_prefix,
self._corpus_directories_libfuzzer(corpus_directories) +
arguments.list(),
timeout=self.get_total_timeout(fuzz_timeout))
self._pull_new_corpus_from_target_to_host(corpus_directories)
self._clear_all_target_corpora()
return result
def merge(self,
corpus_directories,
merge_timeout,
artifact_prefix=None,
tmp_dir=None,
additional_args=None,
merge_control_file=None):
undercoat.prepare_fuzzer(self.handle, self.executable_path)
self._push_corpora_from_host_to_target(corpus_directories)
arguments = fuzzer_options.FuzzerArguments.from_list(additional_args)
assert arguments is not None
arguments[constants.MAX_TOTAL_TIME_FLAGNAME] = int(merge_timeout)
target_merge_control_file = 'data/.mergefile'
if merge_control_file:
undercoat.put_data(self.handle, self.executable_path, merge_control_file,
target_merge_control_file)
# Run merge.
arguments['merge'] = 1
arguments['merge_control_file'] = target_merge_control_file
result = undercoat.run_fuzzer(
self.handle,
self.executable_path,
None,
self._corpus_directories_libfuzzer(corpus_directories) +
arguments.list(),
timeout=self.get_total_timeout(merge_timeout))
self._pull_new_corpus_from_target_to_host(corpus_directories)
if merge_control_file:
undercoat.put_data(self.handle, self.executable_path,
target_merge_control_file, merge_control_file)
self._clear_all_target_corpora()
return result
def run_single_testcase(self,
testcase_path,
timeout=None,
additional_args=None):
"""Run a single testcase."""
#TODO(eep): Are all these copy.copy() calls still necessary?
additional_args = copy.copy(additional_args)
if additional_args is None:
additional_args = []
self._ensure_target_exists()
# We need to push the testcase to the device and pass in the name.
testcase_path_name = os.path.basename(os.path.normpath(testcase_path))
undercoat.prepare_fuzzer(self.handle, self.executable_path)
undercoat.put_data(self.handle, self.executable_path, testcase_path,
'data/')
if timeout:
timeout = self.get_total_timeout(timeout)
result = undercoat.run_fuzzer(
self.handle,
self.executable_path,
None, ['data/' + testcase_path_name] + additional_args,
timeout=timeout)
return result
def minimize_crash(self,
testcase_path,
output_path,
timeout,
artifact_prefix=None,
additional_args=None):
arguments = fuzzer_options.FuzzerArguments.from_list(additional_args)
assert arguments is not None
arguments[constants.MINIMIZE_CRASH_FLAGNAME] = 1
arguments[constants.MAX_TOTAL_TIME_FLAGNAME] = int(
self.get_minimize_total_time(timeout))
target_artifact_prefix = 'data/'
target_minimized_file = 'final-minimized-crash'
min_file_fullpath = target_artifact_prefix + target_minimized_file
arguments[constants.EXACT_ARTIFACT_PATH_FLAGNAME] = str(min_file_fullpath)
# We need to push the testcase to the device and pass in the name.
testcase_path_name = os.path.basename(os.path.normpath(testcase_path))
undercoat.prepare_fuzzer(self.handle, self.executable_path)
undercoat.put_data(self.handle, self.executable_path, testcase_path,
'data/')
output_dir = os.path.dirname(output_path)
result = undercoat.run_fuzzer(
self.handle,
self.executable_path,
output_dir, ['data/' + testcase_path_name] + arguments.list(),
timeout=self.get_total_timeout(timeout))
# The minimized artifact is automatically fetched if minimization succeeded,
# but this isn't always the case so let's just always fetch a new copy
undercoat.get_data(self.handle, self.executable_path, min_file_fullpath,
output_dir)
shutil.move(os.path.join(output_dir, target_minimized_file), output_path)
return result
class MinijailLibFuzzerRunner(new_process.UnicodeProcessRunnerMixin,
engine_common.MinijailEngineFuzzerRunner,
LibFuzzerCommon):
"""Minijail libFuzzer runner."""
def __init__(self, executable_path, chroot, default_args=None):
"""Inits the LibFuzzerRunner.
Args:
executable_path: Path to the fuzzer executable.
chroot: A MinijailChroot.
default_args: Default arguments to always pass to the fuzzer.
"""
super().__init__(
executable_path=executable_path,
chroot=chroot,
default_args=default_args)
def get_testcase_path(self, log_lines):
"""Get testcase path from log lines."""
path = LibFuzzerCommon.get_testcase_path(self, log_lines)
if not path:
return path
for binding in self.chroot.bindings:
if path.startswith(binding.dest_path):
return os.path.join(binding.src_path,
os.path.relpath(path, binding.dest_path))
raise LibFuzzerError('Invalid testcase path ' + path)
def _get_chroot_corpus_paths(self, corpus_directories):
"""Return chroot relative paths for the given corpus directories.
Args:
corpus_directories: A list of host corpus directories.
Returns:
A list of chroot relative paths.
"""
return [self._get_chroot_directory(path) for path in corpus_directories]
def _get_chroot_directory(self, directory_path):
"""Return chroot relative path for the given directory.
Args:
directory_path: A path to the directory to be bound.
Returns:
A chroot relative path for the given directory.
"""
binding = self.chroot.get_binding(directory_path)
if not binding:
raise LibFuzzerError(
f'Failed to get chroot binding for "{directory_path}".')
return binding.dest_path
def _bind_corpus_dirs(self, corpus_directories):
"""Bind corpus directories to the minijail chroot.
Also makes sure that the directories are world writeable.
Args:
corpus_directories: A list of corpus paths.
"""
for corpus_directory in corpus_directories:
target_dir = '/' + os.path.basename(corpus_directory)
self.chroot.add_binding(
minijail.ChrootBinding(corpus_directory, target_dir, writeable=True))
def fuzz(self,
corpus_directories,
fuzz_timeout,
artifact_prefix=None,
additional_args=None,
extra_env=None):
"""LibFuzzerCommon.fuzz override."""
bind_directories = copy.copy(corpus_directories)
if artifact_prefix:
bind_directories.append(artifact_prefix)
ld_preload = None
if extra_env and 'LD_PRELOAD' in extra_env:
ld_preload = extra_env['LD_PRELOAD']
bind_directories.append(os.path.dirname(ld_preload))
self._bind_corpus_dirs(bind_directories)
corpus_directories = self._get_chroot_corpus_paths(corpus_directories)
if ld_preload:
extra_env['LD_PRELOAD'] = os.path.join(
self._get_chroot_directory(os.path.dirname(ld_preload)),
os.path.basename(ld_preload))
if artifact_prefix:
artifact_prefix = self._get_chroot_directory(artifact_prefix)
return LibFuzzerCommon.fuzz(
self,
corpus_directories,
fuzz_timeout,
artifact_prefix=artifact_prefix,
additional_args=additional_args,
extra_env=extra_env)
def merge(self,
corpus_directories,
merge_timeout,
artifact_prefix=None,
tmp_dir=None,
additional_args=None,
merge_control_file=None):
"""LibFuzzerCommon.merge override."""
additional_args = copy.copy(additional_args)
if additional_args is None:
additional_args = []
bind_directories = copy.copy(corpus_directories)
if artifact_prefix:
bind_directories.append(artifact_prefix)
self._bind_corpus_dirs(bind_directories)
corpus_directories = self._get_chroot_corpus_paths(corpus_directories)
if artifact_prefix:
artifact_prefix = self._get_chroot_directory(artifact_prefix)
chroot_merge_control_file = None
if merge_control_file:
merge_control_dir = os.path.dirname(merge_control_file)
self._bind_corpus_dirs([merge_control_dir])
chroot_merge_control_dir = self._get_chroot_directory(merge_control_dir)
chroot_merge_control_file = os.path.join(
chroot_merge_control_dir,
os.path.relpath(merge_control_file, merge_control_dir))
return LibFuzzerCommon.merge(
self,
corpus_directories,
merge_timeout,
artifact_prefix=artifact_prefix,
tmp_dir=None, # Use default in minijail.
additional_args=additional_args,
merge_control_file=chroot_merge_control_file)
def run_single_testcase(self,
testcase_path,
timeout=None,
additional_args=None):
"""LibFuzzerCommon.run_single_testcase override."""
with self._chroot_testcase(testcase_path) as chroot_testcase_path:
return LibFuzzerCommon.run_single_testcase(self, chroot_testcase_path,
timeout, additional_args)
def minimize_crash(self,
testcase_path,
output_path,
timeout,
artifact_prefix=None,
additional_args=None):
"""LibFuzzerCommon.minimize_crash override."""
with self._chroot_testcase(testcase_path) as chroot_testcase_path:
chroot_output_name = 'minimized_crash'
chroot_output_path = '/' + chroot_output_name
host_output_path = os.path.join(self.chroot.directory, chroot_output_name)
result = LibFuzzerCommon.minimize_crash(
self,
chroot_testcase_path,
chroot_output_path,
timeout,
artifact_prefix=constants.TMP_ARTIFACT_PREFIX_ARGUMENT,
additional_args=additional_args)
if os.path.exists(host_output_path):
shutil.copy(host_output_path, output_path)
return result
def cleanse_crash(self,
testcase_path,
output_path,
timeout,
artifact_prefix=None,
additional_args=None):
"""LibFuzzerCommon.cleanse_crash override."""
with self._chroot_testcase(testcase_path) as chroot_testcase_path:
chroot_output_name = 'cleanse_crash'
chroot_output_path = '/' + chroot_output_name
host_output_path = os.path.join(self.chroot.directory, chroot_output_name)
result = LibFuzzerCommon.cleanse_crash(
self,
chroot_testcase_path,
chroot_output_path,
timeout,
artifact_prefix=constants.TMP_ARTIFACT_PREFIX_ARGUMENT,
additional_args=additional_args)
if os.path.exists(host_output_path):
shutil.copy(host_output_path, output_path)
return result
class AndroidLibFuzzerRunner(new_process.UnicodeProcessRunner, LibFuzzerCommon):
"""Android libFuzzer runner."""
# This temp directory is used by libFuzzer merge tool. DONT CHANGE.
LIBFUZZER_TEMP_DIR = '/data/local/tmp'
def __init__(self, executable_path, build_directory, default_args=None):
"""Inits the AndroidLibFuzzerRunner.
Args:
executable_path: Path to the fuzzer executable.
build_directory: A MinijailChroot.
default_args: Default arguments to always pass to the fuzzer.
"""
super().__init__(
executable_path=android.adb.get_adb_path(),
default_args=self._get_default_args(executable_path, default_args))
android.adb.create_directory_if_needed(self.LIBFUZZER_TEMP_DIR)
self.copy_local_directory_to_device(build_directory)
def _get_default_args(self, executable_path, extra_args):
"""Return a set of default arguments to pass to adb binary."""
default_args = ['shell']
# LD_LIBRARY_PATH set to search for fuzzer deps first, and then
# sanitizers if any are found.
ld_library_path = ''
if not android.settings.is_automotive():
# TODO(MHA3): Remove this auto check.
executable_dir = os.path.dirname(executable_path)
deps_path = os.path.join(self._get_device_path(executable_dir), 'lib')
ld_library_path += deps_path
memory_tool_path = android.sanitizer.get_ld_library_path_for_memory_tools(
)
if memory_tool_path:
ld_library_path += ':' + memory_tool_path
default_args.append('LD_LIBRARY_PATH=' + ld_library_path)
# Add sanitizer options.
default_args += environment.get_sanitizer_options_for_display()
default_args.append(self._get_device_path(executable_path))
if extra_args:
default_args += extra_args
return default_args
def _get_device_corpus_paths(self, corpus_directories):
"""Return device paths for the given corpus directories."""
return [self._get_device_path(path) for path in corpus_directories]
def _get_device_path(self, local_path):
"""Return device path for the given local path."""
root_directory = environment.get_root_directory()
return os.path.join(android.constants.DEVICE_FUZZING_DIR,
os.path.relpath(local_path, root_directory))
def _get_local_path(self, device_path):
"""Return local path for the given device path."""
if not device_path.startswith(android.constants.DEVICE_FUZZING_DIR + '/'):
logs.log_error('Bad device path: ' + device_path)
return None
root_directory = environment.get_root_directory()
return os.path.join(
root_directory,
os.path.relpath(device_path, android.constants.DEVICE_FUZZING_DIR))
def _copy_local_directories_to_device(self, local_directories):
"""Copies local directories to device."""
for local_directory in sorted(set(local_directories)):
self.copy_local_directory_to_device(local_directory)
def copy_local_directory_to_device(self, local_directory):
"""Copy local directory to device."""
device_directory = self._get_device_path(local_directory)
android.adb.remove_directory(device_directory, recreate=True)
android.adb.copy_local_directory_to_remote(local_directory,
device_directory)
def _copy_local_directories_from_device(self, local_directories):
"""Copies directories from device to local."""
for local_directory in sorted(set(local_directories)):
device_directory = self._get_device_path(local_directory)
shell.remove_directory(local_directory, recreate=True)
android.adb.copy_remote_directory_to_local(device_directory,
local_directory)
def _extract_trusty_stacktrace_from_logcat(self, logcat):
"""Finds and returns a TA stacktrace from a logcat"""
begin = android.constants.TRUSTY_STACKTRACE_BEGIN
end = android.constants.TRUSTY_STACKTRACE_END
target_idx = logcat.rfind(begin)
if target_idx != -1:
#Logcat contains kernel panic
begin = logcat[:target_idx].rfind('\n')
end_idx = target_idx + logcat[target_idx:].find('\n')
end_idx += logcat[end_idx:].find(end)
end_idx += logcat[end_idx:].find('\n')
ta_stacktrace = []
split_marker = 'trusty:log: '
for line in logcat[begin:end_idx].splitlines():
split_idx = line.find(split_marker) + len(split_marker)
ta_stacktrace.append(line[split_idx:])
return '\n'.join(ta_stacktrace)
begin = '---------'
target = 'Backtrace for thread:'
target_idx = logcat.rfind(target)
if target_idx == -1:
return 'No TA crash stacktrace found in logcat.\n'
begin_idx = logcat[:target_idx].rfind(begin)
end_idx = target_idx + logcat[target_idx:].find(end)
end_idx += logcat[end_idx:].find('\n')
return logcat[begin_idx:end_idx]
def _add_trusty_stacktrace_if_needed(self, output):
"""Add trusty stacktrace to beginning of output if found in logcat."""
if android.adb.get_device_state() == 'is-ramdump-mode:yes':
logcat = android.adb.extract_logcat_from_ramdump_and_reboot()
else:
logcat = android.logger.log_output()
ta_stacktrace = self._extract_trusty_stacktrace_from_logcat(logcat)
# Defer imports since stack_symbolizer pulls in a lot of things.
from clusterfuzz._internal.crash_analysis.stack_parsing import \
stack_symbolizer
loop = stack_symbolizer.SymbolizationLoop()
ta_stacktrace = loop.process_trusty_stacktrace(ta_stacktrace)
return '+-- Logcat excerpt: Trusted App crash stacktrace --+\
\n{ta_stacktrace}\n\n{output}\n\nLogcat:\n{logcat_output}'.format(
ta_stacktrace=ta_stacktrace, output=output, logcat_output=logcat)
def _extract_mte_stacktrace_from_logcat(self, logcat):
"""Finds and returns the MTE stacktrace from a logcat."""
begin = android.constants.MTE_STACKTRACE_BEGIN
end = android.constants.MTE_STACKTRACE_END
target_idx = logcat.rfind(begin)
if target_idx != -1:
# Logcat contains MTE crash
begin = logcat[:target_idx].rfind('\n')
end_idx = target_idx + logcat[target_idx:].find('\n')
end_idx += logcat[end_idx:].find(end)
end_idx += logcat[end_idx:].find('\n')
mte_stacktrace = ['MTE Stacktrace:']
for line in logcat[begin:end_idx].splitlines():
mte_stacktrace.append(line)
return '\n'.join(mte_stacktrace)
begin = '---------'
target = 'Backtrace for thread:'
target_idx = logcat.rfind(target)
if target_idx == -1:
return 'No MTE crash stacktrace found in logcat.\n'
begin_idx = logcat[:target_idx].rfind(begin)
end_idx = target_idx + logcat[target_idx:].find(end)
end_idx += logcat[end_idx:].find('\n')
return logcat[begin_idx:end_idx]
def _add_mte_stacktrace_if_needed(self, output):
"""Add mte stacktrace to beginning of output if found in logcat."""
logcat = android.logger.log_output()
mte_stacktrace = self._extract_mte_stacktrace_from_logcat(logcat)
return '+-- Logcat excerpt: MTE crash stacktrace --+\
\n{mte_stacktrace}\n\n{output}\n\nLogcat:\n{logcat_output}'.format(
mte_stacktrace=mte_stacktrace, output=output, logcat_output=logcat)
def _add_logcat_output_if_needed(self, output):
"""Add logcat output to end of output to capture crashes from related
processes if current output has no sanitizer crash."""
if 'Sanitizer: ' in output:
return output
if environment.is_android_emulator():
return self._add_trusty_stacktrace_if_needed(output)
if environment.is_android() and android.settings.is_mte_build():
return self._add_mte_stacktrace_if_needed(output)
return '{output}\n\nLogcat:\n{logcat_output}'.format(
output=output, logcat_output=android.logger.log_output())
def _device_file(self, file_path):
"""Context manager for device files.
Args:
file_path: Host path to file.
Returns:
Path to file on device.
"""
device_file_path = self._get_device_path(file_path)
android.adb.copy_local_file_to_remote(file_path, device_file_path)
yield device_file_path
# Cleanup
android.adb.remove_file(device_file_path)
def get_testcase_path(self, log_lines):
"""Get testcase path from log lines."""
path = LibFuzzerCommon.get_testcase_path(self, log_lines)
if not path:
return path
return self._get_local_path(path)
def fuzz(self,
corpus_directories,
fuzz_timeout,
artifact_prefix=None,
additional_args=None,
extra_env=None):
"""LibFuzzerCommon.fuzz override."""
android.logger.clear_log()
sync_directories = copy.copy(corpus_directories)
if artifact_prefix:
sync_directories.append(artifact_prefix)
self._copy_local_directories_to_device(sync_directories)
corpus_directories = self._get_device_corpus_paths(corpus_directories)
if artifact_prefix:
artifact_prefix = self._get_device_path(artifact_prefix)
# Extract local dict path from arguments list and subsitute with device one.
arguments = fuzzer_options.FuzzerArguments.from_list(additional_args)
assert arguments is not None
dict_path = arguments.get(
constants.DICT_FLAGNAME, default=None, constructor=str)
if dict_path:
device_dict_path = self._get_device_path(dict_path)
android.adb.copy_local_file_to_remote(dict_path, device_dict_path)
arguments[constants.DICT_FLAGNAME] = device_dict_path
result = LibFuzzerCommon.fuzz(
self,
corpus_directories,
fuzz_timeout,
artifact_prefix=artifact_prefix,
additional_args=arguments.list(),
extra_env=extra_env)
result.output = self._add_logcat_output_if_needed(result.output)
self._copy_local_directories_from_device(sync_directories)
return result
def merge(self,
corpus_directories,
merge_timeout,
artifact_prefix=None,
tmp_dir=None,
additional_args=None,
merge_control_file=None):
"""LibFuzzerCommon.merge override."""
additional_args = copy.copy(additional_args)
if additional_args is None:
additional_args = []
sync_directories = copy.copy(corpus_directories)
if artifact_prefix:
sync_directories.append(artifact_prefix)
device_merge_control_file = None
if merge_control_file:
device_merge_control_file = self._get_device_path(merge_control_file)
merge_control_dir = os.path.dirname(merge_control_file)
sync_directories.append(merge_control_dir)
self._copy_local_directories_to_device(sync_directories)
corpus_directories = self._get_device_corpus_paths(corpus_directories)
if artifact_prefix:
artifact_prefix = self._get_device_path(artifact_prefix)
result = LibFuzzerCommon.merge(
self,
corpus_directories,
merge_timeout,
artifact_prefix=artifact_prefix,
tmp_dir=None,
additional_args=additional_args,
merge_control_file=device_merge_control_file)
self._copy_local_directories_from_device(sync_directories)
return result
def run_single_testcase(self,
testcase_path,
timeout=None,
additional_args=None):
"""LibFuzzerCommon.run_single_testcase override."""
android.logger.clear_log()
with self._device_file(testcase_path) as device_testcase_path:
result = LibFuzzerCommon.run_single_testcase(self, device_testcase_path,
timeout, additional_args)
result.output = self._add_logcat_output_if_needed(result.output)
return result
def minimize_crash(self,
testcase_path,
output_path,
timeout,
artifact_prefix=None,
additional_args=None):
"""LibFuzzerCommon.minimize_crash override."""
with self._device_file(testcase_path) as device_testcase_path:
device_output_path = self._get_device_path(output_path)
result = LibFuzzerCommon.minimize_crash(
self,
device_testcase_path,
device_output_path,
timeout,
artifact_prefix=constants.TMP_ARTIFACT_PREFIX_ARGUMENT,
additional_args=additional_args)
if android.adb.file_exists(device_output_path):
android.adb.copy_remote_file_to_local(device_output_path, output_path)
return result
def cleanse_crash(self,
testcase_path,
output_path,
timeout,
artifact_prefix=None,
additional_args=None):
"""LibFuzzerCommon.cleanse_crash override."""
with self._device_file(testcase_path) as device_testcase_path:
device_output_path = self._get_device_path(output_path)
result = LibFuzzerCommon.cleanse_crash(
self,
device_testcase_path,
device_output_path,
timeout,
artifact_prefix=constants.TMP_ARTIFACT_PREFIX_ARGUMENT,
additional_args=additional_args)
if android.adb.file_exists(device_output_path):
android.adb.copy_remote_file_to_local(device_output_path, output_path)
return result
The provided code snippet includes necessary dependencies for implementing the `get_runner` function. Write a Python function `def get_runner(fuzzer_path, temp_dir=None, use_minijail=None)` to solve the following problem:
Get a libfuzzer runner.
Here is the function:
def get_runner(fuzzer_path, temp_dir=None, use_minijail=None):
"""Get a libfuzzer runner."""
if use_minijail is None:
use_minijail = environment.get_value('USE_MINIJAIL')
if use_minijail is False:
# If minijail is explicitly disabled, set the environment variable as well.
environment.set_value('USE_MINIJAIL', False)
if temp_dir is None:
temp_dir = fuzzer_utils.get_temp_dir()
build_dir = environment.get_value('BUILD_DIR')
dataflow_build_dir = environment.get_value('DATAFLOW_BUILD_DIR')
is_android = environment.is_android()
is_fuchsia = environment.platform() == 'FUCHSIA'
if not is_fuchsia:
# To ensure that we can run the fuzz target.
os.chmod(fuzzer_path, 0o755)
is_chromeos_system_job = environment.is_chromeos_system_job()
if is_chromeos_system_job:
minijail_chroot = minijail.ChromeOSChroot(build_dir)
elif use_minijail:
minijail_chroot = minijail.MinijailChroot(base_dir=temp_dir)
if use_minijail or is_chromeos_system_job:
# While it's possible for dynamic binaries to run without this, they need
# to be accessible for symbolization etc. For simplicity we bind BUILD_DIR
# to the same location within the chroot, which leaks the directory
# structure of CF but this shouldn't be a big deal.
minijail_chroot.add_binding(
minijail.ChrootBinding(build_dir, build_dir, writeable=False))
if dataflow_build_dir:
minijail_chroot.add_binding(
minijail.ChrootBinding(
dataflow_build_dir, dataflow_build_dir, writeable=False))
# Also bind the build dir to /out to make it easier to hardcode references
# to data files.
minijail_chroot.add_binding(
minijail.ChrootBinding(build_dir, '/out', writeable=False))
minijail_bin = os.path.join(minijail_chroot.directory, 'bin')
shell.create_directory(minijail_bin)
# Set up /bin with llvm-symbolizer to allow symbolized stacktraces.
# Don't copy if it already exists (e.g. ChromeOS chroot jail).
llvm_symbolizer_source_path = environment.get_llvm_symbolizer_path()
llvm_symbolizer_destination_path = os.path.join(minijail_bin,
'llvm-symbolizer')
if not os.path.exists(llvm_symbolizer_destination_path):
shutil.copy(llvm_symbolizer_source_path, llvm_symbolizer_destination_path)
# copy /bin/sh, necessary for system().
if not environment.is_chromeos_system_job():
# The chroot has its own shell we don't need to copy (and probably
# shouldn't because of library differences).
shutil.copy(os.path.realpath('/bin/sh'), os.path.join(minijail_bin, 'sh'))
runner = MinijailLibFuzzerRunner(fuzzer_path, minijail_chroot)
elif is_fuchsia:
instance_handle = environment.get_value('FUCHSIA_INSTANCE_HANDLE')
if not instance_handle:
raise undercoat.UndercoatError('Instance handle not provided.')
runner = FuchsiaUndercoatLibFuzzerRunner(fuzzer_path, instance_handle)
elif is_android:
runner = AndroidLibFuzzerRunner(fuzzer_path, build_dir)
else:
runner = LibFuzzerRunner(fuzzer_path)
return runner | Get a libfuzzer runner. |
157,286 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `copy_from_corpus` function. Write a Python function `def copy_from_corpus(dest_corpus_path, src_corpus_path, num_testcases)` to solve the following problem:
Choose |num_testcases| testcases from the src corpus directory (and its subdirectories) and copy it into the dest directory.
Here is the function:
def copy_from_corpus(dest_corpus_path, src_corpus_path, num_testcases):
"""Choose |num_testcases| testcases from the src corpus directory (and its
subdirectories) and copy it into the dest directory."""
src_corpus_files = []
for root, _, files in shell.walk(src_corpus_path):
for f in files:
src_corpus_files.append(os.path.join(root, f))
# There is no reason to preserve structure of src_corpus_path directory.
for i, to_copy in enumerate(random.sample(src_corpus_files, num_testcases)):
shutil.copy(os.path.join(to_copy), os.path.join(dest_corpus_path, str(i))) | Choose |num_testcases| testcases from the src corpus directory (and its subdirectories) and copy it into the dest directory. |
157,287 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `strip_fuzzing_arguments` function. Write a Python function `def strip_fuzzing_arguments(arguments, is_merge=False)` to solve the following problem:
Remove arguments used during fuzzing.
Here is the function:
def strip_fuzzing_arguments(arguments, is_merge=False):
"""Remove arguments used during fuzzing."""
args = fuzzer_options.FuzzerArguments.from_list(arguments)
for argument in [
# Remove as it overrides `-merge` argument.
constants.FORK_FLAGNAME, # It overrides `-merge` argument.
# Remove as it may shrink the testcase.
constants.MAX_LEN_FLAGNAME, # This may shrink the testcases.
# Remove any existing runs argument as we will create our own for
# reproduction.
constants.RUNS_FLAGNAME, # Make sure we don't have any '-runs' argument.
# Remove the following flags/arguments that are only used for fuzzing.
constants.DATA_FLOW_TRACE_FLAGNAME,
constants.DICT_FLAGNAME,
constants.FOCUS_FUNCTION_FLAGNAME,
]:
if argument in args:
del args[argument]
# Value profile is needed during corpus merge, so do not remove if set.
if not is_merge:
if constants.VALUE_PROFILE_FLAGNAME in args:
del args[constants.VALUE_PROFILE_FLAGNAME]
return args.list() | Remove arguments used during fuzzing. |
157,288 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `fix_timeout_argument_for_reproduction` function. Write a Python function `def fix_timeout_argument_for_reproduction(arguments)` to solve the following problem:
Changes timeout argument for reproduction. This is slightly less than the |TEST_TIMEOUT| value for the job.
Here is the function:
def fix_timeout_argument_for_reproduction(arguments):
"""Changes timeout argument for reproduction. This is slightly less than the
|TEST_TIMEOUT| value for the job."""
args = fuzzer_options.FuzzerArguments.from_list(arguments)
if constants.TIMEOUT_FLAGNAME in args:
del args[constants.TIMEOUT_FLAGNAME]
# Leave 5 sec buffer for report processing.
adjusted_test_timeout = max(
1,
environment.get_value('TEST_TIMEOUT', constants.DEFAULT_TIMEOUT_LIMIT) -
constants.REPORT_PROCESSING_TIME)
args[constants.TIMEOUT_FLAGNAME] = adjusted_test_timeout
return args.list() | Changes timeout argument for reproduction. This is slightly less than the |TEST_TIMEOUT| value for the job. |
157,289 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `parse_log_stats` function. Write a Python function `def parse_log_stats(log_lines)` to solve the following problem:
Parse libFuzzer log output.
Here is the function:
def parse_log_stats(log_lines):
"""Parse libFuzzer log output."""
log_stats = {}
# Parse libFuzzer generated stats (`-print_final_stats=1`).
stats_regex = re.compile(r'stat::([A-Za-z_]+):\s*([^\s]+)')
for line in log_lines:
match = stats_regex.match(line)
if not match:
continue
value = match.group(2)
if not value.isdigit():
# We do not expect any non-numeric stats from libFuzzer, skip those.
logs.log_error('Corrupted stats reported by libFuzzer: "%s".' % line)
continue
value = int(value)
log_stats[match.group(1)] = value
if log_stats.get('new_units_added') is not None:
# 'new_units_added' value will be overwritten after corpus merge step, but
# the initial number of units generated is an interesting data as well.
log_stats['new_units_generated'] = log_stats['new_units_added']
return log_stats | Parse libFuzzer log output. |
157,290 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `set_sanitizer_options` function. Write a Python function `def set_sanitizer_options(fuzzer_path, fuzz_options=None)` to solve the following problem:
Sets sanitizer options based on .options file overrides, FuzzOptions (if provided), and what this script requires.
Here is the function:
def set_sanitizer_options(fuzzer_path, fuzz_options=None):
"""Sets sanitizer options based on .options file overrides, FuzzOptions (if
provided), and what this script requires."""
engine_common.process_sanitizer_options_overrides(fuzzer_path)
sanitizer_options_var = environment.get_current_memory_tool_var()
sanitizer_options = environment.get_memory_tool_options(
sanitizer_options_var, {})
sanitizer_options['exitcode'] = constants.TARGET_ERROR_EXITCODE
if fuzz_options and fuzz_options.use_dataflow_tracing:
# Focus function feature does not work without symbolization.
sanitizer_options['symbolize'] = 1
environment.update_symbolizer_options(sanitizer_options)
environment.set_memory_tool_options(sanitizer_options_var, sanitizer_options) | Sets sanitizer options based on .options file overrides, FuzzOptions (if provided), and what this script requires. |
157,291 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
DEFAULT_MERGE_TIMEOUT = 30 * 60
The provided code snippet includes necessary dependencies for implementing the `get_fuzz_timeout` function. Write a Python function `def get_fuzz_timeout(is_mutations_run, total_timeout=None)` to solve the following problem:
Get the fuzz timeout.
Here is the function:
def get_fuzz_timeout(is_mutations_run, total_timeout=None):
"""Get the fuzz timeout."""
fuzz_timeout = (
engine_common.get_hard_timeout(total_timeout=total_timeout) -
engine_common.get_merge_timeout(DEFAULT_MERGE_TIMEOUT))
if is_mutations_run:
fuzz_timeout -= engine_common.get_new_testcase_mutations_timeout()
return fuzz_timeout | Get the fuzz timeout. |
157,292 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
def is_sha1_hash(possible_hash):
"""Returns True if |possible_hash| looks like a valid sha1 hash."""
if len(possible_hash) != 40:
return False
hexdigits_set = set(string.hexdigits)
return all(char in hexdigits_set for char in possible_hash)
The provided code snippet includes necessary dependencies for implementing the `move_mergeable_units` function. Write a Python function `def move_mergeable_units(merge_directory, corpus_directory)` to solve the following problem:
Move new units in |merge_directory| into |corpus_directory|.
Here is the function:
def move_mergeable_units(merge_directory, corpus_directory):
"""Move new units in |merge_directory| into |corpus_directory|."""
initial_units = {
os.path.basename(filename)
for filename in shell.get_files_list(corpus_directory)
}
for unit_path in shell.get_files_list(merge_directory):
unit_name = os.path.basename(unit_path)
if unit_name in initial_units and is_sha1_hash(unit_name):
continue
dest_path = os.path.join(corpus_directory, unit_name)
shell.move(unit_path, dest_path) | Move new units in |merge_directory| into |corpus_directory|. |
157,293 | import collections
import contextlib
import copy
import os
import random
import re
import shutil
import string
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot import testcase_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options as fuzzer_options
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.libFuzzer import constants
from clusterfuzz._internal.bot.fuzzers.libFuzzer.peach import pits
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.platforms.fuchsia import undercoat
from clusterfuzz._internal.system import archive
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import minijail
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
MAX_VALUE_FOR_MAX_LENGTH = 10000
StrategyInfo = collections.namedtuple('StrategiesInfo', [
'fuzzing_strategies',
'arguments',
'additional_corpus_dirs',
'extra_env',
'use_dataflow_tracing',
'is_mutations_run',
])
DATAFLOW_TRACE_DIR_SUFFIX = '_dft'
def create_corpus_directory(name):
"""Create a corpus directory with a give name in temp directory and return its
full path."""
new_corpus_directory = os.path.join(fuzzer_utils.get_temp_dir(), name)
engine_common.recreate_directory(new_corpus_directory)
return new_corpus_directory
def use_peach_mutator(extra_env, grammar):
"""Decide whether or not to use peach mutator, and set up all of the
environment variables necessary to do so."""
# TODO(mpherman): Include architecture info in job definition and exclude
# i386.
if environment.is_lib() or not is_linux_asan():
return False
if not grammar:
return False
pit_path = pits.get_path(grammar)
if not pit_path:
return False
# Set title and pit environment variables
extra_env['PIT_FILENAME'] = pit_path
extra_env['PIT_TITLE'] = grammar
# Extract zip of peach mutator code.
peach_dir = os.path.join(environment.get_platform_resources_directory(),
'peach')
unzipped = os.path.join(peach_dir, 'mutator')
source = os.path.join(peach_dir, 'peach_mutator.zip')
with archive.open(source) as reader:
reader.extract_all(unzipped, trusted=True)
# Set LD_PRELOAD.
peach_path = os.path.join(unzipped, 'peach_mutator', 'src', 'peach.so')
extra_env['LD_PRELOAD'] = peach_path
# Set Python path.
new_path = [
os.path.join(unzipped, 'peach_mutator', 'src'),
os.path.join(unzipped, 'peach_mutator', 'third_party', 'peach'),
] + sys.path
extra_env['PYTHONPATH'] = os.pathsep.join(new_path)
return True
def has_existing_mutator_strategy(fuzzing_strategy):
return any(strategy in fuzzing_strategy for strategy in MUTATOR_STRATEGIES)
def should_set_fork_flag(existing_arguments, strategy_pool):
"""Returns True if fork flag should be set."""
# FIXME: Disable for now to avoid severe battery drainage. Stabilize and
# re-enable with a lower process count.
if environment.is_android():
return False
# Fork mode is not supported on Fuchsia platform.
if environment.platform() == 'FUCHSIA':
return False
# Fork mode is disabled on ephemeral bots due to a bug on the platform.
if environment.is_ephemeral():
return False
# Do not use fork mode for DFT-based fuzzing. This is needed in order to
# collect readable and actionable logs from fuzz targets running with DFT.
# If fork_server is already set by the user, let's keep it that way.
if constants.FORK_FLAGNAME in existing_arguments.flags:
return False
return strategy_pool.do_strategy(strategy.FORK_STRATEGY)
The provided code snippet includes necessary dependencies for implementing the `pick_strategies` function. Write a Python function `def pick_strategies(strategy_pool, fuzzer_path, corpus_directory, existing_arguments, grammar=None)` to solve the following problem:
Pick strategies.
Here is the function:
def pick_strategies(strategy_pool,
fuzzer_path,
corpus_directory,
existing_arguments,
grammar=None):
"""Pick strategies."""
build_directory = environment.get_value('BUILD_DIR')
fuzzing_strategies = []
arguments = fuzzer_options.FuzzerArguments({})
additional_corpus_dirs = []
# Select a generator to attempt to use for existing testcase mutations.
candidate_generator = engine_common.select_generator(strategy_pool,
fuzzer_path)
is_mutations_run = (not environment.is_ephemeral() and
candidate_generator != engine_common.Generator.NONE)
# Depends on the presense of DFSan instrumented build.
dataflow_build_dir = environment.get_value('DATAFLOW_BUILD_DIR')
use_dataflow_tracing = (
dataflow_build_dir and
strategy_pool.do_strategy(strategy.DATAFLOW_TRACING_STRATEGY))
if use_dataflow_tracing:
dataflow_binary_path = os.path.join(
dataflow_build_dir, os.path.relpath(fuzzer_path, build_directory))
dataflow_trace_dir = dataflow_binary_path + DATAFLOW_TRACE_DIR_SUFFIX
if os.path.exists(dataflow_trace_dir):
arguments[constants.DATA_FLOW_TRACE_FLAGNAME] = str(dataflow_trace_dir)
arguments[constants.FOCUS_FUNCTION_FLAGNAME] = 'auto'
fuzzing_strategies.append(strategy.DATAFLOW_TRACING_STRATEGY.name)
else:
logs.log_warn(
'Dataflow trace is not found in dataflow build, skipping strategy.')
use_dataflow_tracing = False
# Generate new testcase mutations using radamsa, etc.
if is_mutations_run:
new_testcase_mutations_directory = create_corpus_directory('mutations')
generator_used = engine_common.generate_new_testcase_mutations(
corpus_directory, new_testcase_mutations_directory, candidate_generator)
# Add the used generator strategy to our fuzzing strategies list.
if (generator_used and
candidate_generator == engine_common.Generator.RADAMSA):
fuzzing_strategies.append(strategy.CORPUS_MUTATION_RADAMSA_STRATEGY.name)
additional_corpus_dirs.append(new_testcase_mutations_directory)
if strategy_pool.do_strategy(strategy.RANDOM_MAX_LENGTH_STRATEGY):
if constants.MAX_LEN_FLAGNAME not in existing_arguments:
max_length = random.SystemRandom().randint(1, MAX_VALUE_FOR_MAX_LENGTH)
arguments[constants.MAX_LEN_FLAGNAME] = max_length
fuzzing_strategies.append(strategy.RANDOM_MAX_LENGTH_STRATEGY.name)
if strategy_pool.do_strategy(strategy.VALUE_PROFILE_STRATEGY):
arguments[constants.VALUE_PROFILE_FLAGNAME] = 1
fuzzing_strategies.append(strategy.VALUE_PROFILE_STRATEGY.name)
if not use_dataflow_tracing and should_set_fork_flag(existing_arguments,
strategy_pool):
max_fuzz_threads = environment.get_value('MAX_FUZZ_THREADS', 1)
num_fuzz_processes = max(1, utils.cpu_count() // max_fuzz_threads)
arguments[constants.FORK_FLAGNAME] = num_fuzz_processes
fuzzing_strategies.append(
'%s_%d' % (strategy.FORK_STRATEGY.name, num_fuzz_processes))
extra_env = {}
if (not has_existing_mutator_strategy(fuzzing_strategies) and
strategy_pool.do_strategy(strategy.PEACH_GRAMMAR_MUTATION_STRATEGY) and
use_peach_mutator(extra_env, grammar)):
fuzzing_strategies.append(
'%s_%s' % (strategy.PEACH_GRAMMAR_MUTATION_STRATEGY.name, grammar))
if (environment.platform() == 'LINUX' and utils.is_oss_fuzz() and
strategy_pool.do_strategy(strategy.USE_EXTRA_SANITIZERS_STRATEGY)):
fuzzing_strategies.append(strategy.USE_EXTRA_SANITIZERS_STRATEGY.name)
return StrategyInfo(fuzzing_strategies, arguments, additional_corpus_dirs,
extra_env, use_dataflow_tracing, is_mutations_run) | Pick strategies. |
157,294 | import glob
import os
import re
import shutil
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
class HonggfuzzError(Exception):
"""Base exception class."""
The provided code snippet includes necessary dependencies for implementing the `_get_runner` function. Write a Python function `def _get_runner()` to solve the following problem:
Get the honggfuzz runner.
Here is the function:
def _get_runner():
"""Get the honggfuzz runner."""
honggfuzz_path = os.path.join(environment.get_value('BUILD_DIR'), 'honggfuzz')
if not os.path.exists(honggfuzz_path):
raise HonggfuzzError('honggfuzz not found in build')
os.chmod(honggfuzz_path, 0o755)
if environment.get_value('USE_UNSHARE'):
return new_process.UnicodeModifierRunner(honggfuzz_path)
return new_process.UnicodeProcessRunner(honggfuzz_path) | Get the honggfuzz runner. |
157,295 | import glob
import os
import re
import shutil
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
_HF_SANITIZER_LOG_PREFIX = 'HF.sanitizer.log'
The provided code snippet includes necessary dependencies for implementing the `_find_sanitizer_stacktrace` function. Write a Python function `def _find_sanitizer_stacktrace(reproducers_dir)` to solve the following problem:
Find the sanitizer stacktrace from the reproducers dir.
Here is the function:
def _find_sanitizer_stacktrace(reproducers_dir):
"""Find the sanitizer stacktrace from the reproducers dir."""
for stacktrace_path in glob.glob(
os.path.join(reproducers_dir, _HF_SANITIZER_LOG_PREFIX + '*')):
with open(stacktrace_path, 'rb') as f:
return utils.decode_to_unicode(f.read())
return None | Find the sanitizer stacktrace from the reproducers dir. |
157,296 | import glob
import os
import re
import shutil
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
_CRASH_REGEX = re.compile('Crash: saved as \'(.*)\'')
The provided code snippet includes necessary dependencies for implementing the `_get_reproducer_path` function. Write a Python function `def _get_reproducer_path(line)` to solve the following problem:
Get the reproducer path, if any.
Here is the function:
def _get_reproducer_path(line):
"""Get the reproducer path, if any."""
crash_match = _CRASH_REGEX.match(line)
if not crash_match:
return None
return crash_match.group(1) | Get the reproducer path, if any. |
157,297 | import glob
import os
import re
import shutil
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
_STATS_PREFIX = 'Summary '
The provided code snippet includes necessary dependencies for implementing the `_get_stats` function. Write a Python function `def _get_stats(line)` to solve the following problem:
Get stats, if any.
Here is the function:
def _get_stats(line):
"""Get stats, if any."""
if not line.startswith(_STATS_PREFIX):
return None
parts = line[len(_STATS_PREFIX):].split()
stats = {}
for part in parts:
if ':' not in part:
logs.log_error('Invalid stat part.', value=part)
key, value = part.split(':', 2)
try:
stats[key] = int(value)
except (ValueError, TypeError):
logs.log_error('Invalid stat value.', key=key, value=value)
return stats | Get stats, if any. |
157,298 | import glob
import os
import re
import shutil
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
from clusterfuzz.fuzz import engine
The provided code snippet includes necessary dependencies for implementing the `_contains_netdriver` function. Write a Python function `def _contains_netdriver(target_path)` to solve the following problem:
Returns whether |target_path| contains netdriver string.
Here is the function:
def _contains_netdriver(target_path):
"""Returns whether |target_path| contains netdriver string."""
with open(target_path, 'rb') as file_handle:
data = file_handle.read()
return data.find(b'\x01_LIBHFUZZ_NETDRIVER_BINARY_SIGNATURE_\x02\xff') != -1 | Returns whether |target_path| contains netdriver string. |
157,299 | import atexit
import collections
import enum
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import strategy_selection
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.afl import constants
from clusterfuzz._internal.bot.fuzzers.afl import stats
from clusterfuzz._internal.bot.fuzzers.afl.fuzzer import write_dummy_file
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import profiler
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `_verify_system_config` function. Write a Python function `def _verify_system_config()` to solve the following problem:
Verifies system settings required for AFL.
Here is the function:
def _verify_system_config():
"""Verifies system settings required for AFL."""
def _check_core_pattern_file():
"""Verifies that core pattern file content is set to 'core'."""
if not os.path.exists(constants.CORE_PATTERN_FILE_PATH):
return False
with open(constants.CORE_PATTERN_FILE_PATH, 'rb') as f:
return f.read().strip() == b'core'
if _check_core_pattern_file():
return
return_code = subprocess.call(
'sudo -n bash -c "echo core > {path}"'.format(
path=constants.CORE_PATTERN_FILE_PATH),
shell=True)
if return_code or not _check_core_pattern_file():
logs.log_fatal_and_exit(
'Failed to set {path}. AFL needs {path} to be set to core.'.format(
path=constants.CORE_PATTERN_FILE_PATH)) | Verifies system settings required for AFL. |
157,300 | import atexit
import collections
import enum
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import strategy_selection
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.afl import constants
from clusterfuzz._internal.bot.fuzzers.afl import stats
from clusterfuzz._internal.bot.fuzzers.afl.fuzzer import write_dummy_file
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import profiler
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `load_testcase_if_exists` function. Write a Python function `def load_testcase_if_exists(fuzzer_runner, testcase_file_path)` to solve the following problem:
Loads a crash testcase if it exists.
Here is the function:
def load_testcase_if_exists(fuzzer_runner, testcase_file_path):
"""Loads a crash testcase if it exists."""
# To ensure that we can run the fuzzer.
os.chmod(fuzzer_runner.executable_path, stat.S_IRWXU | stat.S_IRGRP
| stat.S_IXGRP)
fuzzer_runner.run_single_testcase(testcase_file_path)
print(fuzzer_runner.fuzzer_stderr)
return True | Loads a crash testcase if it exists. |
157,301 | import atexit
import collections
import enum
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import strategy_selection
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.afl import constants
from clusterfuzz._internal.bot.fuzzers.afl import stats
from clusterfuzz._internal.bot.fuzzers.afl.fuzzer import write_dummy_file
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import profiler
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `remove_path` function. Write a Python function `def remove_path(path)` to solve the following problem:
Remove |path| if it exists. Similar to running rm -rf |path|.
Here is the function:
def remove_path(path):
"""Remove |path| if it exists. Similar to running rm -rf |path|."""
# Remove links to files and files.
if os.path.isfile(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path)
# Else path doesn't exist. Do nothing. | Remove |path| if it exists. Similar to running rm -rf |path|. |
157,302 | import atexit
import collections
import enum
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
from clusterfuzz._internal.base import utils
from clusterfuzz._internal.bot.fuzzers import dictionary_manager
from clusterfuzz._internal.bot.fuzzers import engine_common
from clusterfuzz._internal.bot.fuzzers import options
from clusterfuzz._internal.bot.fuzzers import strategy_selection
from clusterfuzz._internal.bot.fuzzers import utils as fuzzer_utils
from clusterfuzz._internal.bot.fuzzers.afl import constants
from clusterfuzz._internal.bot.fuzzers.afl import stats
from clusterfuzz._internal.bot.fuzzers.afl.fuzzer import write_dummy_file
from clusterfuzz._internal.fuzzing import strategy
from clusterfuzz._internal.metrics import logs
from clusterfuzz._internal.metrics import profiler
from clusterfuzz._internal.platforms import android
from clusterfuzz._internal.system import environment
from clusterfuzz._internal.system import new_process
from clusterfuzz._internal.system import shell
The provided code snippet includes necessary dependencies for implementing the `list_full_file_paths_device` function. Write a Python function `def list_full_file_paths_device(directory)` to solve the following problem:
List the absolute paths of files in |directory| on Android device.
Here is the function:
def list_full_file_paths_device(directory):
"""List the absolute paths of files in |directory| on Android device."""
directory_absolute_path = os.path.abspath(directory)
directory_absolute_path = android.util.get_device_path(
directory_absolute_path)
dir_contents = android.adb.run_command(
['shell', 'ls', directory_absolute_path])
paths = []
for rel_path in dir_contents.split():
full_path = os.path.join(directory_absolute_path, rel_path)
if android.adb.file_exists(full_path):
paths.append(full_path)
return paths | List the absolute paths of files in |directory| on Android device. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.