id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
157,103
import base64 import collections import copy import json import re from google.cloud import ndb import requests import yaml from clusterfuzz._internal.base import tasks from clusterfuzz._internal.base import untrusted from clusterfuzz._internal.base import utils from clusterfuzz._internal.config import db_config from clusterfuzz._internal.config import local_config 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 fuzzer_selection from clusterfuzz._internal.google_cloud_utils import pubsub from clusterfuzz._internal.google_cloud_utils import storage from clusterfuzz._internal.metrics import logs from . import service_accounts def _create_pubsub_topic(name, client): """Create a pubsub topic and subscription if needed.""" application_id = utils.get_application_id() topic_name = pubsub.topic_name(application_id, name) if client.get_topic(topic_name) is None: client.create_topic(topic_name) subscription_name = pubsub.subscription_name(application_id, name) if client.get_subscription(subscription_name) is None: client.create_subscription(subscription_name, topic_name) The provided code snippet includes necessary dependencies for implementing the `create_pubsub_topics_for_queue_id` function. Write a Python function `def create_pubsub_topics_for_queue_id(platform)` to solve the following problem: Create pubsub topics from project configs for tasks. Here is the function: def create_pubsub_topics_for_queue_id(platform): """Create pubsub topics from project configs for tasks.""" platform, queue_id = platform.split(tasks.SUBQUEUE_IDENTIFIER) name = untrusted.queue_name(platform, queue_id) client = pubsub.PubSubClient() _create_pubsub_topic(name, client)
Create pubsub topics from project configs for tasks.
157,104
import base64 import collections import copy import json import re from google.cloud import ndb import requests import yaml from clusterfuzz._internal.base import tasks from clusterfuzz._internal.base import untrusted from clusterfuzz._internal.base import utils from clusterfuzz._internal.config import db_config from clusterfuzz._internal.config import local_config 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 fuzzer_selection from clusterfuzz._internal.google_cloud_utils import pubsub from clusterfuzz._internal.google_cloud_utils import storage from clusterfuzz._internal.metrics import logs from . import service_accounts def update_fuzzer_jobs(fuzzer_entities, job_names): """Update fuzzer job mappings.""" to_delete = {} for fuzzer_entity_key in fuzzer_entities: fuzzer_entity = fuzzer_entity_key.get() for job in data_types.Job.query(): if not job.environment_string: continue job_environment = job.get_environment() if not utils.string_is_true(job_environment.get('MANAGED', 'False')): continue if job.name in job_names: continue logs.log(f'Deleting job {job.name}') to_delete[job.name] = job.key try: fuzzer_entity.jobs.remove(job.name) except ValueError: pass fuzzer_entity.put() fuzzer_selection.update_mappings_for_fuzzer(fuzzer_entity) if to_delete: ndb_utils.delete_multi(to_delete.values()) def cleanup_old_projects_settings(project_names): """Delete old projects that are no longer used or disabled.""" to_delete = [] for project in data_types.OssFuzzProject.query(): if project.name not in project_names: logs.log(f'Deleting project {project.name}.') to_delete.append(project.key) if to_delete: ndb_utils.delete_multi(to_delete) def cleanup_pubsub_topics(project_names): """Delete old pubsub topics and subscriptions.""" client = pubsub.PubSubClient() application_id = utils.get_application_id() expected_topics = set() for platform in PUBSUB_PLATFORMS: expected_topics.update( [untrusted.queue_name(project, platform) for project in project_names]) pubsub_config = local_config.Config('pubsub.queues') unmanaged_queues = [queue['name'] for queue in pubsub_config.get('resources')] for topic in client.list_topics(pubsub.project_name(application_id)): _, name = pubsub.parse_name(topic) if (not name.startswith(tasks.JOBS_PREFIX) and not name.startswith(tasks.HIGH_END_JOBS_PREFIX)): # Some topic created by another service, ignore. continue if name in unmanaged_queues: continue if name in expected_topics: continue for subscription in client.list_topic_subscriptions(topic): client.delete_subscription(subscription) client.delete_topic(topic) The provided code snippet includes necessary dependencies for implementing the `cleanup_stale_projects` function. Write a Python function `def cleanup_stale_projects(fuzzer_entities, project_names, job_names, segregate_projects)` to solve the following problem: Clean up stale projects. Here is the function: def cleanup_stale_projects(fuzzer_entities, project_names, job_names, segregate_projects): """Clean up stale projects.""" update_fuzzer_jobs(fuzzer_entities, job_names) cleanup_old_projects_settings(project_names) if segregate_projects: cleanup_pubsub_topics(project_names)
Clean up stale projects.
157,105
import collections import datetime from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment The provided code snippet includes necessary dependencies for implementing the `_past_day_formatter` function. Write a Python function `def _past_day_formatter(query_format, dataset)` to solve the following problem: Simple formatter to get stats for the past day. Here is the function: def _past_day_formatter(query_format, dataset): """Simple formatter to get stats for the past day.""" end_time = utils.utcnow().date() start_time = end_time - datetime.timedelta(days=1) return query_format.format( dataset=dataset, start_time=start_time, end_time=end_time)
Simple formatter to get stats for the past day.
157,106
import collections import datetime from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment The provided code snippet includes necessary dependencies for implementing the `_new_fuzzer_formatter` function. Write a Python function `def _new_fuzzer_formatter(query_format, dataset)` to solve the following problem: Prepare a query to check for new fuzzers from the past week. Here is the function: def _new_fuzzer_formatter(query_format, dataset): """Prepare a query to check for new fuzzers from the past week.""" now = utils.utcnow().date() cutoff_time = now - datetime.timedelta(days=7) return query_format.format(dataset=dataset, cutoff_time=cutoff_time)
Prepare a query to check for new fuzzers from the past week.
157,107
import collections import datetime from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment The provided code snippet includes necessary dependencies for implementing the `_coverage_formatter` function. Write a Python function `def _coverage_formatter(query_format, dataset)` to solve the following problem: Prepare a query to check for changes in coverage week over week. Here is the function: def _coverage_formatter(query_format, dataset): """Prepare a query to check for changes in coverage week over week.""" end_date = utils.utcnow().date() - datetime.timedelta(days=1) middle_date = end_date - datetime.timedelta(days=7) start_date = end_date - datetime.timedelta(days=14) return query_format.format( dataset=dataset, start_date=start_date, middle_date=middle_date, end_date=end_date)
Prepare a query to check for changes in coverage week over week.
157,108
import collections import datetime from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment RESTORE_DEFAULT_MATCH = SpecificationMatch( new_weight=1.0, reason='no longer matches any weight adjustment rules') def update_weight_for_target(fuzz_target_name, job, match): """Set the weight for a particular target.""" target_job = data_handler.get_fuzz_target_job(fuzz_target_name, job) if not target_job: # Bail out. This is expected if any fuzzer/job combinations become outdated. return weight = match.new_weight logs.log('Adjusted weight to %f for target %s and job %s (%s).' % (weight, fuzz_target_name, job, match.reason)) target_job.weight = weight target_job.put() def update_matches_for_specification(specification, client, engine, matches, run_set): """Run a query and adjust weights based on a given query specification.""" query = specification.formatter(specification.query_format, fuzzer_stats.dataset_name(engine)) results = _query_helper(client, query) for result in results: fuzzer = result['fuzzer'] job = result['job'] new_weight = result['new_weight'] if new_weight is None: continue run_set.add((fuzzer, job)) if new_weight != 1.0: match = SpecificationMatch( new_weight=new_weight, reason=specification.reason) _update_match(matches, fuzzer, job, match) The provided code snippet includes necessary dependencies for implementing the `update_target_weights_for_engine` function. Write a Python function `def update_target_weights_for_engine(client, engine, specifications)` to solve the following problem: Update all fuzz target weights for the specified engine. Here is the function: def update_target_weights_for_engine(client, engine, specifications): """Update all fuzz target weights for the specified engine.""" matches = {} run_set = set() # All fuzzers with non-default weights must be tracked with a special # specification. This ensures that they will be restored to normal weight # once conditions causing adjustments are no longer met. target_jobs = data_types.FuzzTargetJob.query( data_types.FuzzTarget.engine == engine).filter( data_types.FuzzTargetJob.weight != 1.0) for target_job in target_jobs: matches[(target_job.fuzz_target_name, target_job.job)] = RESTORE_DEFAULT_MATCH for match in specifications: update_matches_for_specification(match, client, engine, matches, run_set) for (fuzzer, job), match in matches.items(): if (fuzzer, job) not in run_set: # This ensures that we don't reset weights for fuzzers with problems if # they didn't run in the time covered by our queries. continue update_weight_for_target(fuzzer, job, match) logs.log('Weight adjustments complete for engine %s.' % engine)
Update all fuzz target weights for the specified engine.
157,109
import collections import datetime from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment The provided code snippet includes necessary dependencies for implementing the `store_current_weights_in_bigquery` function. Write a Python function `def store_current_weights_in_bigquery()` to solve the following problem: Update a bigquery table containing the daily stats. Here is the function: def store_current_weights_in_bigquery(): """Update a bigquery table containing the daily stats.""" rows = [] target_jobs = ndb_utils.get_all_from_model(data_types.FuzzTargetJob) for target_job in target_jobs: row = { 'fuzzer': target_job.fuzz_target_name, 'job': target_job.job, 'weight': target_job.weight } rows.append(big_query.Insert(row=row, insert_id=None)) client = big_query.Client(dataset_id='main', table_id='fuzzer_weights') client.insert(rows)
Update a bigquery table containing the daily stats.
157,110
import collections import datetime from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment DEFAULT_MULTIPLIER = 30.0 TARGET_COUNT_WEIGHT_CAP = 100.0 def update_job_weight(job_name, multiplier): """Update a job weight.""" tool_name = environment.get_memory_tool_name(job_name) multiplier *= SANITIZER_WEIGHTS.get(tool_name, DEFAULT_SANITIZER_WEIGHT) engine = environment.get_engine_for_job(job_name) multiplier *= ENGINE_WEIGHTS.get(engine, DEFAULT_ENGINE_WEIGHT) query = data_types.FuzzerJob.query(data_types.FuzzerJob.job == job_name) changed_weights = [] for fuzzer_job in query: if fuzzer_job.multiplier != multiplier: fuzzer_job.multiplier = multiplier changed_weights.append(fuzzer_job) if changed_weights: ndb_utils.put_multi(changed_weights) The provided code snippet includes necessary dependencies for implementing the `update_job_weights` function. Write a Python function `def update_job_weights()` to solve the following problem: Update job weights. Here is the function: def update_job_weights(): """Update job weights.""" for job in data_types.Job.query(): multiplier = DEFAULT_MULTIPLIER if environment.is_engine_fuzzer_job(job.name): targets_count = ndb.Key(data_types.FuzzTargetsCount, job.name).get() # If the count is 0, it may be due to a bad build or some other issue. Use # the default weight in that case to allow for recovery. if targets_count and targets_count.count: multiplier = targets_count.count multiplier = min(multiplier, TARGET_COUNT_WEIGHT_CAP) update_job_weight(job.name, multiplier)
Update job weights.
157,111
from google.cloud import ndb from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.metrics import logs FUZZER_JOB_BATCH_SIZE = 4000 The provided code snippet includes necessary dependencies for implementing the `batch_fuzzer_jobs` function. Write a Python function `def batch_fuzzer_jobs()` to solve the following problem: Batches FuzzerJobs for reduced Datastore read ops by bots. Here is the function: def batch_fuzzer_jobs(): """Batches FuzzerJobs for reduced Datastore read ops by bots.""" platforms = [ item.platform for item in data_types.FuzzerJob.query( projection=[data_types.FuzzerJob.platform], distinct=True) ] for platform in platforms: fuzzer_jobs = list( data_types.FuzzerJob.query(data_types.FuzzerJob.platform == platform)) fuzzer_jobs.sort(key=lambda item: item.job) batches_to_remove = { b.key for b in data_types.FuzzerJobs.query( data_types.FuzzerJobs.platform == platform) } batch_count = 0 for i in range(0, len(fuzzer_jobs), FUZZER_JOB_BATCH_SIZE): key_id = platform + '-' + str(batch_count) end = min(i + FUZZER_JOB_BATCH_SIZE, len(fuzzer_jobs)) batched = data_types.FuzzerJobs(id=key_id, platform=platform) batched.platform = platform batched.fuzzer_jobs = fuzzer_jobs[i:end] batched.put() batch_count += 1 batches_to_remove.discard(batched.key) # Removes additional batches if number reduced. if batches_to_remove: ndb.delete_multi(batches_to_remove)
Batches FuzzerJobs for reduced Datastore read ops by bots.
157,112
import datetime import os from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import fuzz_target_utils from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.fuzzing import corpus_manager from clusterfuzz._internal.google_cloud_utils import storage from clusterfuzz._internal.metrics import logs def _set_public_acl_if_needed(url): """Sets public ACL on the object with given URL, if it's not public yet.""" if storage.get_acl(url, 'allUsers'): logs.log('%s is already marked public, skipping.' % url) return True if not storage.set_acl(url, 'allUsers'): logs.log_error('Failed to mark %s public.' % url) return False return True The provided code snippet includes necessary dependencies for implementing the `_make_corpus_backup_public` function. Write a Python function `def _make_corpus_backup_public(target, corpus_fuzzer_name_override, corpus_backup_bucket_name)` to solve the following problem: Identifies old corpus backups and makes them public. Here is the function: def _make_corpus_backup_public(target, corpus_fuzzer_name_override, corpus_backup_bucket_name): """Identifies old corpus backups and makes them public.""" corpus_backup_date = utils.utcnow().date() - datetime.timedelta( days=data_types.CORPUS_BACKUP_PUBLIC_LOOKBACK_DAYS) corpus_backup_url = corpus_manager.gcs_url_for_backup_file( corpus_backup_bucket_name, corpus_fuzzer_name_override or target.engine, target.project_qualified_name(), corpus_backup_date) if not storage.get(corpus_backup_url): logs.log_warn('Failed to find corpus backup %s.' % corpus_backup_url) return if not _set_public_acl_if_needed(corpus_backup_url): return filename = ( corpus_manager.PUBLIC_BACKUP_TIMESTAMP + os.extsep + corpus_manager.BACKUP_ARCHIVE_FORMAT) public_url = os.path.join(os.path.dirname(corpus_backup_url), filename) if not storage.copy_blob(corpus_backup_url, public_url): logs.log_error( 'Failed to overwrite %s with the latest public corpus backup.' % public_url) return if not _set_public_acl_if_needed(public_url): return logs.log('Corpus backup %s is now marked public.' % corpus_backup_url)
Identifies old corpus backups and makes them public.
157,113
from concurrent.futures import ThreadPoolExecutor import datetime import random import string import time from googleapiclient.errors import HttpError import httplib2 from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import fuzzer_stats from clusterfuzz._internal.metrics import fuzzer_stats_schema from clusterfuzz._internal.metrics import logs STATS_KINDS = [fuzzer_stats.JobRun, fuzzer_stats.TestcaseRun] NUM_RETRIES = 2 _HEX_DIGITS = string.hexdigits[:-6] def _utc_now(): """Return datetime.datetime.utcnow().""" return datetime.datetime.utcnow() def _create_dataset_if_needed(bigquery, dataset_id): """Create a new dataset if necessary.""" project_id = utils.get_application_id() dataset_body = { 'datasetReference': { 'datasetId': dataset_id, 'projectId': project_id, }, } dataset_insert = bigquery.datasets().insert( projectId=project_id, body=dataset_body) return _execute_insert_request(dataset_insert) def _create_table_if_needed(bigquery, dataset_id, table_id, schema): """Create a new table if needed.""" project_id = utils.get_application_id() table_body = { 'tableReference': { 'datasetId': dataset_id, 'projectId': project_id, 'tableId': table_id, }, 'timePartitioning': { 'type': 'DAY', }, } if schema is not None: table_body['schema'] = schema table_insert = bigquery.tables().insert( projectId=project_id, datasetId=dataset_id, body=table_body) return _execute_insert_request(table_insert) def _poll_completion(bigquery, project_id, job_id): """Poll for completion.""" response = bigquery.jobs().get( projectId=project_id, jobId=job_id).execute(num_retries=NUM_RETRIES) while response['status']['state'] == 'RUNNING': response = bigquery.jobs().get( projectId=project_id, jobId=job_id).execute(num_retries=NUM_RETRIES) time.sleep(POLL_INTERVAL) return response The provided code snippet includes necessary dependencies for implementing the `_load_data` function. Write a Python function `def _load_data(fuzzer)` to solve the following problem: Load yesterday's stats into BigQuery. Here is the function: def _load_data(fuzzer): """Load yesterday's stats into BigQuery.""" bigquery = big_query.get_api_client() project_id = utils.get_application_id() yesterday = (_utc_now().date() - datetime.timedelta(days=1)) date_string = yesterday.strftime('%Y%m%d') timestamp = utils.utc_date_to_timestamp(yesterday) dataset_id = fuzzer_stats.dataset_name(fuzzer) if not _create_dataset_if_needed(bigquery, dataset_id): return for kind in STATS_KINDS: kind_name = kind.__name__ table_id = kind_name if kind == fuzzer_stats.TestcaseRun: schema = fuzzer_stats_schema.get(fuzzer) else: schema = kind.SCHEMA if not schema: continue if not _create_table_if_needed(bigquery, dataset_id, table_id, schema): continue gcs_path = fuzzer_stats.get_gcs_stats_path(kind_name, fuzzer, timestamp) # Shard loads by prefix to avoid causing BigQuery to run out of memory. first_write = True for prefix in _HEX_DIGITS: load = { 'destinationTable': { 'projectId': project_id, 'tableId': table_id + '$' + date_string, 'datasetId': dataset_id, }, 'schemaUpdateOptions': ['ALLOW_FIELD_ADDITION',], 'sourceFormat': 'NEWLINE_DELIMITED_JSON', 'sourceUris': ['gs:/' + gcs_path + prefix + '*.json'], # Truncate on the first shard, then append the rest. 'writeDisposition': 'WRITE_TRUNCATE' if first_write else 'WRITE_APPEND', 'schema': schema, } job_body = { 'configuration': { 'load': load, }, } try: logs.log("Uploading job to BigQuery.", job_body=job_body) request = bigquery.jobs().insert(projectId=project_id, body=job_body) # pylint: disable=no-member load_response = request.execute(num_retries=NUM_RETRIES) job_id = load_response['jobReference']['jobId'] logs.log(f'Load job id: {job_id}') response = _poll_completion(bigquery, project_id, job_id) logs.log('Completed load: %s' % response) errors = response['status'].get('errors') if errors: logs.log_error( f'Failed load for {job_id} with errors: {str(errors)})') else: # Successful write. Subsequent writes should be WRITE_APPEND. first_write = False except Exception as e: # Log exception here as otherwise it gets lost in the thread pool # worker. logs.log_error(f'Failed to load: {str(e)}')
Load yesterday's stats into BigQuery.
157,114
from collections import namedtuple from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.fuzzing import strategy from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs def _query_multi_armed_bandit_probabilities(engine): """Get query results. Queries above BANDIT_PROBABILITY_QUERY and yields results from bigquery. This query is sorted by strategies implemented.""" strategy_names_list = [ strategy_entry.name for strategy_entry in engine.query_strategy_list ] strategies_subquery = '\n'.join([ STRATEGY_SUBQUERY_FORMAT.format(strategy_name=strategy_name) for strategy_name in strategy_names_list ]) client = big_query.Client() strategies = ','.join( ['strategy_' + strategy_name for strategy_name in strategy_names_list]) formatted_query = BANDIT_PROBABILITY_QUERY_FORMAT.format( performance_metric=engine.performance_metric, temperature_value=TEMPERATURE_PARAMETER, strategies=strategies, strategies_subquery=strategies_subquery, engine=engine.name) return client.query(query=formatted_query).rows def _store_probabilities_in_bigquery(engine, data): """Update a bigquery table containing the daily updated probability distribution over strategies.""" bigquery_data = [] # TODO(mukundv): Update once we choose a temperature parameter for final # implementation. for row in data: bigquery_row = { 'strategy_name': row['strategy'], 'probability': row['bandit_weight'], 'engine': engine.name } bigquery_data.append(big_query.Insert(row=bigquery_row, insert_id=None)) if bigquery_data: client = big_query.Client( dataset_id='main', table_id='fuzz_strategy_probability') client.insert(bigquery_data) else: logs.log('No fuzz strategy distribution data was found to upload to ' 'BigQuery.') The provided code snippet includes necessary dependencies for implementing the `_query_and_upload_strategy_probabilities` function. Write a Python function `def _query_and_upload_strategy_probabilities(engine)` to solve the following problem: Uploads queried data into datastore. Calls query functions and uploads query results to datastore to use as new probabilities. Probabilities are based on new_edges feature. Here is the function: def _query_and_upload_strategy_probabilities(engine): """Uploads queried data into datastore. Calls query functions and uploads query results to datastore to use as new probabilities. Probabilities are based on new_edges feature.""" strategy_data = [] data = _query_multi_armed_bandit_probabilities(engine) logs.log('Queried distribution for {}.'.format(engine.name)) # TODO(mukundv): Update once we choose a temperature parameter for final # implementation. for row in data: curr_strategy = data_types.FuzzStrategyProbability() curr_strategy.strategy_name = str(row['strategy']) curr_strategy.probability = float(row['bandit_weight']) curr_strategy.engine = engine.name strategy_data.append(curr_strategy) query = data_types.FuzzStrategyProbability.query( data_types.FuzzStrategyProbability.engine == engine.name) ndb_utils.delete_multi( [entity.key for entity in ndb_utils.get_all_from_query(query)]) ndb_utils.put_multi(strategy_data) logs.log('Uploaded queried distribution to ndb for {}'.format(engine.name)) _store_probabilities_in_bigquery(engine, data) logs.log('Uploaded queried distribution to BigQuery for {}'.format( engine.name))
Uploads queried data into datastore. Calls query functions and uploads query results to datastore to use as new probabilities. Probabilities are based on new_edges feature.
157,115
from clusterfuzz._internal.base import tasks from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import fuzz_target_utils from clusterfuzz._internal.metrics import logs The provided code snippet includes necessary dependencies for implementing the `get_tasks_to_schedule` function. Write a Python function `def get_tasks_to_schedule()` to solve the following problem: Return (task_target, job_name, queue_name) arguments to schedule a task. Here is the function: def get_tasks_to_schedule(): """Return (task_target, job_name, queue_name) arguments to schedule a task.""" for job in data_types.Job.query(): if not utils.string_is_true(job.get_environment().get('CORPUS_PRUNE')): continue queue_name = tasks.queue_for_job(job.name) for target_job in fuzz_target_utils.get_fuzz_target_jobs(job=job.name): task_target = target_job.fuzz_target_name yield (task_target, job.name, queue_name)
Return (task_target, job_name, queue_name) arguments to schedule a task.
157,116
from clusterfuzz._internal.base import tasks from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs The provided code snippet includes necessary dependencies for implementing the `schedule` function. Write a Python function `def schedule(task)` to solve the following problem: Creates tasks for open reproducible testcases. Here is the function: def schedule(task): """Creates tasks for open reproducible testcases.""" testcase_ids = [] for status in ['Processed', 'Duplicate']: for testcase in data_types.Testcase.query( ndb_utils.is_true(data_types.Testcase.open), ndb_utils.is_false(data_types.Testcase.one_time_crasher_flag), data_types.Testcase.status == status): testcase_id = testcase.key.id() try: tasks.add_task( task, testcase_id, testcase.job_type, queue=tasks.queue_for_testcase(testcase)) testcase_ids.append(testcase_id) except Exception: logs.log_error(f'Failed to create task for {testcase_id}') logs.log( 'Created progression tasks for testcases.', testcase_ids=testcase_ids)
Creates tasks for open reproducible testcases.
157,117
from googleapiclient import discovery from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs The provided code snippet includes necessary dependencies for implementing the `admins_from_iam_policy` function. Write a Python function `def admins_from_iam_policy(iam_policy)` to solve the following problem: Gets a list of admins from the IAM policy. Here is the function: def admins_from_iam_policy(iam_policy): """Gets a list of admins from the IAM policy.""" # Per # https://cloud.google.com/appengine/docs/standard/python/users/adminusers, An # administrator is a user who has the Viewer, Editor, or Owner primitive role, # or the App Engine App Admin predefined role roles = [ 'roles/editor', 'roles/owner', 'roles/viewer', 'roles/appengine.appAdmin', ] admins = [] for binding in iam_policy['bindings']: if binding['role'] not in roles: continue for member in binding['members']: user_type, email = member.split(':', 2) if user_type == 'user': admins.append(email) return admins
Gets a list of admins from the IAM policy.
157,118
from googleapiclient import discovery from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs The provided code snippet includes necessary dependencies for implementing the `update_admins` function. Write a Python function `def update_admins(new_admins)` to solve the following problem: Update list of admins. Here is the function: def update_admins(new_admins): """Update list of admins.""" existing_admins = ndb_utils.get_all_from_model(data_types.Admin) to_remove = [] existing_admin_emails = set() for admin in existing_admins: if admin.email not in new_admins: logs.log('Removing admin ' + admin.email) to_remove.append(admin.key) existing_admin_emails.add(admin.email) ndb_utils.delete_multi(to_remove) to_add = [] for admin in new_admins: if admin not in existing_admin_emails: to_add.append(data_types.Admin(id=admin, email=admin)) logs.log('Adding admin ' + admin) ndb_utils.put_multi(to_add)
Update list of admins.
157,119
from google.cloud import ndb from clusterfuzz._internal.base import untrusted from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.metrics import logs The provided code snippet includes necessary dependencies for implementing the `generate_cert` function. Write a Python function `def generate_cert(project_name)` to solve the following problem: Generate a self signed cerficate. Here is the function: def generate_cert(project_name): """Generate a self signed cerficate.""" # Defer imports to avoid issues on Python 2. from OpenSSL import crypto key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().C = 'US' cert.get_subject().CN = '*' + untrusted.internal_network_domain() cert.get_subject().O = project_name cert.set_serial_number(9001) cert.set_notBefore(b'20000101000000Z') cert.set_notAfter(b'21000101000000Z') cert.set_issuer(cert.get_subject()) cert.set_pubkey(key) cert.sign(key, 'sha256') cert_contents = crypto.dump_certificate(crypto.FILETYPE_PEM, cert) key_contents = crypto.dump_privatekey(crypto.FILETYPE_PEM, key) return cert_contents, key_contents
Generate a self signed cerficate.
157,120
import collections import re from clusterfuzz._internal.base import errors from clusterfuzz._internal.config import local_config 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.issue_management import issue_tracker_utils from clusterfuzz._internal.metrics import logs from . import cleanup from . import group_leader FORWARDED_ATTRIBUTES = ('crash_state', 'crash_type', 'group_id', 'one_time_crasher_flag', 'project_name', 'security_flag', 'timestamp', 'job_type') class TestcaseAttributes: """Testcase attributes used for grouping.""" __slots__ = ('id', 'is_leader', 'issue_id') + FORWARDED_ATTRIBUTES def __init__(self, testcase_id): self.id = testcase_id self.is_leader = True self.issue_id = None def _group_testcases_based_on_variants(testcase_map): """Group testcases that are associated based on variant analysis.""" # Skip this if the project is configured so (like Google3). enable = local_config.ProjectConfig().get('deduplication.variant', True) if not enable: return logs.log('Grouping based on variant analysis.') grouping_candidates = collections.defaultdict(list) project_num_testcases = collections.defaultdict(int) # Phase 1: collect all grouping candidates. for testcase_1_id, testcase_1 in testcase_map.items(): # Count the number of testcases for each project. project_num_testcases[testcase_1.project_name] += 1 for testcase_2_id, testcase_2 in testcase_map.items(): # Rule: Don't group the same testcase and use different combinations for # comparisons. if testcase_1_id <= testcase_2_id: continue # Rule: If both testcase have the same group id, then no work to do. if testcase_1.group_id == testcase_2.group_id and testcase_1.group_id: continue # Rule: Check both testcase are under the same project. if testcase_1.project_name != testcase_2.project_name: continue # Rule: If both testcase have same job_type, then skip variant anlysis. if testcase_1.job_type == testcase_2.job_type: continue # Rule: Skip variant analysis if any testcase is timeout or OOM. if (VARIANT_CRASHES_IGNORE.match(testcase_1.crash_type) or VARIANT_CRASHES_IGNORE.match(testcase_2.crash_type)): continue # Rule: Skip variant analysis if any testcase states is NULL. if (VARIANT_STATES_IGNORE.match(testcase_1.crash_state) or VARIANT_STATES_IGNORE.match(testcase_2.crash_state)): continue # Rule: Skip variant analysis if any testcase is not reproducible. if testcase_1.one_time_crasher_flag or testcase_2.one_time_crasher_flag: continue # Rule: Group testcase with similar variants. # For each testcase2, get the related variant1 and check for equivalence. candidate_variant = data_handler.get_testcase_variant( testcase_1_id, testcase_2.job_type) if (not candidate_variant or not is_same_variant(candidate_variant, testcase_2)): continue current_project = testcase_1.project_name grouping_candidates[current_project].append((testcase_1_id, testcase_2_id)) # Top crashes are usually startup crashes, so don't group them. top_crashes_by_project_and_platform = ( cleanup.get_top_crashes_for_all_projects_and_platforms( limit=TOP_CRASHES_LIMIT)) # Phase 2: check for the anomalous candidates # i.e. candiates matched with many testcases. for project, candidate_list in grouping_candidates.items(): project_ignore_testcases = set() # Count the number of times a testcase is matched for grouping. project_counter = collections.defaultdict(int) for candidate_tuple in candidate_list: for testcase_id in candidate_tuple: project_counter[testcase_id] += 1 # Determine anomalous candidates. threshold = VARIANT_THRESHOLD_PERCENTAGE * project_num_testcases[project] threshold = min(threshold, VARIANT_MAX_THRESHOLD) threshold = max(threshold, VARIANT_MIN_THRESHOLD) # Check threshold to be above a minimum, to avoid unnecessary filtering. for testcase_id, count in project_counter.items(): if count >= threshold: project_ignore_testcases.add(testcase_id) for (testcase_1_id, testcase_2_id) in candidate_list: if (testcase_1_id in project_ignore_testcases or testcase_2_id in project_ignore_testcases): logs.log('VARIANT ANALYSIS (Pruning): Anomalous match: (id1=%s, ' 'matched_count1=%d) matched with (id2=%d, matched_count2=%d), ' 'threshold=%.2f.' % (testcase_1_id, project_counter[testcase_1_id], testcase_2_id, project_counter[testcase_2_id], threshold)) continue testcase_1 = testcase_map[testcase_1_id] testcase_2 = testcase_map[testcase_2_id] if (matches_top_crash(testcase_1, top_crashes_by_project_and_platform) or matches_top_crash(testcase_2, top_crashes_by_project_and_platform)): logs.log(f'VARIANT ANALYSIS: {testcase_1_id} or {testcase_2_id} ' 'is a top crash, skipping.') continue logs.log( 'VARIANT ANALYSIS: Grouping testcase 1 ' '(id=%s, ' 'crash_type=%s, crash_state=%s, security_flag=%s, job=%s, group=%s) ' 'and testcase 2 (id=%s, ' 'crash_type=%s, crash_state=%s, security_flag=%s, job=%s, group=%s).' % (testcase_1.id, testcase_1.crash_type, testcase_1.crash_state, testcase_1.security_flag, testcase_1.job_type, testcase_1.group_id, testcase_2.id, testcase_2.crash_type, testcase_2.crash_state, testcase_2.security_flag, testcase_2.job_type, testcase_2.group_id)) combine_testcases_into_group(testcase_1, testcase_2, testcase_map) def _group_testcases_with_same_issues(testcase_map): """Group testcases that are associated with same underlying issue.""" logs.log('Grouping based on same issues.') for testcase_1_id, testcase_1 in testcase_map.items(): for testcase_2_id, testcase_2 in testcase_map.items(): # Rule: Don't group the same testcase and use different combinations for # comparisons. if testcase_1_id <= testcase_2_id: continue # Rule: If both testcase have the same group id, then no work to do. if testcase_1.group_id == testcase_2.group_id and testcase_1.group_id: continue # Rule: Check both testcase have an associated issue id. if testcase_1.issue_id is None or testcase_2.issue_id is None: continue # Rule: Check both testcase are under the same project. if testcase_1.project_name != testcase_2.project_name: continue # Rule: Group testcase with same underlying issue. if testcase_1.issue_id != testcase_2.issue_id: continue combine_testcases_into_group(testcase_1, testcase_2, testcase_map) def _group_testcases_with_similar_states(testcase_map): """Group testcases with similar looking crash states.""" logs.log('Grouping based on similar states.') for testcase_1_id, testcase_1 in testcase_map.items(): for testcase_2_id, testcase_2 in testcase_map.items(): # Rule: Don't group the same testcase and use different combinations for # comparisons. if testcase_1_id <= testcase_2_id: continue # If both testcase have the same group id, then no work to do. if testcase_1.group_id == testcase_2.group_id and testcase_1.group_id: continue # Rule: Check both testcase are under the same project. if testcase_1.project_name != testcase_2.project_name: continue # Rule: Security bugs should never be grouped with functional bugs. if testcase_1.security_flag != testcase_2.security_flag: continue # Rule: Follow different comparison rules when crash types is one of the # ones that have unique crash state (custom ones specifically). if (testcase_1.crash_type in data_types.CRASH_TYPES_WITH_UNIQUE_STATE or testcase_2.crash_type in data_types.CRASH_TYPES_WITH_UNIQUE_STATE): # For grouping, make sure that both crash type and state match. if (testcase_1.crash_type != testcase_2.crash_type or testcase_1.crash_state != testcase_2.crash_state): continue else: # Rule: For functional bugs, compare for similar crash states. if not testcase_1.security_flag: crash_comparer = CrashComparer(testcase_1.crash_type, testcase_2.crash_type) if not crash_comparer.is_similar(): continue # Rule: Check for crash state similarity. crash_comparer = CrashComparer(testcase_1.crash_state, testcase_2.crash_state) if not crash_comparer.is_similar(): continue combine_testcases_into_group(testcase_1, testcase_2, testcase_map) def _has_testcase_with_same_params(testcase, testcase_map): """Return a bool whether there is another testcase with same params.""" for other_testcase_id in testcase_map: # yapf: disable if (testcase.project_name == testcase_map[other_testcase_id].project_name and testcase.crash_state == testcase_map[other_testcase_id].crash_state and testcase.crash_type == testcase_map[other_testcase_id].crash_type and testcase.security_flag == testcase_map[other_testcase_id].security_flag and testcase.one_time_crasher_flag == testcase_map[other_testcase_id].one_time_crasher_flag): return True # yapf: enable return False def _shrink_large_groups_if_needed(testcase_map): """Shrinks groups that exceed a particular limit.""" def _key_func(testcase): weight = 0 if not testcase.one_time_crasher_flag: weight |= 2**1 if testcase.issue_id: weight |= 2**2 return weight group_id_with_testcases_map = {} for testcase in testcase_map.values(): if not testcase.group_id: continue if testcase.group_id not in group_id_with_testcases_map: group_id_with_testcases_map[testcase.group_id] = [testcase] else: group_id_with_testcases_map[testcase.group_id].append(testcase) for testcases_in_group in group_id_with_testcases_map.values(): if len(testcases_in_group) <= GROUP_MAX_TESTCASE_LIMIT: continue testcases_in_group = sorted(testcases_in_group, key=_key_func) for testcase in testcases_in_group[:-GROUP_MAX_TESTCASE_LIMIT]: try: testcase_entity = data_handler.get_testcase_by_id(testcase.id) except errors.InvalidTestcaseError: # Already deleted. continue if testcase_entity.bug_information: continue logs.log_warn(('Deleting testcase {testcase_id} due to overflowing group ' '{group_id}.').format( testcase_id=testcase.id, group_id=testcase.group_id)) testcase_entity.key.delete() The provided code snippet includes necessary dependencies for implementing the `group_testcases` function. Write a Python function `def group_testcases()` to solve the following problem: Group testcases based on rules like same bug numbers, similar crash states, etc. Here is the function: def group_testcases(): """Group testcases based on rules like same bug numbers, similar crash states, etc.""" testcase_map = {} cached_issue_map = {} for testcase_id in data_handler.get_open_testcase_id_iterator(): try: testcase = data_handler.get_testcase_by_id(testcase_id) except errors.InvalidTestcaseError: # Already deleted. continue # Remove duplicates early on to avoid large groups. if (not testcase.bug_information and not testcase.uploader_email and _has_testcase_with_same_params(testcase, testcase_map)): logs.log('Deleting duplicate testcase %d.' % testcase_id) testcase.key.delete() continue # Wait for minimization to finish as this might change crash params such # as type and may mark it as duplicate / closed. if not testcase.minimized_keys: continue # Store needed testcase attributes into |testcase_map|. testcase_map[testcase_id] = TestcaseAttributes(testcase_id) testcase_attributes = testcase_map[testcase_id] for attribute_name in FORWARDED_ATTRIBUTES: setattr(testcase_attributes, attribute_name, getattr(testcase, attribute_name)) # Store original issue mappings in the testcase attributes. if testcase.bug_information: issue_id = int(testcase.bug_information) project_name = testcase.project_name if (project_name in cached_issue_map and issue_id in cached_issue_map[project_name]): testcase_attributes.issue_id = ( cached_issue_map[project_name][issue_id]) else: try: issue_tracker = issue_tracker_utils.get_issue_tracker_for_testcase( testcase) except ValueError: logs.log_error('Couldn\'t get issue tracker for issue.') del testcase_map[testcase_id] continue if not issue_tracker: logs.log_error( 'Unable to access issue tracker for issue %d.' % issue_id) testcase_attributes.issue_id = issue_id continue # Determine the original issue id traversing the list of duplicates. try: issue = issue_tracker.get_original_issue(issue_id) original_issue_id = int(issue.id) except: # If we are unable to access the issue, then we can't determine # the original issue id. Assume that it is the same as issue id. logs.log_error( 'Unable to determine original issue for issue %d.' % issue_id) testcase_attributes.issue_id = issue_id continue if project_name not in cached_issue_map: cached_issue_map[project_name] = {} cached_issue_map[project_name][issue_id] = original_issue_id cached_issue_map[project_name][original_issue_id] = original_issue_id testcase_attributes.issue_id = original_issue_id # No longer needed. Free up some memory. cached_issue_map.clear() _group_testcases_with_similar_states(testcase_map) _group_testcases_with_same_issues(testcase_map) _group_testcases_based_on_variants(testcase_map) _shrink_large_groups_if_needed(testcase_map) group_leader.choose(testcase_map) # TODO(aarya): Replace with an optimized implementation using dirty flag. # Update the group mapping in testcase object. for testcase_id in data_handler.get_open_testcase_id_iterator(): if testcase_id not in testcase_map: # A new testcase that was just created. Skip for now, will be grouped in # next iteration of group task. continue # If we are part of a group, then calculate the number of testcases in that # group and lowest issue id of issues associated with testcases in that # group. updated_group_id = testcase_map[testcase_id].group_id updated_is_leader = testcase_map[testcase_id].is_leader updated_group_id_count = 0 updated_group_bug_information = 0 if updated_group_id: for other_testcase in testcase_map.values(): if other_testcase.group_id != updated_group_id: continue updated_group_id_count += 1 # Update group issue id to be lowest issue id in the entire group. if other_testcase.issue_id is None: continue if (not updated_group_bug_information or updated_group_bug_information > other_testcase.issue_id): updated_group_bug_information = other_testcase.issue_id # If this group id is used by only one testcase, then remove it. if updated_group_id_count == 1: data_handler.delete_group(updated_group_id, update_testcases=False) updated_group_id = 0 updated_group_bug_information = 0 updated_is_leader = True try: testcase = data_handler.get_testcase_by_id(testcase_id) except errors.InvalidTestcaseError: # Already deleted. continue is_changed = ( (testcase.group_id != updated_group_id) or (testcase.group_bug_information != updated_group_bug_information) or (testcase.is_leader != updated_is_leader)) if not testcase.get_metadata('ran_grouper'): testcase.set_metadata('ran_grouper', True, update_testcase=not is_changed) if not is_changed: continue testcase.group_bug_information = updated_group_bug_information testcase.group_id = updated_group_id testcase.is_leader = updated_is_leader testcase.put() logs.log( 'Updated testcase %d group to %d.' % (testcase_id, updated_group_id))
Group testcases based on rules like same bug numbers, similar crash states, etc.
157,121
import datetime import json import logging import time from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import crash_stats class TooEarlyError(Exception): """The end hour is too early according to BIGQUERY_INSERTION_DELAY.""" def get_next_end_hour(): """Gets the next end hour. If it's too early to compute data for the next end hour, return None.""" last_successful_hour = get_last_successful_hour_or_start_hour() if not last_successful_hour: # No crashes seen, too early to start building stats. raise TooEarlyError() next_end_hour = last_successful_hour + 1 next_datetime = crash_stats.get_datetime(next_end_hour) if (utils.utcnow() - next_datetime) <= BIGQUERY_INSERTION_DELAY: raise TooEarlyError() return next_end_hour def build(end_hour): """Builds crash stats for the end hour.""" logging.info('Started building crash stats for %s.', crash_stats.get_datetime(end_hour)) job_id = JOB_ID_TEMPLATE.format(unique_number=int(time.time())) client = big_query.Client() make_request(client, job_id, end_hour) start_time = time.time() while (time.time() - start_time) < TIMEOUT: time.sleep(10) result = client.get_job(job_id) logging.info('Checking %s', json.dumps(result)) if result['status']['state'] == 'DONE': if result['status'].get('errors'): raise Exception(json.dumps(result)) # pylint: disable=broad-exception-raised return raise Exception('Building crash stats exceeded %d seconds.' % TIMEOUT) # pylint: disable=broad-exception-raised The provided code snippet includes necessary dependencies for implementing the `build_if_needed` function. Write a Python function `def build_if_needed()` to solve the following problem: Gets the next end hour and decide whether to execute build(). If build() succeeds, then record the next end hour. Here is the function: def build_if_needed(): """Gets the next end hour and decide whether to execute build(). If build() succeeds, then record the next end hour.""" try: end_hour = get_next_end_hour() build(end_hour) job_history = data_types.BuildCrashStatsJobHistory() job_history.end_time_in_hours = end_hour job_history.put() logging.info('CrashStatistics for end_hour=%s is built successfully', crash_stats.get_datetime(end_hour)) return end_hour except TooEarlyError: logging.info("Skip building crash stats because it's too early.") return None
Gets the next end hour and decide whether to execute build(). If build() succeeds, then record the next end hour.
157,122
import os import re from clusterfuzz._internal.base import errors from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment LSAN_TOOL_NAME = 'lsan' The provided code snippet includes necessary dependencies for implementing the `cleanup_global_blacklist` function. Write a Python function `def cleanup_global_blacklist()` to solve the following problem: Cleans out closed and deleted testcases from the global blacklist. Here is the function: def cleanup_global_blacklist(): """Cleans out closed and deleted testcases from the global blacklist.""" blacklists_to_delete = [] global_blacklists = data_types.Blacklist.query( data_types.Blacklist.tool_name == LSAN_TOOL_NAME) for blacklist in global_blacklists: testcase_id = blacklist.testcase_id try: testcase = data_handler.get_testcase_by_id(testcase_id) except errors.InvalidTestcaseError: testcase = None # Delete entry if testcase is closed, deleted, or unreproducible. if not testcase or not testcase.open or testcase.one_time_crasher_flag: blacklists_to_delete.append(blacklist.key) ndb_utils.delete_multi(blacklists_to_delete)
Cleans out closed and deleted testcases from the global blacklist.
157,123
import os import re from clusterfuzz._internal.base import errors from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment DIRECT_LEAK_REGEX = re.compile(r'^ *Direct leak of') FIRST_LEAK_DIVIDER = ('%s\nThe following leaks are not necessarily related ' 'to the first leak.\n\n' % ('=' * 80)) STACK_REGEX = re.compile(r'^ *#[0-9]+\s0x[A-Za-z0-9]+') STACK_START_REGEX = re.compile(r'^ *#0 ') BLANK_LINE_REGEX = re.compile(r'^\s*$') The provided code snippet includes necessary dependencies for implementing the `highlight_first_direct_leak` function. Write a Python function `def highlight_first_direct_leak(crash_stacktrace)` to solve the following problem: Highlights the first direct leak in a report. Args: crash_stacktrace: The crash report. Returns: new_report: Updated crash report with first direct leak highlighted. Here is the function: def highlight_first_direct_leak(crash_stacktrace): """Highlights the first direct leak in a report. Args: crash_stacktrace: The crash report. Returns: new_report: Updated crash report with first direct leak highlighted. """ new_report = [] processed_first_leak = False num_stacks = 0 highlighted_stack_index = 0 divider_index = 0 # Used to prevent highlighting on first indirect leak. direct_leak = False currently_highlighting = False for line in crash_stacktrace.splitlines(): if DIRECT_LEAK_REGEX.match(line): direct_leak = True # Marking the end of the highlighted stack with a divider. if BLANK_LINE_REGEX.match(line) and currently_highlighting: currently_highlighting = False processed_first_leak = True if STACK_REGEX.match(line): if STACK_START_REGEX.match(line): num_stacks += 1 if direct_leak and not processed_first_leak: highlighted_stack_index = num_stacks currently_highlighting = True # If the line is in the first stack, highlight. if currently_highlighting: line = '<b>%s</b>' % line if not processed_first_leak: divider_index += 1 new_report.append(line) # If there's only one stack, return original report. if num_stacks == 1: return crash_stacktrace # If there are leaks after the highlighted leak, insert a divider. if highlighted_stack_index != num_stacks: new_report.insert(divider_index + 1, FIRST_LEAK_DIVIDER) return '\n'.join(new_report)
Highlights the first direct leak in a report. Args: crash_stacktrace: The crash report. Returns: new_report: Updated crash report with first direct leak highlighted.
157,124
import collections from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import fuzz_target_utils from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment def update_mappings_for_fuzzer(fuzzer, mappings=None): """Clear existing mappings for a fuzzer, and replace them.""" if mappings is None: mappings = fuzzer.jobs query = data_types.FuzzerJob.query() query = query.filter(data_types.FuzzerJob.fuzzer == fuzzer.name) entities = ndb_utils.get_all_from_query(query) old_mappings = {} for entity in entities: old_mappings[entity.job] = entity new_mappings = [] for job_name in mappings: mapping = old_mappings.pop(job_name, None) if mapping: continue job = data_types.Job.query(data_types.Job.name == job_name).get() if not job: logs.log_error('An unknown job %s was selected for fuzzer %s.' % (job_name, fuzzer.name)) continue mapping = data_types.FuzzerJob() mapping.fuzzer = fuzzer.name mapping.job = job_name mapping.platform = job.platform new_mappings.append(mapping) ndb_utils.put_multi(new_mappings) ndb_utils.delete_multi([m.key for m in list(old_mappings.values())]) The provided code snippet includes necessary dependencies for implementing the `update_mappings_for_job` function. Write a Python function `def update_mappings_for_job(job, mappings)` to solve the following problem: Clear existing mappings for a job, and replace them. Here is the function: def update_mappings_for_job(job, mappings): """Clear existing mappings for a job, and replace them.""" existing_fuzzers = { fuzzer.name: fuzzer for fuzzer in data_types.Fuzzer.query() if job.name in fuzzer.jobs } modified_fuzzers = [] for fuzzer_name in mappings: fuzzer = existing_fuzzers.pop(fuzzer_name, None) if fuzzer: continue fuzzer = data_types.Fuzzer.query( data_types.Fuzzer.name == fuzzer_name).get() if not fuzzer: logs.log_error('An unknown fuzzer %s was selected for job %s.' % (fuzzer_name, job.name)) continue fuzzer.jobs.append(job.name) modified_fuzzers.append(fuzzer) update_mappings_for_fuzzer(fuzzer) # Removing the remaining values in exisiting_fuzzers as # they are no longer mapped. for fuzzer in existing_fuzzers.values(): fuzzer.jobs.remove(job.name) modified_fuzzers.append(fuzzer) update_mappings_for_fuzzer(fuzzer) ndb.put_multi(modified_fuzzers)
Clear existing mappings for a job, and replace them.
157,125
import collections from google.cloud import ndb from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.datastore import fuzz_target_utils from clusterfuzz._internal.datastore import ndb_utils from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment The provided code snippet includes necessary dependencies for implementing the `update_platform_for_job` function. Write a Python function `def update_platform_for_job(job_name, new_platform)` to solve the following problem: Update platform for all mappings for a particular job. Here is the function: def update_platform_for_job(job_name, new_platform): """Update platform for all mappings for a particular job.""" query = data_types.FuzzerJob.query() query = query.filter(data_types.FuzzerJob.job == job_name) mappings = ndb_utils.get_all_from_query(query) new_mappings = [] for mapping in mappings: mapping.platform = new_platform new_mappings.append(mapping) ndb_utils.put_multi(new_mappings)
Update platform for all mappings for a particular job.
157,126
import os import re import shutil from google.protobuf import timestamp_pb2 from clusterfuzz._internal.base import utils from clusterfuzz._internal.bot.tasks import task_types from clusterfuzz._internal.bot.tasks.utasks import uworker_io from clusterfuzz._internal.datastore import data_handler 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 from clusterfuzz._internal.system import shell def _rsync_errors_below_threshold(gsutil_result, max_errors): """Check if the number of errors during rsync is lower than our threshold.""" match = re.search(RSYNC_ERROR_REGEX, gsutil_result.output, re.MULTILINE) if not match: return False error_count = int(match.group(1)) # Ignore NotFoundException(s) since they can happen when files can get deleted # e.g. when pruning task is updating corpus. error_count -= gsutil_result.output.count(b'NotFoundException') error_count -= gsutil_result.output.count(b'No such file or directory') return error_count <= max_errors The provided code snippet includes necessary dependencies for implementing the `_handle_rsync_result` function. Write a Python function `def _handle_rsync_result(gsutil_result, max_errors)` to solve the following problem: Handle rsync result. Here is the function: def _handle_rsync_result(gsutil_result, max_errors): """Handle rsync result.""" if gsutil_result.return_code == 0: sync_succeeded = True else: logs.log_warn( 'gsutil rsync got non-zero:\n' 'Command: %s\n' 'Output: %s\n' % (gsutil_result.command, gsutil_result.output)) sync_succeeded = _rsync_errors_below_threshold(gsutil_result, max_errors) return sync_succeeded and not gsutil_result.timed_out
Handle rsync result.
157,127
import os import re import shutil from google.protobuf import timestamp_pb2 from clusterfuzz._internal.base import utils from clusterfuzz._internal.bot.tasks import task_types from clusterfuzz._internal.bot.tasks.utasks import uworker_io from clusterfuzz._internal.datastore import data_handler 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 from clusterfuzz._internal.system import shell The provided code snippet includes necessary dependencies for implementing the `_count_corpus_files` function. Write a Python function `def _count_corpus_files(directory)` to solve the following problem: Count the number of corpus files. Here is the function: def _count_corpus_files(directory): """Count the number of corpus files.""" return shell.get_directory_file_count(directory)
Count the number of corpus files.
157,128
import os import re import shutil from google.protobuf import timestamp_pb2 from clusterfuzz._internal.base import utils from clusterfuzz._internal.bot.tasks import task_types from clusterfuzz._internal.bot.tasks.utasks import uworker_io from clusterfuzz._internal.datastore import data_handler 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 from clusterfuzz._internal.system import shell def legalize_filenames(file_paths): """Convert the name of every file in |file_paths| a name that is legal on Windows. Returns list of legally named files.""" if environment.is_trusted_host(): return file_paths illegal_chars = {'<', '>', ':', '\\', '|', '?', '*'} failed_to_move_files = [] legally_named = [] for file_path in file_paths: file_dir_path, basename = os.path.split(file_path) if not any(char in illegal_chars for char in basename): legally_named.append(file_path) continue # Hash file to get new name since it also lets us get rid of duplicates, # will not cause collisions for different files and makes things more # consistent (since libFuzzer uses hashes). sha1sum = utils.file_hash(file_path) new_file_path = os.path.join(file_dir_path, sha1sum) try: shutil.move(file_path, new_file_path) legally_named.append(new_file_path) except OSError: failed_to_move_files.append((file_path, new_file_path)) if failed_to_move_files: logs.log_error( 'Failed to rename files.', failed_to_move_files=failed_to_move_files) return legally_named The provided code snippet includes necessary dependencies for implementing the `legalize_corpus_files` function. Write a Python function `def legalize_corpus_files(directory)` to solve the following problem: Convert the name of every corpus file in |directory| to a name that is allowed on Windows. Here is the function: def legalize_corpus_files(directory): """Convert the name of every corpus file in |directory| to a name that is allowed on Windows.""" # Iterate through return value of legalize_filenames to convert every # filename. files_list = shell.get_files_list(directory) legalize_filenames(files_list)
Convert the name of every corpus file in |directory| to a name that is allowed on Windows.
157,129
import os import re import shutil from google.protobuf import timestamp_pb2 from clusterfuzz._internal.base import utils from clusterfuzz._internal.bot.tasks import task_types from clusterfuzz._internal.bot.tasks.utasks import uworker_io from clusterfuzz._internal.datastore import data_handler 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 from clusterfuzz._internal.system import shell def download_corpus(corpus, directory): storage.download_signed_urls(corpus.download_urls, directory) storage.download_signed_urls(corpus.regression_download_urls, directory)
null
157,130
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `create_directory` function. Write a Python function `def create_directory(request, _)` to solve the following problem: Create a directory. Here is the function: def create_directory(request, _): """Create a directory.""" result = shell.create_directory(request.path, request.create_intermediates) return untrusted_runner_pb2.CreateDirectoryResponse(result=result)
Create a directory.
157,131
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `remove_directory` function. Write a Python function `def remove_directory(request, _)` to solve the following problem: Remove a directory. Here is the function: def remove_directory(request, _): """Remove a directory.""" result = shell.remove_directory(request.path, request.recreate) return untrusted_runner_pb2.RemoveDirectoryResponse(result=result)
Remove a directory.
157,132
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `list_files` function. Write a Python function `def list_files(request, _)` to solve the following problem: List files. Here is the function: def list_files(request, _): """List files.""" file_paths = [] if request.recursive: for root, _, files in shell.walk(request.path): for filename in files: file_paths.append(os.path.join(root, filename)) else: file_paths.extend( os.path.join(request.path, path) for path in os.listdir(request.path)) return untrusted_runner_pb2.ListFilesResponse(file_paths=file_paths)
List files.
157,133
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `copy_file_to_worker` function. Write a Python function `def copy_file_to_worker(request_iterator, context)` to solve the following problem: Copy file from host to worker. Here is the function: def copy_file_to_worker(request_iterator, context): """Copy file from host to worker.""" metadata = dict(context.invocation_metadata()) path = metadata['path-bin'].decode('utf-8') # Create intermediate directories if needed. directory = os.path.dirname(path) if not os.path.exists(directory): try: os.makedirs(directory) except Exception: pass if not os.path.isdir(directory): # Failed to create intermediate directories. return untrusted_runner_pb2.CopyFileToResponse(result=False) file_utils.write_chunks(path, request_iterator) return untrusted_runner_pb2.CopyFileToResponse(result=True)
Copy file from host to worker.
157,134
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `copy_file_from_worker` function. Write a Python function `def copy_file_from_worker(request, context)` to solve the following problem: Copy file from worker to host. Here is the function: def copy_file_from_worker(request, context): """Copy file from worker to host.""" path = request.path if not os.path.isfile(path): context.set_trailing_metadata([('result', 'invalid-path')]) return with open(path, 'rb') as f: yield from file_utils.file_chunk_generator(f) context.set_trailing_metadata([('result', 'ok')])
Copy file from worker to host.
157,135
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `stat` function. Write a Python function `def stat(request, _)` to solve the following problem: Stat a path. Here is the function: def stat(request, _): """Stat a path.""" if not os.path.exists(request.path): return untrusted_runner_pb2.StatResponse(result=False) stat_result = os.stat(request.path) return untrusted_runner_pb2.StatResponse( result=True, st_mode=stat_result.st_mode, st_size=stat_result.st_size, st_atime=stat_result.st_atime, st_mtime=stat_result.st_mtime, st_ctime=stat_result.st_ctime)
Stat a path.
157,136
import os from clusterfuzz._internal.bot.fuzzers import utils as fuzzers_utils from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import shell from . import file_utils The provided code snippet includes necessary dependencies for implementing the `get_fuzz_targets` function. Write a Python function `def get_fuzz_targets(request, _)` to solve the following problem: Get list of fuzz targets. Here is the function: def get_fuzz_targets(request, _): """Get list of fuzz targets.""" fuzz_target_paths = fuzzers_utils.get_fuzz_targets_local(request.path) return untrusted_runner_pb2.GetFuzzTargetsResponse( fuzz_target_paths=fuzz_target_paths)
Get list of fuzz targets.
157,137
from clusterfuzz._internal.build_management import build_manager from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import environment from . import host def _clear_env(): """Clear build env vars.""" environment.remove_key('APP_PATH') environment.remove_key('APP_REVISION') environment.remove_key('APP_PATH_DEBUG') environment.remove_key('APP_DIR') environment.remove_key('BUILD_DIR') environment.remove_key('BUILD_URL') environment.remove_key('FUZZ_TARGET') def _update_env_from_response(response): """Update environment variables from response.""" environment.set_value('APP_PATH', response.app_path) environment.set_value('APP_PATH_DEBUG', response.app_path_debug) environment.set_value('APP_DIR', response.app_dir) environment.set_value('BUILD_DIR', response.build_dir) environment.set_value('BUILD_URL', response.build_url) environment.set_value('FUZZ_TARGET', response.fuzz_target) environment.set_value('FUZZ_TARGET_COUNT', response.fuzz_target_count) The provided code snippet includes necessary dependencies for implementing the `_handle_response` function. Write a Python function `def _handle_response(build, response)` to solve the following problem: Handle build setup response. Here is the function: def _handle_response(build, response): """Handle build setup response.""" if not response.result: _clear_env() return False _update_env_from_response(response) if not environment.get_value('APP_PATH'): fuzzer_directory = environment.get_value('FUZZER_DIR') if fuzzer_directory: build_manager.set_environment_vars([fuzzer_directory]) environment.set_value('APP_REVISION', build.revision) return True
Handle build setup response.
157,138
import datetime from google.protobuf import wrappers_pb2 import grpc from clusterfuzz._internal.bot import testcase_manager from clusterfuzz._internal.bot.tasks.utasks import corpus_pruning_task from clusterfuzz._internal.bot.untrusted_runner import file_host from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz.fuzz import engine from . import host The provided code snippet includes necessary dependencies for implementing the `engine_reproduce` function. Write a Python function `def engine_reproduce(engine_impl, target_name, testcase_path, arguments, timeout)` to solve the following problem: Run engine reproduce on untrusted worker. Here is the function: def engine_reproduce(engine_impl, target_name, testcase_path, arguments, timeout): """Run engine reproduce on untrusted worker.""" rebased_testcase_path = file_host.rebase_to_worker_root(testcase_path) file_host.copy_file_to_worker(testcase_path, rebased_testcase_path) request = untrusted_runner_pb2.EngineReproduceRequest( engine=engine_impl.name, target_name=target_name, testcase_path=rebased_testcase_path, arguments=arguments, timeout=timeout) try: response = host.stub().EngineReproduce(request) except grpc.RpcError as e: if 'TargetNotFoundError' in repr(e): # Resurface the right exception. raise testcase_manager.TargetNotFoundError('Failed to find target ' + target_name) raise return engine.ReproduceResult( list(response.command), response.return_code, response.time_executed, response.output)
Run engine reproduce on untrusted worker.
157,139
from clusterfuzz._internal.build_management import build_manager from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import environment def _build_response(result): if not result: return untrusted_runner_pb2.SetupBuildResponse(result=False) return untrusted_runner_pb2.SetupBuildResponse( result=True, app_path=environment.get_value('APP_PATH'), app_path_debug=environment.get_value('APP_PATH_DEBUG'), app_dir=environment.get_value('APP_DIR'), build_dir=environment.get_value('BUILD_DIR'), build_url=environment.get_value('BUILD_URL'), fuzz_target=environment.get_value('FUZZ_TARGET'), fuzz_target_count=environment.get_value('FUZZ_TARGET_COUNT')) The provided code snippet includes necessary dependencies for implementing the `setup_regular_build` function. Write a Python function `def setup_regular_build(request)` to solve the following problem: Set up a regular build. Here is the function: def setup_regular_build(request): """Set up a regular build.""" build = build_manager.RegularBuild(request.base_build_dir, request.revision, request.build_url, request.target_weights, request.build_prefix) return _build_response(build.setup())
Set up a regular build.
157,140
from clusterfuzz._internal.crash_analysis.stack_parsing import stack_symbolizer from clusterfuzz._internal.protos import untrusted_runner_pb2 The provided code snippet includes necessary dependencies for implementing the `symbolize_stacktrace` function. Write a Python function `def symbolize_stacktrace(request)` to solve the following problem: Symbolize stacktrace. Here is the function: def symbolize_stacktrace(request): """Symbolize stacktrace.""" symbolized_stacktrace = stack_symbolizer.symbolize_stacktrace( request.unsymbolized_crash_stacktrace, request.enable_inline_frames) return untrusted_runner_pb2.SymbolizeStacktraceResponse( # pylint: disable=no-member symbolized_stacktrace=symbolized_stacktrace)
Symbolize stacktrace.
157,141
import os import re def set_environment_vars(env, source_env): """Copy allowed environment variables from |source_env|.""" if not source_env: return for name, value in source_env.items(): if is_forwarded_environment_variable(name): # Avoid creating circular dependencies from importing environment by # using os.getenv. if os.getenv('TRUSTED_HOST') and should_rebase_environment_value(name): value = file_host.rebase_to_worker_root(value) env[name] = value The provided code snippet includes necessary dependencies for implementing the `get_env_for_untrusted_process` function. Write a Python function `def get_env_for_untrusted_process(overrides)` to solve the following problem: Return environment for running an untrusted process. Here is the function: def get_env_for_untrusted_process(overrides): """Return environment for running an untrusted process.""" env = {} if overrides is not None: set_environment_vars(env, overrides) else: set_environment_vars(env, os.environ) return env
Return environment for running an untrusted process.
157,142
import os import re The provided code snippet includes necessary dependencies for implementing the `reset_environment` function. Write a Python function `def reset_environment()` to solve the following problem: Reset environment variables. Here is the function: def reset_environment(): """Reset environment variables.""" request = untrusted_runner_pb2.ResetEnvironmentRequest() # pylint: disable=no-member host.stub().ResetEnvironment(request)
Reset environment variables.
157,143
from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import new_process from clusterfuzz._internal.system import process_handler from . import protobuf_utils def process_result_to_proto(process_result): """Convert new_process.ProcessResult to proto.""" process_result_proto = untrusted_runner_pb2.ProcessResult( # pylint: disable=no-member return_code=process_result.return_code, output=process_result.output, time_executed=process_result.time_executed, timed_out=process_result.timed_out) process_result_proto.command.extend(process_result.command) # pylint: disable=no-member return process_result_proto The provided code snippet includes necessary dependencies for implementing the `run_and_wait` function. Write a Python function `def run_and_wait(request, _)` to solve the following problem: Implementation of RunAndWait. Here is the function: def run_and_wait(request, _): """Implementation of RunAndWait.""" process_runner = new_process.ProcessRunner(request.executable_path, request.default_args) args = {} protobuf_utils.get_protobuf_field(args, request.popen_args, 'bufsize') protobuf_utils.get_protobuf_field(args, request.popen_args, 'executable') protobuf_utils.get_protobuf_field(args, request.popen_args, 'shell') protobuf_utils.get_protobuf_field(args, request.popen_args, 'cwd') if request.popen_args.env_is_set: args['env'] = request.popen_args.env else: args['env'] = None args['additional_args'] = request.additional_args protobuf_utils.get_protobuf_field(args, request, 'timeout') protobuf_utils.get_protobuf_field(args, request, 'terminate_before_kill') protobuf_utils.get_protobuf_field(args, request, 'terminate_wait_time') protobuf_utils.get_protobuf_field(args, request, 'input_data') protobuf_utils.get_protobuf_field(args, request, 'max_stdout_len') logs.log('Running command: %s' % process_runner.get_command()) return untrusted_runner_pb2.RunAndWaitResponse( # pylint: disable=no-member result=process_result_to_proto(process_runner.run_and_wait(**args)))
Implementation of RunAndWait.
157,144
from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import new_process from clusterfuzz._internal.system import process_handler from . import protobuf_utils The provided code snippet includes necessary dependencies for implementing the `run_process` function. Write a Python function `def run_process(request, _)` to solve the following problem: Implementation of RunProcess. Here is the function: def run_process(request, _): """Implementation of RunProcess.""" args = {} protobuf_utils.get_protobuf_field(args, request, 'cmdline') protobuf_utils.get_protobuf_field(args, request, 'current_working_directory') protobuf_utils.get_protobuf_field(args, request, 'timeout') protobuf_utils.get_protobuf_field(args, request, 'need_shell') if request.gestures: args['gestures'] = request.gestures if request.env_copy: args['env_copy'] = request.env_copy protobuf_utils.get_protobuf_field(args, request, 'testcase_run') protobuf_utils.get_protobuf_field(args, request, 'ignore_children') return_code, execution_time, output = process_handler.run_process(**args) response = untrusted_runner_pb2.RunProcessResponse( # pylint: disable=no-member return_code=return_code, execution_time=execution_time, output=output) return response
Implementation of RunProcess.
157,145
import os import subprocess from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import new_process from clusterfuzz._internal.system import process_handler from . import environment from . import host The provided code snippet includes necessary dependencies for implementing the `process_result_from_proto` function. Write a Python function `def process_result_from_proto(process_result_proto)` to solve the following problem: Convert ProcessResult proto to new_process.ProcessResult. Here is the function: def process_result_from_proto(process_result_proto): """Convert ProcessResult proto to new_process.ProcessResult.""" return new_process.ProcessResult( process_result_proto.command, process_result_proto.return_code, process_result_proto.output, process_result_proto.time_executed, process_result_proto.timed_out)
Convert ProcessResult proto to new_process.ProcessResult.
157,146
import os import subprocess from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import new_process from clusterfuzz._internal.system import process_handler from . import environment from . import host The provided code snippet includes necessary dependencies for implementing the `run_process` function. Write a Python function `def run_process(cmdline, current_working_directory=None, timeout=process_handler.DEFAULT_TEST_TIMEOUT, need_shell=False, gestures=None, env_copy=None, testcase_run=True, ignore_children=True)` to solve the following problem: Remote version of process_handler.run_process. Here is the function: def run_process(cmdline, current_working_directory=None, timeout=process_handler.DEFAULT_TEST_TIMEOUT, need_shell=False, gestures=None, env_copy=None, testcase_run=True, ignore_children=True): """Remote version of process_handler.run_process.""" request = untrusted_runner_pb2.RunProcessRequest( cmdline=cmdline, current_working_directory=current_working_directory, timeout=timeout, need_shell=need_shell, testcase_run=testcase_run, ignore_children=ignore_children) if gestures: request.gestures.extend(gestures) env = {} # run_process's local behaviour is to apply the passed |env_copy| on top of # the current environment instead of replacing it completely (like with # subprocess). environment.set_environment_vars(env, os.environ) environment.set_environment_vars(env, env_copy) request.env_copy.update(env) response = host.stub().RunProcess(request) return response.return_code, response.execution_time, response.output
Remote version of process_handler.run_process.
157,147
import sys import threading import time from google.cloud import ndb import grpc from clusterfuzz._internal.base import untrusted from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.metrics import monitoring_metrics from clusterfuzz._internal.protos import heartbeat_pb2 from clusterfuzz._internal.protos import heartbeat_pb2_grpc from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.protos import untrusted_runner_pb2_grpc from clusterfuzz._internal.system import environment from . import config RPC_FAIL_WAIT_TIME = 10 class ChannelState: """The host's view of the channel state.""" # Channel isn't ready for sending RPCs. NOT_READY = 0 # Channel is ready for RPCS. READY = 1 # The host found that the worker is in an inconsistent state. That is, we # detected that either the worker has a different source version, or if it # restarted without us knowing. INCONSISTENT = 2 def _check_channel_state(wait_time): """Check the channel's state.""" with _host_state.channel_condition: if (_host_state.channel_state in (ChannelState.READY, ChannelState.INCONSISTENT)): # Nothing to do in these states. return _host_state.channel_state # The channel is not ready, so we wait for a (re)connect. _host_state.channel_condition.wait(wait_time) return _host_state.channel_state def host_exit_no_return(return_code=1): """Called when there is a host error.""" if return_code: monitoring_metrics.HOST_ERROR_COUNT.increment({'return_code': return_code}) # Always try to get the worker to exit too. update_worker() # Prevent exceptions during shutdown. _host_state.channel.unsubscribe(_channel_connectivity_changed) # This should bypass most exception handlers and avoid callers from catching # this incorrectly. logs.log('Shutting down host.', return_code=return_code) raise untrusted.HostError(return_code) The provided code snippet includes necessary dependencies for implementing the `_wrap_call` function. Write a Python function `def _wrap_call(func, num_retries=config.RPC_RETRY_ATTEMPTS)` to solve the following problem: Wrapper for stub calls to add error handling and retry logic. Here is the function: def _wrap_call(func, num_retries=config.RPC_RETRY_ATTEMPTS): """Wrapper for stub calls to add error handling and retry logic.""" def wrapped(*args, **kwargs): """Wrapper for adding retry logic.""" for retry_attempt in range(num_retries + 1): # Wait for channel to (re)connect if necessary. state = _check_channel_state(config.RECONNECT_TIMEOUT_SECONDS) if state == ChannelState.INCONSISTENT: # No point retrying if the worker is inconsistent. monitoring_metrics.HOST_INCONSISTENT_COUNT.increment() logs.log_warn('Worker got into an inconsistent state.') host_exit_no_return(return_code=0) if state == ChannelState.NOT_READY: # Channel still isn't ready. logs.log_warn( 'Channel failed to become ready within reconnect timeout.') if retry_attempt == num_retries: # Last attempt. host_exit_no_return() continue try: return func(*args, **kwargs) except grpc.RpcError as e: # For timeouts, which aren't fatal errors, resurface the right # exception. if 'TimeoutError' in repr(e): raise TimeoutError(str(e)) if num_retries == 0: # Just re-raise the original exception if this RPC is not configured # for retries. raise logs.log_warn('Failed RPC: ' + repr(e)) if retry_attempt == num_retries: # Last attempt. host_exit_no_return() time.sleep(RPC_FAIL_WAIT_TIME) return None return wrapped
Wrapper for stub calls to add error handling and retry logic.
157,148
import sys import threading import time from google.cloud import ndb import grpc from clusterfuzz._internal.base import untrusted from clusterfuzz._internal.base import utils from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.metrics import monitoring_metrics from clusterfuzz._internal.protos import heartbeat_pb2 from clusterfuzz._internal.protos import heartbeat_pb2_grpc from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.protos import untrusted_runner_pb2_grpc from clusterfuzz._internal.system import environment from . import config def _connect(): """Initial connect to the worker.""" worker_assignment = _get_host_worker_assignment() assert worker_assignment is not None assert worker_assignment.worker_name is not None assert worker_assignment.project_name is not None root_cert = _get_root_cert(worker_assignment.project_name) if not root_cert: logs.log_warn('TLS certs not yet generated.') time.sleep(WAIT_TLS_CERT_SECONDS) sys.exit(0) environment.set_value( 'QUEUE_OVERRIDE', untrusted.platform_name(worker_assignment.project_name, 'linux')) server_name = worker_assignment.worker_name if not environment.get_value('LOCAL_DEVELOPMENT'): server_name += untrusted.internal_network_domain() _host_state.worker_bot_name = worker_assignment.worker_name credentials = grpc.ssl_channel_credentials(root_cert) _host_state.channel = grpc.secure_channel( '%s:%d' % (server_name, config.PORT), credentials=credentials, options=config.GRPC_OPTIONS) _host_state.stub = UntrustedRunnerStub(_host_state.channel) logs.log('Connecting to worker %s...' % server_name) _host_state.channel.subscribe( _channel_connectivity_changed, try_to_connect=True) channel_state = _check_channel_state(config.INITIAL_CONNECT_TIMEOUT_SECONDS) if channel_state == ChannelState.INCONSISTENT: logs.log_warn('Worker inconsistent on initial connect.') monitoring_metrics.HOST_INCONSISTENT_COUNT.increment() host_exit_no_return(return_code=0) if channel_state != ChannelState.READY: raise untrusted.HostError('Failed to connect to worker.') environment.set_value('WORKER_BOT_NAME', worker_assignment.worker_name) _host_state.heartbeat_thread = threading.Thread(target=_do_heartbeat) _host_state.heartbeat_thread.daemon = True _host_state.heartbeat_thread.start() The provided code snippet includes necessary dependencies for implementing the `init` function. Write a Python function `def init()` to solve the following problem: Initialize channel to untrusted instance. Here is the function: def init(): """Initialize channel to untrusted instance.""" _connect()
Initialize channel to untrusted instance.
157,149
from clusterfuzz._internal.protos import untrusted_runner_pb2 from . import host from . import protobuf_utils The provided code snippet includes necessary dependencies for implementing the `symbolize_stacktrace` function. Write a Python function `def symbolize_stacktrace(unsymbolized_crash_stacktrace, enable_inline_frames=True)` to solve the following problem: Symbolize stacktrace. Here is the function: def symbolize_stacktrace(unsymbolized_crash_stacktrace, enable_inline_frames=True): """Symbolize stacktrace.""" request = untrusted_runner_pb2.SymbolizeStacktraceRequest( # pylint: disable=no-member unsymbolized_crash_stacktrace=protobuf_utils.encode_utf8_if_unicode( unsymbolized_crash_stacktrace), enable_inline_frames=enable_inline_frames) response = host.stub().SymbolizeStacktrace(request) return response.symbolized_stacktrace
Symbolize stacktrace.
157,150
from google.protobuf import wrappers_pb2 from google.protobuf.any_pb2 import Any from clusterfuzz._internal.bot import testcase_manager 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.datastore import data_types from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz.fuzz import engine def _proto_to_fuzz_target(proto): """Convert protobuf to FuzzTarget.""" return data_types.FuzzTarget( engine=proto.engine, project=proto.project, binary=proto.binary) def _proto_to_cross_pollinate_fuzzer(proto): """Convert protobuf to CrossPollinateFuzzer.""" return corpus_pruning_task.CrossPollinateFuzzer( fuzz_target=_proto_to_fuzz_target(proto.fuzz_target), backup_bucket_name=proto.backup_bucket_name, corpus_engine_name=proto.corpus_engine_name) The provided code snippet includes necessary dependencies for implementing the `prune_corpus` function. Write a Python function `def prune_corpus(request, _)` to solve the following problem: Prune corpus. Here is the function: def prune_corpus(request, _): """Prune corpus.""" context = corpus_pruning_task.Context( None, _proto_to_fuzz_target(request.fuzz_target), [ _proto_to_cross_pollinate_fuzzer(proto) for proto in request.cross_pollinate_fuzzers ]) result = corpus_pruning_task.do_corpus_pruning(context, request.revision) cross_pollination_stats = None if result.cross_pollination_stats: cross_pollination_stats = untrusted_runner_pb2.CrossPollinationStats( project_qualified_name=result.cross_pollination_stats. project_qualified_name, sources=result.cross_pollination_stats.sources, initial_corpus_size=result.cross_pollination_stats.initial_corpus_size, corpus_size=result.cross_pollination_stats.corpus_size, initial_edge_coverage=result.cross_pollination_stats. initial_edge_coverage, edge_coverage=result.cross_pollination_stats.edge_coverage, initial_feature_coverage=result.cross_pollination_stats. initial_feature_coverage, feature_coverage=result.cross_pollination_stats.feature_coverage) # 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 = untrusted_runner_pb2.CoverageInfo( corpus_size_units=result.coverage_info.corpus_size_units, corpus_size_bytes=result.coverage_info.corpus_size_bytes, corpus_location=result.coverage_info.corpus_location, corpus_backup_location=result.coverage_info.corpus_backup_location, quarantine_size_units=result.coverage_info.quarantine_size_units, quarantine_size_bytes=result.coverage_info.quarantine_size_bytes, quarantine_location=result.coverage_info.quarantine_location) crashes = [ untrusted_runner_pb2.CorpusCrash( crash_state=crash.crash_state, crash_type=crash.crash_type, crash_address=crash.crash_address, crash_stacktrace=crash.crash_stacktrace, unit_path=crash.unit_path, security_flag=crash.security_flag, ) for crash in result.crashes ] return untrusted_runner_pb2.PruneCorpusResponse( coverage_info=coverage_info, crashes=crashes, fuzzer_binary_name=result.fuzzer_binary_name, revision=result.revision, cross_pollination_stats=cross_pollination_stats)
Prune corpus.
157,151
from google.protobuf import wrappers_pb2 from google.protobuf.any_pb2 import Any from clusterfuzz._internal.bot import testcase_manager 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.datastore import data_types from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz.fuzz import engine The provided code snippet includes necessary dependencies for implementing the `process_testcase` function. Write a Python function `def process_testcase(request, _)` to solve the following problem: Process testcase. Here is the function: def process_testcase(request, _): """Process testcase.""" tool_name_map = { untrusted_runner_pb2.ProcessTestcaseRequest.MINIMIZE: 'minimize', untrusted_runner_pb2.ProcessTestcaseRequest.CLEANSE: 'cleanse', } # TODO(ochang): Support other engines. assert request.engine == 'libFuzzer' assert request.operation in tool_name_map result = minimize_task.run_libfuzzer_engine( tool_name_map[request.operation], request.target_name, request.arguments, request.testcase_path, request.output_path, request.timeout) return untrusted_runner_pb2.EngineReproduceResult( return_code=result.return_code, time_executed=result.time_executed, output=result.output)
Process testcase.
157,152
from google.protobuf import wrappers_pb2 from google.protobuf.any_pb2 import Any from clusterfuzz._internal.bot import testcase_manager 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.datastore import data_types from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz.fuzz import engine def _pack_values(values): """Pack protobuf values.""" packed = {} if values is None: return packed for key, value in values.items(): packed_value = Any() if isinstance(value, float): packed_value.Pack(wrappers_pb2.DoubleValue(value=value)) elif isinstance(value, int): packed_value.Pack(wrappers_pb2.Int64Value(value=value)) elif isinstance(value, str): packed_value.Pack(wrappers_pb2.StringValue(value=value)) else: raise ValueError('Unknown stat type for ' + key) packed[key] = packed_value return packed The provided code snippet includes necessary dependencies for implementing the `engine_fuzz` function. Write a Python function `def engine_fuzz(request, _)` to solve the following problem: Run engine fuzzer. Here is the function: def engine_fuzz(request, _): """Run engine fuzzer.""" engine_impl = engine.get(request.engine) result, fuzzer_metadata, strategies = fuzz_task.run_engine_fuzzer( engine_impl, request.target_name, request.sync_corpus_directory, request.testcase_directory) crashes = [ untrusted_runner_pb2.EngineCrash( input_path=crash.input_path, stacktrace=crash.stacktrace, reproduce_args=crash.reproduce_args, crash_time=crash.crash_time) for crash in result.crashes ] packed_stats = _pack_values(result.stats) packed_strategies = _pack_values(strategies) return untrusted_runner_pb2.EngineFuzzResponse( logs=result.logs, command=result.command, crashes=crashes, stats=packed_stats, time_executed=result.time_executed, fuzzer_metadata=fuzzer_metadata, strategies=packed_strategies)
Run engine fuzzer.
157,153
from google.protobuf import wrappers_pb2 from google.protobuf.any_pb2 import Any from clusterfuzz._internal.bot import testcase_manager 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.datastore import data_types from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz.fuzz import engine The provided code snippet includes necessary dependencies for implementing the `engine_reproduce` function. Write a Python function `def engine_reproduce(request, _)` to solve the following problem: Run engine reproduce. Here is the function: def engine_reproduce(request, _): """Run engine reproduce.""" engine_impl = engine.get(request.engine) result = testcase_manager.engine_reproduce(engine_impl, request.target_name, request.testcase_path, request.arguments, request.timeout) return untrusted_runner_pb2.EngineReproduceResult( command=result.command, return_code=result.return_code, time_executed=result.time_executed, output=result.output)
Run engine reproduce.
157,154
from concurrent import futures import functools import os import threading import time import traceback import grpc from clusterfuzz._internal.base import utils from clusterfuzz._internal.google_cloud_utils import compute_metadata from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import heartbeat_pb2 from clusterfuzz._internal.protos import heartbeat_pb2_grpc from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.protos import untrusted_runner_pb2_grpc from clusterfuzz._internal.system import environment from clusterfuzz._internal.system import process_handler from clusterfuzz._internal.system import shell from . import build_setup from . import config from . import file_impl from . import remote_process from . import symbolize from . import tasks_impl _worker_state = WorkerState() _rpc_count_lock = threading.Lock() _rpc_count = 0 The provided code snippet includes necessary dependencies for implementing the `wrap_servicer` function. Write a Python function `def wrap_servicer(func)` to solve the following problem: Wrap a servicer to add additional functionality. Here is the function: def wrap_servicer(func): """Wrap a servicer to add additional functionality.""" @functools.wraps(func) def wrapper(self, request, context): # pylint: disable=unused-argument """Wrapper function.""" global _rpc_count # Check if there is a in-progress RPC. with _rpc_count_lock: if _rpc_count > 0: logs.log_error('Hung RPC detected, shutting down.') _worker_state.shutting_down.set() return None _rpc_count += 1 try: result = func(self, request, context) except Exception: # Include full exception details. context.set_code(grpc.StatusCode.UNKNOWN) context.set_details(traceback.format_exc()) raise finally: with _rpc_count_lock: assert _rpc_count > 0 _rpc_count -= 1 return result return wrapper
Wrap a servicer to add additional functionality.
157,155
from concurrent import futures import functools import os import threading import time import traceback import grpc from clusterfuzz._internal.base import utils from clusterfuzz._internal.google_cloud_utils import compute_metadata from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import heartbeat_pb2 from clusterfuzz._internal.protos import heartbeat_pb2_grpc from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.protos import untrusted_runner_pb2_grpc from clusterfuzz._internal.system import environment from clusterfuzz._internal.system import process_handler from clusterfuzz._internal.system import shell from . import build_setup from . import config from . import file_impl from . import remote_process from . import symbolize from . import tasks_impl SHUTDOWN_GRACE_SECONDS = 5 _worker_state = WorkerState() class UntrustedRunnerServicer( untrusted_runner_pb2_grpc.UntrustedRunnerServicer): """Untrusted runner implementation.""" def GetStatus(self, request, context): # pylint: disable=unused-argument return untrusted_runner_pb2.GetStatusResponse( revision=utils.current_source_version(), start_time=_worker_state.start_time, bot_name=environment.get_value('BOT_NAME')) def SetupRegularBuild(self, request, _): return build_setup.setup_regular_build(request) def RunAndWait(self, request, context): return remote_process.run_and_wait(request, context) def RunProcess(self, request, context): return remote_process.run_process(request, context) def CreateDirectory(self, request, context): return file_impl.create_directory(request, context) def RemoveDirectory(self, request, context): return file_impl.remove_directory(request, context) def ListFiles(self, request, context): return file_impl.list_files(request, context) def CopyFileTo(self, request_iterator, context): return file_impl.copy_file_to_worker(request_iterator, context) def CopyFileFrom(self, request, context): return file_impl.copy_file_from_worker(request, context) def Stat(self, request, context): return file_impl.stat(request, context) def UpdateEnvironment(self, request, _): os.environ.update(request.env) return untrusted_runner_pb2.UpdateEnvironmentResponse() def ResetEnvironment(self, _, context): # pylint: disable=unused-argument environment.reset_environment() return untrusted_runner_pb2.ResetEnvironmentResponse() def UpdateSource(self, request, context): # pylint: disable=unused-argument # Exit and let run.py update source. _worker_state.shutting_down.set() return untrusted_runner_pb2.UpdateSourceResponse() def SymbolizeStacktrace(self, request, _): return symbolize.symbolize_stacktrace(request) def TerminateStaleApplicationInstances(self, request, context): # pylint: disable=unused-argument process_handler.terminate_stale_application_instances() return untrusted_runner_pb2.TerminateStaleApplicationInstancesResponse() def GetFuzzTargets(self, request, context): return file_impl.get_fuzz_targets(request, context) def ProcessTestcase(self, request, context): return tasks_impl.process_testcase(request, context) def EngineFuzz(self, request, context): return tasks_impl.engine_fuzz(request, context) def EngineReproduce(self, request, context): return tasks_impl.engine_reproduce(request, context) def PruneCorpus(self, request, context): return tasks_impl.prune_corpus(request, context) class HeartbeatServicer(heartbeat_pb2_grpc.HeartbeatServicer): """Heartbeat service (for keeping connections alive).""" def Beat(self, _, context): # pylint: disable=unused-argument return heartbeat_pb2.HeartbeatResponse() def _get_tls_cert_and_key(): """Get the TLS cert from instance metadata.""" # TODO(ochang): Implement a fake metadata server for testing. local_cert_location = environment.get_value('UNTRUSTED_TLS_CERT_FOR_TESTING') local_key_location = environment.get_value('UNTRUSTED_TLS_KEY_FOR_TESTING') if local_cert_location and local_key_location: with open(local_cert_location, 'rb') as f: cert_contents = f.read() with open(local_key_location, 'rb') as f: key_contents = f.read() return cert_contents, key_contents cert_contents = compute_metadata.get('instance/attributes/tls-cert').encode() key_contents = compute_metadata.get('instance/attributes/tls-key').encode() return cert_contents, key_contents def server(): """Return the grpc.Server.""" return _worker_state.server The provided code snippet includes necessary dependencies for implementing the `start_server` function. Write a Python function `def start_server()` to solve the following problem: Start the server. Here is the function: def start_server(): """Start the server.""" # Check overall free disk space. If we are running too low, clear all # data directories like builds, fuzzers, data bundles, etc. shell.clear_data_directories_on_low_disk_space() cert_contents, key_contents = _get_tls_cert_and_key() assert cert_contents and key_contents server_credentials = grpc.ssl_server_credentials([(key_contents, cert_contents)]) _worker_state.server = grpc.server( futures.ThreadPoolExecutor(max_workers=config.NUM_WORKER_THREADS), options=config.GRPC_OPTIONS) untrusted_runner_pb2_grpc.add_UntrustedRunnerServicer_to_server( UntrustedRunnerServicer(), _worker_state.server) heartbeat_pb2_grpc.add_HeartbeatServicer_to_server(HeartbeatServicer(), _worker_state.server) _worker_state.server.add_secure_port('[::]:%d' % config.PORT, server_credentials) _worker_state.start_time = int(time.time()) _worker_state.server.start() logs.log('Server started.') # Run forever until shutdown. _worker_state.shutting_down.wait() logs.log('Server shutting down.') stopped = _worker_state.server.stop(SHUTDOWN_GRACE_SECONDS) stopped.wait() # Prevent python GIL deadlocks on shutdown. See https://crbug.com/744680. # pylint: disable=protected-access os._exit(0)
Start the server.
157,156
import os import shutil from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import untrusted_runner_pb2 from clusterfuzz._internal.system import environment from clusterfuzz._internal.system import shell from . import file_utils from . import host 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 target paths. Here is the function: def get_fuzz_targets(path): """Get list of fuzz target paths.""" request = untrusted_runner_pb2.GetFuzzTargetsRequest(path=path) # pylint: disable=no-member response = host.stub().GetFuzzTargets(request) return response.fuzz_target_paths
Get list of fuzz target paths.
157,157
import os from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.system import environment from clusterfuzz._internal.system import process_handler SCRIPT_DIR = os.path.join('bot', 'init') def _extension(platform): """Get the init extension for a platform.""" if platform == 'windows': return '.ps1' return '.bash' The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def run()` to solve the following problem: Run custom platform specific init scripts. Here is the function: def run(): """Run custom platform specific init scripts.""" platform = environment.platform().lower() platform = environment.base_platform(platform) script_path = os.path.join(environment.get_config_directory(), SCRIPT_DIR, platform + _extension(platform)) if not os.path.exists(script_path): return os.chmod(script_path, 0o750) if script_path.endswith('.ps1'): cmd = 'powershell.exe ' + script_path else: cmd = script_path try: process_handler.run_process( cmd, timeout=1800, need_shell=True, testcase_run=False, ignore_children=True) except Exception: logs.log_error('Failed to execute platform initialization script.')
Run custom platform specific init scripts.
157,158
import os import shlex import subprocess from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer from clusterfuzz._internal.bot.tokenizer.grammars.HTMLLexer import HTMLLexer from . import errors test_command = None The provided code snippet includes necessary dependencies for implementing the `set_test_command` function. Write a Python function `def set_test_command(new_test_command)` to solve the following problem: Set the command used for testing. Here is the function: def set_test_command(new_test_command): """Set the command used for testing.""" global test_command test_command = shlex.split(new_test_command)
Set the command used for testing.
157,159
import os import shlex import subprocess from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer from clusterfuzz._internal.bot.tokenizer.grammars.HTMLLexer import HTMLLexer from . import errors attempts = 1 The provided code snippet includes necessary dependencies for implementing the `set_test_attempts` function. Write a Python function `def set_test_attempts(new_attempts)` to solve the following problem: Set the number of times to attempt the test. Here is the function: def set_test_attempts(new_attempts): """Set the number of times to attempt the test.""" global attempts attempts = new_attempts
Set the number of times to attempt the test.
157,160
import os import shlex import subprocess from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer from clusterfuzz._internal.bot.tokenizer.grammars.HTMLLexer import HTMLLexer from . import errors test_command = None STACKTRACE_TOOL_MARKERS = [ ' runtime error: ', 'AddressSanitizer', 'ASAN:', 'CFI: Most likely a control flow integrity violation;', 'ERROR: libFuzzer', 'KASAN:', 'LeakSanitizer', 'MemorySanitizer', 'ThreadSanitizer', 'UndefinedBehaviorSanitizer', 'UndefinedSanitizer', ] STACKTRACE_END_MARKERS = [ 'ABORTING', 'END MEMORY TOOL REPORT', 'End of process memory map.', 'END_KASAN_OUTPUT', 'SUMMARY:', 'Shadow byte and word', '[end of stack trace]', '\nExiting', 'minidump has been written', ] CHECK_FAILURE_MARKERS = [ 'Check failed:', 'Device rebooted', 'Fatal error in', 'FATAL EXCEPTION', 'JNI DETECTED ERROR IN APPLICATION:', 'Sanitizer CHECK failed:', ] def get_size_string(size): """Return string representation for size.""" if size < 1 << 10: return '%d B' % size if size < 1 << 20: return '%d KB' % (size >> 10) if size < 1 << 30: return '%d MB' % (size >> 20) return '%d GB' % (size >> 30) def has_marker(stacktrace, marker_list): """Return true if the stacktrace has atleast one marker in the marker list.""" for marker in marker_list: if marker in stacktrace: return True return False The provided code snippet includes necessary dependencies for implementing the `single_test_run` function. Write a Python function `def single_test_run(test_path)` to solve the following problem: Hacky test function that checks for certain common errors. Here is the function: def single_test_run(test_path): """Hacky test function that checks for certain common errors.""" if not test_command: raise errors.NoCommandError args = test_command + [test_path] try: console_output = subprocess.check_output(args, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as error: console_output = error.output # If we meet one of these conditions, assume we crashed. if ((has_marker(console_output, STACKTRACE_TOOL_MARKERS) and has_marker(console_output, STACKTRACE_END_MARKERS)) or has_marker(console_output, CHECK_FAILURE_MARKERS)): print('Crashed, current test size %s.' % (get_size_string( os.path.getsize(test_path)))) return False # No crash, test passed. print('Not crashed, current test size %s.' % (get_size_string( os.path.getsize(test_path)))) return True
Hacky test function that checks for certain common errors.
157,161
import os import shlex import subprocess from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer from clusterfuzz._internal.bot.tokenizer.grammars.HTMLLexer import HTMLLexer from . import errors class AntlrTokenizer(object): """Tokenizer. Takes an Antlr Lexer created using $ antlr4 -Dlanguage=Pythonn <AntlrGrammar.g4> and allows user to tokenize files using that grammar.""" def __init__(self, lexer): self._lexer = lexer def fill(self, stream): """Helper function. antlr4.CommonTokenStream.fill should work, but it does not fetch all of the tokens. This is a replacement that works.""" i = 0 while stream.fetch(1): i += 1 return i def tokenize(self, data): """Takes in a file and uses the antlr lexer to return a list of tokens""" # Antlr expects a string, but test cases are not necessarily valid utf-8. try: lexer_input = antlr4.InputStream(data.decode('utf-8')) except UnicodeDecodeError: raise errors.AntlrDecodeError stream = antlr4.CommonTokenStream(self._lexer(lexer_input)) end = self.fill(stream) tokens = stream.getTokens(0, end) return [token.text for token in tokens] def combine(self, tokens): """Token combiner passed to minimizer""" # This tokenizer must handle either bytes or str inputs. Antlr works with # strings, but the tokenizer validation step uses the original data, which # is always raw bytes. return b''.join(utils.encode_as_unicode(t) for t in tokens) class HTMLLexer(Lexer): atn = ATNDeserializer().deserialize(serializedATN()) decisionsToDFA = [DFA(ds, i) for i, ds in enumerate(atn.decisionToState)] TAG = 1 SCRIPT = 2 STYLE = 3 ATTVALUE = 4 HTML_COMMENT = 1 HTML_CONDITIONAL_COMMENT = 2 XML_DECLARATION = 3 CDATA = 4 DTD = 5 SCRIPTLET = 6 SEA_WS = 7 SCRIPT_OPEN = 8 STYLE_OPEN = 9 TAG_OPEN = 10 HTML_TEXT = 11 TAG_CLOSE = 12 TAG_SLASH_CLOSE = 13 TAG_SLASH = 14 TAG_EQUALS = 15 TAG_NAME = 16 TAG_WHITESPACE = 17 SCRIPT_BODY = 18 SCRIPT_SHORT_BODY = 19 STYLE_BODY = 20 STYLE_SHORT_BODY = 21 ATTVALUE_VALUE = 22 ATTRIBUTE = 23 channelNames = [u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN"] modeNames = [u"DEFAULT_MODE", u"TAG", u"SCRIPT", u"STYLE", u"ATTVALUE"] literalNames = [u"<INVALID>", u"'<'", u"'>'", u"'/>'", u"'/'", u"'='"] symbolicNames = [ u"<INVALID>", u"HTML_COMMENT", u"HTML_CONDITIONAL_COMMENT", u"XML_DECLARATION", u"CDATA", u"DTD", u"SCRIPTLET", u"SEA_WS", u"SCRIPT_OPEN", u"STYLE_OPEN", u"TAG_OPEN", u"HTML_TEXT", u"TAG_CLOSE", u"TAG_SLASH_CLOSE", u"TAG_SLASH", u"TAG_EQUALS", u"TAG_NAME", u"TAG_WHITESPACE", u"SCRIPT_BODY", u"SCRIPT_SHORT_BODY", u"STYLE_BODY", u"STYLE_SHORT_BODY", u"ATTVALUE_VALUE", u"ATTRIBUTE" ] ruleNames = [ u"HTML_COMMENT", u"HTML_CONDITIONAL_COMMENT", u"XML_DECLARATION", u"CDATA", u"DTD", u"SCRIPTLET", u"SEA_WS", u"SCRIPT_OPEN", u"STYLE_OPEN", u"TAG_OPEN", u"HTML_TEXT", u"TAG_CLOSE", u"TAG_SLASH_CLOSE", u"TAG_SLASH", u"TAG_EQUALS", u"TAG_NAME", u"TAG_WHITESPACE", u"HEXDIGIT", u"DIGIT", u"TAG_NameChar", u"TAG_NameStartChar", u"SCRIPT_BODY", u"SCRIPT_SHORT_BODY", u"STYLE_BODY", u"STYLE_SHORT_BODY", u"ATTVALUE_VALUE", u"ATTRIBUTE", u"ATTCHAR", u"ATTCHARS", u"HEXCHARS", u"DECCHARS", u"DOUBLE_QUOTE_STRING", u"SINGLE_QUOTE_STRING" ] grammarFileName = u"HTMLLexer.g4" def __init__(self, input=None, output=sys.stdout): super(HTMLLexer, self).__init__(input, output=output) self.checkVersion("4.7.1") self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache()) self._actions = None self._predicates = None The provided code snippet includes necessary dependencies for implementing the `tokenize` function. Write a Python function `def tokenize(data)` to solve the following problem: HTML tokenizer. Here is the function: def tokenize(data): """HTML tokenizer.""" return AntlrTokenizer(HTMLLexer).tokenize(data)
HTML tokenizer.
157,162
import os import shlex import subprocess from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer from clusterfuzz._internal.bot.tokenizer.grammars.HTMLLexer import HTMLLexer from . import errors The provided code snippet includes necessary dependencies for implementing the `token_combiner` function. Write a Python function `def token_combiner(tokens)` to solve the following problem: Dummy token combiner. Here is the function: def token_combiner(tokens): """Dummy token combiner.""" return ''.join(tokens)
Dummy token combiner.
157,163
import copy import functools import os import tempfile import threading import time from clusterfuzz._internal.metrics import logs from . import errors The provided code snippet includes necessary dependencies for implementing the `_default_tokenizer` function. Write a Python function `def _default_tokenizer(s)` to solve the following problem: Default string tokenizer which splits on newlines. Here is the function: def _default_tokenizer(s): """Default string tokenizer which splits on newlines.""" return s.split(b'\n')
Default string tokenizer which splits on newlines.
157,164
import copy import functools import os import tempfile import threading import time from clusterfuzz._internal.metrics import logs from . import errors The provided code snippet includes necessary dependencies for implementing the `_default_combiner` function. Write a Python function `def _default_combiner(tokens)` to solve the following problem: Default token combiner which assumes each token is a line. Here is the function: def _default_combiner(tokens): """Default token combiner which assumes each token is a line.""" return b'\n'.join(tokens)
Default token combiner which assumes each token is a line.
157,165
from clusterfuzz._internal.bot.tokenizer.antlr_tokenizer import AntlrTokenizer from clusterfuzz._internal.bot.tokenizer.grammars.JavaScriptLexer import \ JavaScriptLexer from . import delta_minimizer from . import errors from . import minimizer from . import utils The provided code snippet includes necessary dependencies for implementing the `step_back_while` function. Write a Python function `def step_back_while(cur_index, condition)` to solve the following problem: Helper function. Decreases index from cur while condition is satisfied. Here is the function: def step_back_while(cur_index, condition): """Helper function. Decreases index from cur while condition is satisfied.""" while cur_index >= 0 and condition(cur_index): cur_index -= 1 return cur_index
Helper function. Decreases index from cur while condition is satisfied.
157,166
from typing import Tuple from typing import Type from typing import TypeVar import uuid from google.cloud import ndb from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.ndb import model import google.protobuf.message from clusterfuzz._internal.base import task_utils 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 `serialize_uworker_input` function. Write a Python function `def serialize_uworker_input(uworker_input: uworker_msg_pb2.Input) -> bytes` to solve the following problem: Serializes and returns |uworker_input| as JSON. Can handle ndb entities. Here is the function: def serialize_uworker_input(uworker_input: uworker_msg_pb2.Input) -> bytes: """Serializes and returns |uworker_input| as JSON. Can handle ndb entities.""" return uworker_input.SerializeToString()
Serializes and returns |uworker_input| as JSON. Can handle ndb entities.
157,167
from typing import Tuple from typing import Type from typing import TypeVar import uuid from google.cloud import ndb from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.ndb import model import google.protobuf.message from clusterfuzz._internal.base import task_utils 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 get_uworker_output_urls(input_gcs_path: str) -> str: """Returns a signed download URL for the uworker to upload the output and a GCS url for the tworker to download the output. Make sure we can infer the actual input since the output is not trusted.""" gcs_path = uworker_input_path_to_output_path(input_gcs_path) # Note that the signed upload URL can't be directly downloaded from. return storage.get_signed_upload_url(gcs_path), gcs_path def get_uworker_input_urls(): """Returns a signed download URL for the uworker to download the input and a GCS url for the tworker to upload it (this happens first).""" gcs_path = get_uworker_input_gcs_path() return storage.get_signed_download_url(gcs_path), gcs_path def upload_uworker_input(uworker_input: bytes, gcs_path: str): """Uploads input for the untrusted portion of a task.""" storage.write_data(uworker_input, gcs_path) The provided code snippet includes necessary dependencies for implementing the `serialize_and_upload_uworker_input` function. Write a Python function `def serialize_and_upload_uworker_input( uworker_input: uworker_msg_pb2.Input) -> Tuple[str, str]` to solve the following problem: Serializes input for the untrusted portion of a task. Here is the function: def serialize_and_upload_uworker_input( uworker_input: uworker_msg_pb2.Input) -> Tuple[str, str]: """Serializes input for the untrusted portion of a task.""" signed_input_download_url, input_gcs_url = get_uworker_input_urls() # Get URLs for the uworker'ps output. We need a signed upload URL so it can # write its output. Also get a download URL in case the caller wants to read # the output. signed_output_upload_url, output_gcs_url = get_uworker_output_urls( input_gcs_url) assert not uworker_input.HasField('uworker_output_upload_url') uworker_input.uworker_output_upload_url = signed_output_upload_url serialized_uworker_input = uworker_input.SerializeToString() upload_uworker_input(serialized_uworker_input, input_gcs_url) return signed_input_download_url, output_gcs_url
Serializes input for the untrusted portion of a task.
157,168
from typing import Tuple from typing import Type from typing import TypeVar import uuid from google.cloud import ndb from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.ndb import model import google.protobuf.message from clusterfuzz._internal.base import task_utils 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 deserialize_uworker_input( serialized_uworker_input: bytes) -> uworker_msg_pb2.Input: """Deserializes input for the untrusted part of a task.""" uworker_input_proto = uworker_msg_pb2.Input() try: uworker_input_proto.ParseFromString(serialized_uworker_input) except google.protobuf.message.DecodeError: logs.log_error('Cannot decode uworker msg.') raise task_utils.UworkerMsgParseError('Cannot decode uworker msg.') return uworker_input_proto The provided code snippet includes necessary dependencies for implementing the `download_and_deserialize_uworker_input` function. Write a Python function `def download_and_deserialize_uworker_input( uworker_input_download_url: str) -> uworker_msg_pb2.Input` to solve the following problem: Downloads and deserializes the input to the uworker from the signed download URL. Here is the function: def download_and_deserialize_uworker_input( uworker_input_download_url: str) -> uworker_msg_pb2.Input: """Downloads and deserializes the input to the uworker from the signed download URL.""" data = storage.download_signed_url(uworker_input_download_url) return deserialize_uworker_input(data)
Downloads and deserializes the input to the uworker from the signed download URL.
157,169
from typing import Tuple from typing import Type from typing import TypeVar import uuid from google.cloud import ndb from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.ndb import model import google.protobuf.message from clusterfuzz._internal.base import task_utils 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 `serialize_uworker_output` function. Write a Python function `def serialize_uworker_output( uworker_output_obj: uworker_msg_pb2.Output) -> bytes` to solve the following problem: Serializes uworker's output for deserializing by deserialize_uworker_output and consumption by postprocess_task. Here is the function: def serialize_uworker_output( uworker_output_obj: uworker_msg_pb2.Output) -> bytes: """Serializes uworker's output for deserializing by deserialize_uworker_output and consumption by postprocess_task.""" return uworker_output_obj.SerializeToString()
Serializes uworker's output for deserializing by deserialize_uworker_output and consumption by postprocess_task.
157,170
from typing import Tuple from typing import Type from typing import TypeVar import uuid from google.cloud import ndb from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.ndb import model import google.protobuf.message from clusterfuzz._internal.base import task_utils 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 `serialize_and_upload_uworker_output` function. Write a Python function `def serialize_and_upload_uworker_output(uworker_output: uworker_msg_pb2.Output, upload_url: str)` to solve the following problem: Serializes |uworker_output| and uploads it to |upload_url. Here is the function: def serialize_and_upload_uworker_output(uworker_output: uworker_msg_pb2.Output, upload_url: str): """Serializes |uworker_output| and uploads it to |upload_url.""" serialized_uworker_output = uworker_output.SerializeToString() storage.upload_signed_url(serialized_uworker_output, upload_url)
Serializes |uworker_output| and uploads it to |upload_url.
157,171
from typing import Tuple from typing import Type from typing import TypeVar import uuid from google.cloud import ndb from google.cloud.datastore_v1.proto import entity_pb2 from google.cloud.ndb import model import google.protobuf.message from clusterfuzz._internal.base import task_utils 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 deserialize_uworker_output(serialized: bytes) -> uworker_msg_pb2.Output: output = uworker_msg_pb2.Output() try: output.ParseFromString(serialized) except google.protobuf.message.DecodeError: logs.log_error('Cannot decode uworker msg.') raise task_utils.UworkerMsgParseError('Cannot decode uworker msg.') return output def download_input_based_on_output_url( output_url: str) -> uworker_msg_pb2.Input: input_url = uworker_output_path_to_input_path(output_url) serialized_uworker_input = storage.read_data(input_url) if serialized_uworker_input is None: logs.log_error(f'No corresponding input for output: {output_url}.') return deserialize_uworker_input(serialized_uworker_input) The provided code snippet includes necessary dependencies for implementing the `download_and_deserialize_uworker_output` function. Write a Python function `def download_and_deserialize_uworker_output( output_url: str) -> uworker_msg_pb2.Output` to solve the following problem: Downloads and deserializes uworker output. Here is the function: def download_and_deserialize_uworker_output( output_url: str) -> uworker_msg_pb2.Output: """Downloads and deserializes uworker output.""" serialized_uworker_output = storage.read_data(output_url) uworker_output = deserialize_uworker_output(serialized_uworker_output) # Now download the input, which is stored securely so that the uworker cannot # tamper with it. uworker_input = download_input_based_on_output_url(output_url) uworker_output.uworker_input.CopyFrom(uworker_input) return uworker_output
Downloads and deserializes uworker output.
157,172
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query 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 `utask_preprocess` function. Write a Python function `def utask_preprocess(testcase_id: str, job_type: str, uworker_env: Dict) -> Optional[uworker_msg_pb2.Input]` to solve the following problem: Prepares inputs for `utask_main()` to run on an untrusted worker. Runs on a trusted worker. Here is the function: def utask_preprocess(testcase_id: str, job_type: str, uworker_env: Dict) -> Optional[uworker_msg_pb2.Input]: """Prepares inputs for `utask_main()` to run on an untrusted worker. Runs on a trusted worker. """ testcase = data_handler.get_testcase_by_id(testcase_id) if testcase.regression: logs.log_error( f'Regression range is already set as {testcase.regression}, skip.') return None # This task is not applicable for custom binaries. if build_manager.is_custom_binary(): testcase.regression = 'NA' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, 'Not applicable for custom binaries') return None data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED) setup_input = setup.preprocess_setup_testcase(testcase, uworker_env) task_input = uworker_msg_pb2.RegressionTaskInput( bad_revisions=build_manager.get_job_bad_revisions()) uworker_input = uworker_msg_pb2.Input( testcase_id=testcase_id, testcase=uworker_io.entity_to_protobuf(testcase), job_type=job_type, uworker_env=uworker_env, setup_input=setup_input, regression_task_input=task_input, ) testcase_manager.preprocess_testcase_manager(testcase, uworker_input) return uworker_input
Prepares inputs for `utask_main()` to run on an untrusted worker. Runs on a trusted worker.
157,173
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def find_regression_range(uworker_input: uworker_msg_pb2.Input, ) -> uworker_msg_pb2.Output: """Attempt to find when the testcase regressed.""" testcase = uworker_io.entity_from_protobuf(uworker_input.testcase, data_types.Testcase) job_type = uworker_input.job_type deadline = tasks.get_task_completion_deadline() fuzz_target = testcase_manager.get_fuzz_target_from_input(uworker_input) # Setup testcase and its dependencies. _, testcase_file_path, error = setup.setup_testcase(testcase, job_type, uworker_input.setup_input) if error: return error build_bucket_path = build_manager.get_primary_bucket_path() revision_list = build_manager.get_revisions_list( build_bucket_path, uworker_input.regression_task_input.bad_revisions, testcase=testcase) if not revision_list: return uworker_msg_pb2.Output( error_type=uworker_msg_pb2.ErrorType.REGRESSION_REVISION_LIST_ERROR) # Pick up where left off in a previous run if necessary. min_revision = testcase.get_metadata('last_regression_min') max_revision = testcase.get_metadata('last_regression_max') first_run = not min_revision and not max_revision if not min_revision: min_revision = revisions.get_first_revision_in_list(revision_list) if not max_revision: max_revision = testcase.crash_revision min_index = revisions.find_min_revision_index(revision_list, min_revision) if min_index is None: error_message = f'Could not find good min revision <= {min_revision}.' return uworker_msg_pb2.Output( error_type=uworker_msg_pb2.ErrorType.REGRESSION_BUILD_NOT_FOUND, error_message=error_message) max_index = revisions.find_max_revision_index(revision_list, max_revision) if max_index is None: error_message = f'Could not find good max revision >= {max_revision}.' return uworker_msg_pb2.Output( error_type=uworker_msg_pb2.ErrorType.REGRESSION_BUILD_NOT_FOUND, error_message=error_message) # Make sure that the revision where we noticed the crash, still crashes at # that revision. Otherwise, our binary search algorithm won't work correctly. max_revision = revision_list[max_index] regression_task_output = uworker_msg_pb2.RegressionTaskOutput() crashes_in_max_revision, error = _testcase_reproduces_in_revision( testcase, testcase_file_path, job_type, max_revision, regression_task_output, fuzz_target, should_log=False) if error: return error if not crashes_in_max_revision: error_message = f'Known crash revision {max_revision} did not crash' return uworker_msg_pb2.Output( regression_task_output=regression_task_output, error_message=error_message, error_type=uworker_msg_pb2.ErrorType.REGRESSION_NO_CRASH) # If we've made it this far, the test case appears to be reproducible. regression_task_output.is_testcase_reproducible = True # On the first run, check to see if we regressed near either the min or max # revision. if first_run: result = found_regression_near_extreme_revisions( testcase, testcase_file_path, job_type, revision_list, min_index, max_index, fuzz_target, regression_task_output) if result: return result 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 (or the same, if we only have # one build), this is as much as we can narrow the range. if max_index - min_index <= 1: # Verify that the regression range seems correct, and save it if so. error = validate_regression_range(testcase, testcase_file_path, job_type, revision_list, min_index, regression_task_output, fuzz_target) if error: return error regression_task_output.regression_range_start = min_revision regression_task_output.regression_range_end = max_revision return uworker_msg_pb2.Output( regression_task_output=regression_task_output) middle_index = (min_index + max_index) // 2 middle_revision = revision_list[middle_index] is_crash, error = _testcase_reproduces_in_revision( testcase, testcase_file_path, job_type, middle_revision, regression_task_output, fuzz_target, min_revision=min_revision, max_revision=max_revision) if error: if error.error_type == uworker_msg_pb2.REGRESSION_BAD_BUILD_ERROR: # Skip this revision. del revision_list[middle_index] max_index -= 1 continue return error if is_crash: max_index = middle_index else: min_index = middle_index # Save current regression range in case the task dies prematurely. regression_task_output.last_regression_min = revision_list[min_index] regression_task_output.last_regression_max = revision_list[max_index] # If we've broken out of the above loop, we timed out. We'll finish by # running another regression task and picking up from this point. # TODO: Error handling should be moved to postprocess. error_message = 'Timed out, current range r%d:r%d' % ( revision_list[min_index], revision_list[max_index]) regression_task_output.last_regression_min = revision_list[min_index] regression_task_output.last_regression_max = revision_list[max_index] return uworker_msg_pb2.Output( regression_task_output=regression_task_output, error_type=uworker_msg_pb2.REGRESSION_TIMEOUT_ERROR, error_message=error_message) 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, ) -> Optional[uworker_msg_pb2.Output]` to solve the following problem: Runs regression task and handles potential errors. Runs on an untrusted worker. Here is the function: def utask_main(uworker_input: uworker_msg_pb2.Input, ) -> Optional[uworker_msg_pb2.Output]: """Runs regression task and handles potential errors. Runs on an untrusted worker. """ testcase = uworker_io.entity_from_protobuf(uworker_input.testcase, data_types.Testcase) uworker_io.check_handling_testcase_safe(testcase) return find_regression_range(uworker_input)
Runs regression task and handles potential errors. Runs on an untrusted worker.
157,174
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_revision_list_error(output: uworker_msg_pb2.Output): testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) data_handler.close_testcase_with_error(testcase, 'Failed to fetch revision list')
null
157,175
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_build_not_found_error(output: uworker_msg_pb2.Output): # If an expected build no longer exists, we can't continue. testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) testcase.regression = 'NA' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, output.error_message)
null
157,176
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_regression_build_setup_error(output: uworker_msg_pb2.Output): # If we failed to setup a build, it is likely a bot error. We can retry # the task in this case. uworker_input = output.uworker_input testcase = data_handler.get_testcase_by_id(uworker_input.testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, output.error_message) build_fail_wait = environment.get_value('FAIL_WAIT') tasks.add_task( 'regression', uworker_input.testcase_id, uworker_input.job_type, wait_time=build_fail_wait)
null
157,177
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_regression_bad_build_error(output: uworker_msg_pb2.Output): # 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 = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) testcase.regression = 'NA' error_message = 'Unable to recover from bad build' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message)
null
157,178
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_regression_no_crash(output: uworker_msg_pb2.Output): testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, output.error_message) task_creation.mark_unreproducible_if_flaky(testcase, 'regression', True)
null
157,179
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_regression_timeout(output: uworker_msg_pb2.Output): testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, output.error_message) tasks.add_task('regression', output.uworker_input.testcase_id, output.uworker_input.job_type)
null
157,180
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def handle_low_confidence_in_regression_range(output: uworker_msg_pb2.Output): testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) testcase.regression = 'NA' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, output.error_message)
null
157,181
import random import time from typing import Dict from typing import List from typing import Optional from clusterfuzz._internal.base import tasks 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.build_management import revisions from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.google_cloud_utils import big_query from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def _save_current_regression_range_indices( task_output: uworker_msg_pb2.RegressionTaskOutput, testcase_id: str): """Save current regression range indices in case we die in middle of task.""" if not task_output.HasField( 'last_regression_min') or not task_output.HasField('last_regression_max'): return testcase = data_handler.get_testcase_by_id(testcase_id) testcase.set_metadata( 'last_regression_min', task_output.last_regression_min, update_testcase=False) testcase.set_metadata( 'last_regression_max', task_output.last_regression_max, update_testcase=False) testcase.put() def save_regression_range(output: uworker_msg_pb2.Output): """Saves the regression range and creates blame and impact task if needed.""" testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) regression_range_start = output.regression_task_output.regression_range_start regression_range_end = output.regression_task_output.regression_range_end testcase.regression = '%d:%d' % (regression_range_start, regression_range_end) data_handler.update_testcase_comment( testcase, data_types.TaskState.FINISHED, 'regressed in range %s' % testcase.regression) write_to_big_query(testcase, regression_range_start, regression_range_end) # Force impacts update after regression range is updated. In several cases, # we might not have a production build to test with, so regression range is # used to decide impacts. task_creation.create_impact_task_if_needed(testcase) # Get blame information using the regression range result. task_creation.create_blame_task_if_needed(testcase) _ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({ uworker_msg_pb2.ErrorType.REGRESSION_BAD_BUILD_ERROR: handle_regression_bad_build_error, uworker_msg_pb2.ErrorType.REGRESSION_BUILD_NOT_FOUND: handle_build_not_found_error, uworker_msg_pb2.ErrorType.REGRESSION_BUILD_SETUP_ERROR: handle_regression_build_setup_error, uworker_msg_pb2.ErrorType.REGRESSION_LOW_CONFIDENCE_IN_REGRESSION_RANGE: handle_low_confidence_in_regression_range, uworker_msg_pb2.ErrorType.REGRESSION_NO_CRASH: handle_regression_no_crash, uworker_msg_pb2.ErrorType.REGRESSION_REVISION_LIST_ERROR: handle_revision_list_error, uworker_msg_pb2.ErrorType.REGRESSION_TIMEOUT_ERROR: handle_regression_timeout, }).compose_with(setup.ERROR_HANDLER) 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) 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) -> None` to solve the following problem: Handles the output of `utask_main()` run on an untrusted worker. Runs on a trusted worker. Here is the function: def utask_postprocess(output: uworker_msg_pb2.Output) -> None: """Handles the output of `utask_main()` run on an untrusted worker. Runs on a trusted worker. """ if output.HasField('regression_task_output'): task_output = output.regression_task_output _update_build_metadata(output.uworker_input.job_type, task_output.build_data_list) _save_current_regression_range_indices(task_output, output.uworker_input.testcase_id) if task_output.is_testcase_reproducible: # Clear metadata from previous runs had it been marked as potentially # flaky. testcase = data_handler.get_testcase_by_id( output.uworker_input.testcase_id) task_creation.mark_unreproducible_if_flaky(testcase, 'regression', False) if output.error_type != uworker_msg_pb2.ErrorType.NO_ERROR: _ERROR_HANDLER.handle(output) return save_regression_range(output)
Handles the output of `utask_main()` run on an untrusted worker. Runs on a trusted worker.
157,182
import datetime from typing import Optional 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.crash_analysis import crash_analyzer from clusterfuzz._internal.crash_analysis import severity_analyzer from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.fuzzing import leak_blacklist 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): def handle_analyze_no_revisions_list_error(output): testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, 'Failed to fetch revision list') handle_build_setup_error(output)
null
157,183
import datetime from typing import Optional 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.crash_analysis import crash_analyzer from clusterfuzz._internal.crash_analysis import severity_analyzer from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.fuzzing import leak_blacklist 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): """Handles errors for scenarios where build setup fails.""" testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, 'Build setup failed') if is_first_analyze_attempt(testcase): task_name = 'analyze' testcase_fail_wait = environment.get_value('FAIL_WAIT') tasks.add_task( task_name, output.uworker_input.testcase_id, output.uworker_input.job_type, wait_time=testcase_fail_wait) return testcase_upload_metadata = query_testcase_upload_metadata( output.uworker_input.testcase_id) data_handler.mark_invalid_uploaded_testcase( testcase, testcase_upload_metadata, 'Build setup failed') def handle_analyze_no_revision_index(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 {testcase.job_type} r{testcase.crash_revision} ' 'does not exist') handle_build_setup_error(output)
null
157,184
import datetime from typing import Optional 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.crash_analysis import crash_analyzer from clusterfuzz._internal.crash_analysis import severity_analyzer from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.fuzzing import leak_blacklist from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def is_first_analyze_attempt(testcase): return data_handler.is_first_attempt_for_task('analyze', testcase) def query_testcase_upload_metadata( testcase_id: str) -> Optional[data_types.TestcaseUploadMetadata]: return data_types.TestcaseUploadMetadata.query( data_types.TestcaseUploadMetadata.testcase_id == int(testcase_id)).get() The provided code snippet includes necessary dependencies for implementing the `handle_noncrash` function. Write a Python function `def handle_noncrash(output)` to solve the following problem: Handles a non-crashing testcase. Either deletes the testcase or schedules another, final analysis. Here is the function: def handle_noncrash(output): """Handles a non-crashing testcase. Either deletes the testcase or schedules another, final analysis.""" # Could not reproduce the crash. testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) log_message = ( f'Testcase didn\'t crash in {output.test_timeout} seconds (with retries)') data_handler.update_testcase_comment(testcase, data_types.TaskState.FINISHED, log_message) # For an unreproducible testcase, 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 is_first_analyze_attempt(testcase): testcase.status = 'Unreproducible, retrying' testcase.put() tasks.add_task('analyze', output.uworker_input.testcase_id, output.uworker_input.job_type) return testcase_upload_metadata = query_testcase_upload_metadata( output.uworker_input.testcase_id) data_handler.mark_invalid_uploaded_testcase( testcase, testcase_upload_metadata, 'Unreproducible')
Handles a non-crashing testcase. Either deletes the testcase or schedules another, final analysis.
157,185
import datetime from typing import Optional 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.crash_analysis import crash_analyzer from clusterfuzz._internal.crash_analysis import severity_analyzer from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.fuzzing import leak_blacklist from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def initialize_testcase_for_main(testcase, job_type): """Initializes a testcase for the crash testing phase.""" # Update initial testcase information. testcase.job_type = job_type testcase.queue = tasks.default_queue() testcase.crash_state = '' testcase.put() def get_analyze_task_input(): return uworker_msg_pb2.AnalyzeTaskInput( bad_revisions=build_manager.get_job_bad_revisions()) def query_testcase_upload_metadata( testcase_id: str) -> Optional[data_types.TestcaseUploadMetadata]: return data_types.TestcaseUploadMetadata.query( data_types.TestcaseUploadMetadata.testcase_id == int(testcase_id)).get() 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 analyze task. Here is the function: def utask_preprocess(testcase_id, job_type, uworker_env): """Runs preprocessing for analyze task.""" # Get the testcase from the database and mark it as started. testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED) testcase_upload_metadata = query_testcase_upload_metadata(testcase_id) if not testcase_upload_metadata: logs.log_error( 'Testcase %s has no associated upload metadata.' % testcase_id) testcase.key.delete() return None # Store the bot name and timestamp in upload metadata. testcase_upload_metadata.bot_name = environment.get_value('BOT_NAME') testcase_upload_metadata.timestamp = datetime.datetime.utcnow() testcase_upload_metadata.put() initialize_testcase_for_main(testcase, job_type) setup_input = setup.preprocess_setup_testcase(testcase, uworker_env) analyze_task_input = get_analyze_task_input() uworker_input = uworker_msg_pb2.Input( testcase_upload_metadata=uworker_io.entity_to_protobuf( testcase_upload_metadata), testcase=uworker_io.entity_to_protobuf(testcase), testcase_id=testcase_id, uworker_env=uworker_env, setup_input=setup_input, job_type=job_type, analyze_task_input=analyze_task_input, ) testcase_manager.preprocess_testcase_manager(testcase, uworker_input) return uworker_input
Runs preprocessing for analyze task.
157,186
import datetime from typing import Optional 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.crash_analysis import crash_analyzer from clusterfuzz._internal.crash_analysis import severity_analyzer from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.fuzzing import leak_blacklist from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def prepare_env_for_main(testcase_upload_metadata): """Prepares the environment for execute_task.""" # Reset redzones. environment.reset_current_memory_tool_options(redzone_size=128) # Unset window location size and position properties so as to use default. environment.set_value('WINDOW_ARG', '') # Adjust the test timeout, if user has provided one. if testcase_upload_metadata.timeout: environment.set_value('TEST_TIMEOUT', testcase_upload_metadata.timeout) # Adjust the number of retries, if user has provided one. if testcase_upload_metadata.retries is not None: environment.set_value('CRASH_RETRIES', testcase_upload_metadata.retries) def setup_testcase_and_build( testcase, job_type, setup_input, bad_revisions) -> (Optional[str], Optional[uworker_msg_pb2.Output]): """Sets up the |testcase| and builds. Returns the path to the testcase on success, None on error.""" # Set up testcase and get absolute testcase path. _, testcase_file_path, error = setup.setup_testcase(testcase, job_type, setup_input) if error: return None, error # Set up build. error = setup_build(testcase, bad_revisions) if error: return None, error # Check if we have an application path. If not, our build failed # to setup correctly. if not build_manager.check_app_path(): # Let postprocess handle ANALYZE_BUILD_SETUP and restart tasks if needed. return None, uworker_msg_pb2.Output( error_type=uworker_msg_pb2.ErrorType.ANALYZE_BUILD_SETUP) update_testcase_after_build_setup(testcase) testcase.absolute_path = testcase_file_path return testcase_file_path, None def test_for_crash_with_retries(fuzz_target, testcase, testcase_file_path, test_timeout): """Tests for a crash with retries. Tries with HTTP (with retries) if initial attempts fail. Returns the most recent crash result and the possibly updated HTTP flag.""" # Get the crash output. http_flag = testcase.http_flag result = testcase_manager.test_for_crash_with_retries( fuzz_target, testcase, testcase_file_path, test_timeout, http_flag=http_flag, compare_crash=False) # If we don't get a crash, try enabling http to see if we can get a crash. # Skip engine fuzzer jobs (e.g. libFuzzer, AFL) for which http testcase paths # are not applicable. if (not result.is_crash() and not http_flag and not environment.is_engine_fuzzer_job()): result_with_http = testcase_manager.test_for_crash_with_retries( fuzz_target, testcase, testcase_file_path, test_timeout, http_flag=True, compare_crash=False) if result_with_http.is_crash(): logs.log('Testcase needs http flag for crash.') http_flag = True result = result_with_http return result, http_flag return result, http_flag def update_testcase_after_crash(testcase, state, job_type, http_flag, analyze_task_output): """Updates |testcase| based on |state|.""" testcase.crash_type = state.crash_type testcase.crash_address = state.crash_address testcase.crash_state = state.crash_state testcase.http_flag = http_flag testcase.security_flag = crash_analyzer.is_security_issue( state.crash_stacktrace, state.crash_type, state.crash_address) # These are passed back to postprocess to update the testcase. analyze_task_output.crash_info_set = True analyze_task_output.http_flag = http_flag analyze_task_output.crash_type = state.crash_type analyze_task_output.crash_address = state.crash_address analyze_task_output.crash_state = state.crash_state analyze_task_output.security_flag = testcase.security_flag # If it is, guess the severity. if testcase.security_flag: testcase.security_severity = severity_analyzer.get_security_severity( state.crash_type, state.crash_stacktrace, job_type, bool(testcase.gestures)) if testcase.security_severity is not None: analyze_task_output.security_severity = testcase.security_severity def _build_task_output( testcase: data_types.Testcase) -> uworker_msg_pb2.AnalyzeTaskOutput: """Copies the testcase updated fields to analyze_task_output to be updated in postprocess.""" analyze_task_output = uworker_msg_pb2.AnalyzeTaskOutput() analyze_task_output.crash_revision = int(testcase.crash_revision) analyze_task_output.absolute_path = testcase.absolute_path analyze_task_output.minimized_arguments = testcase.minimized_arguments if testcase.get_metadata('build_key'): analyze_task_output.build_key = testcase.get_metadata('build_key') if testcase.get_metadata('build_url'): analyze_task_output.build_url = testcase.get_metadata('build_url') if testcase.get_metadata('gn_args'): analyze_task_output.gn_args = testcase.get_metadata('gn_args') if testcase.platform: analyze_task_output.platform = testcase.platform if testcase.platform_id: analyze_task_output.platform_id = testcase.platform_id return analyze_task_output def test_for_reproducibility(fuzz_target, testcase, testcase_file_path, state, test_timeout): one_time_crasher_flag = not testcase_manager.test_for_reproducibility( fuzz_target, testcase_file_path, state.crash_type, state.crash_state, testcase.security_flag, test_timeout, testcase.http_flag, testcase.gestures) testcase.one_time_crasher_flag = one_time_crasher_flag 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 analyze_task. Here is the function: def utask_main(uworker_input): """Executes the untrusted part of analyze_task.""" testcase_upload_metadata = uworker_io.entity_from_protobuf( uworker_input.testcase_upload_metadata, data_types.TestcaseUploadMetadata) testcase = uworker_io.entity_from_protobuf(uworker_input.testcase, data_types.Testcase) uworker_io.check_handling_testcase_safe(testcase) prepare_env_for_main(testcase_upload_metadata) is_lsan_enabled = environment.get_value('LSAN') if is_lsan_enabled: # Creates empty local blacklist so all leaks will be visible to uploader. leak_blacklist.create_empty_local_blacklist() testcase_file_path, output = setup_testcase_and_build( testcase, uworker_input.job_type, uworker_input.setup_input, uworker_input.analyze_task_input.bad_revisions) testcase.crash_revision = environment.get_value('APP_REVISION') if not testcase_file_path: return output analyze_task_output = _build_task_output(testcase) # Initialize some variables. test_timeout = environment.get_value('TEST_TIMEOUT') fuzz_target = testcase_manager.get_fuzz_target_from_input(uworker_input) result, http_flag = test_for_crash_with_retries( fuzz_target, testcase, testcase_file_path, test_timeout) # Set application command line with the correct http flag. application_command_line = ( testcase_manager.get_command_line_for_application( testcase_file_path, needs_http=http_flag)) # Get the crash data. crashed = result.is_crash() crash_time = result.get_crash_time() state = result.get_symbolized_data() unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False) # In the general case, we will not attempt to symbolize if we do not detect # a crash. For user uploads, we should symbolize anyway to provide more # information about what might be happening. crash_stacktrace_output = utils.get_crash_stacktrace_output( application_command_line, state.crash_stacktrace, unsymbolized_crash_stacktrace) testcase.crash_stacktrace = data_handler.filter_stacktrace( crash_stacktrace_output) analyze_task_output.crash_stacktrace = testcase.crash_stacktrace if not crashed: return uworker_msg_pb2.Output( analyze_task_output=analyze_task_output, error_type=uworker_msg_pb2.ErrorType.ANALYZE_NO_CRASH, test_timeout=test_timeout) # Update testcase crash parameters. update_testcase_after_crash(testcase, state, uworker_input.job_type, http_flag, analyze_task_output) # See if we have to ignore this crash. if crash_analyzer.ignore_stacktrace(state.crash_stacktrace): # TODO(metzman): Handle this by closing the testcase on the trusted worker. # Also, deal with the other cases where we are updating testcase comment # in untrusted. data_handler.close_invalid_uploaded_testcase( testcase, testcase_upload_metadata, 'Irrelevant') return uworker_msg_pb2.Output( analyze_task_output=analyze_task_output, error_type=uworker_msg_pb2.ErrorType.UNHANDLED) test_for_reproducibility(fuzz_target, testcase, testcase_file_path, state, test_timeout) analyze_task_output.one_time_crasher_flag = testcase.one_time_crasher_flag fuzz_target_metadata = engine_common.get_fuzz_target_issue_metadata( fuzz_target) return uworker_msg_pb2.Output( analyze_task_output=analyze_task_output, test_timeout=test_timeout, crash_time=crash_time, issue_metadata=fuzz_target_metadata)
Executes the untrusted part of analyze_task.
157,187
import datetime from typing import Optional 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.crash_analysis import crash_analyzer from clusterfuzz._internal.crash_analysis import severity_analyzer from clusterfuzz._internal.datastore import data_handler from clusterfuzz._internal.datastore import data_types from clusterfuzz._internal.fuzzing import leak_blacklist from clusterfuzz._internal.metrics import logs from clusterfuzz._internal.protos import uworker_msg_pb2 from clusterfuzz._internal.system import environment def _add_default_issue_metadata(testcase, fuzz_target_metadata): """Adds the default issue metadata (e.g. components, labels) to testcase.""" testcase_metadata = testcase.get_metadata() for key, default_value in fuzz_target_metadata.items(): # Only string metadata are supported. if not isinstance(default_value, str): continue # Add the default issue metadata first. This gives preference to uploader # specified issue metadata. new_value_list = utils.parse_delimited( default_value, delimiter=',', strip=True, remove_empty=True) # Append uploader specified testcase metadata value to end (for preference). uploader_value = testcase_metadata.get(key, '') uploader_value_list = utils.parse_delimited( uploader_value, delimiter=',', strip=True, remove_empty=True) for value in uploader_value_list: if value not in new_value_list: new_value_list.append(value) new_value = ','.join(new_value_list) if new_value == uploader_value: continue logs.log('Updating issue metadata for {} from {} to {}.'.format( key, uploader_value, new_value)) testcase.set_metadata(key, new_value) _ERROR_HANDLER = uworker_handle_errors.CompositeErrorHandler({ uworker_msg_pb2.ErrorType.ANALYZE_BUILD_SETUP: handle_build_setup_error, uworker_msg_pb2.ErrorType.ANALYZE_NO_CRASH: handle_noncrash, uworker_msg_pb2.ErrorType.ANALYZE_NO_REVISION_INDEX: handle_analyze_no_revision_index, uworker_msg_pb2.ErrorType.ANALYZE_NO_REVISIONS_LIST: handle_analyze_no_revisions_list_error, }).compose_with( setup.ERROR_HANDLER, uworker_handle_errors.UNHANDLED_ERROR_HANDLER, ) def _update_testcase(output): """Updates the testcase using the info passed from utask_main.""" if not output.HasField('analyze_task_output'): return testcase = data_handler.get_testcase_by_id(output.uworker_input.testcase_id) analyze_task_output = output.analyze_task_output testcase.crash_revision = analyze_task_output.crash_revision testcase.absolute_path = analyze_task_output.absolute_path testcase.minimized_arguments = analyze_task_output.minimized_arguments testcase.crash_stacktrace = analyze_task_output.crash_stacktrace if analyze_task_output.crash_info_set: testcase.http_flag = analyze_task_output.http_flag testcase.crash_type = analyze_task_output.crash_type testcase.crash_address = analyze_task_output.crash_address testcase.crash_state = analyze_task_output.crash_state testcase.security_flag = analyze_task_output.security_flag if testcase.security_flag: if analyze_task_output.HasField('security_severity'): testcase.security_severity = analyze_task_output.security_severity else: testcase.security_severity = None testcase.one_time_crasher_flag = analyze_task_output.one_time_crasher_flag # For the following fields, we are assuming an empty string/ None is invalid. if analyze_task_output.build_key: testcase.set_metadata( 'build_key', analyze_task_output.build_key, update_testcase=False) if analyze_task_output.build_url: testcase.set_metadata( 'build_url', analyze_task_output.build_url, update_testcase=False) if analyze_task_output.gn_args: testcase.set_metadata( 'gn_args', analyze_task_output.gn_args, update_testcase=False) if analyze_task_output.platform: testcase.platform = analyze_task_output.platform if analyze_task_output.platform_id: testcase.platform_id = analyze_task_output.platform_id testcase.put() def query_testcase_upload_metadata( testcase_id: str) -> Optional[data_types.TestcaseUploadMetadata]: return data_types.TestcaseUploadMetadata.query( data_types.TestcaseUploadMetadata.testcase_id == int(testcase_id)).get() 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: Cleans up after a uworker execute_task, writing anything needed to the db. Here is the function: def utask_postprocess(output): """Trusted: Cleans up after a uworker execute_task, writing anything needed to the db.""" _update_testcase(output) 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) testcase_upload_metadata = query_testcase_upload_metadata( output.uworker_input.testcase_id) log_message = (f'Testcase crashed in {output.test_timeout} seconds ' f'(r{testcase.crash_revision})') data_handler.update_testcase_comment(testcase, data_types.TaskState.FINISHED, log_message) # Check to see if this is a duplicate. data_handler.check_uploaded_testcase_duplicate(testcase, testcase_upload_metadata) # Set testcase and metadata status if not set already. if testcase.status == 'Duplicate': # For testcase uploaded by bots (with quiet flag), don't create additional # tasks. if testcase_upload_metadata.quiet_flag: data_handler.close_invalid_uploaded_testcase( testcase, testcase_upload_metadata, 'Duplicate') return else: # New testcase. testcase.status = 'Processed' testcase_upload_metadata.status = 'Confirmed' # Reset the timestamp as well, to respect # data_types.MIN_ELAPSED_TIME_SINCE_REPORT. Otherwise it may get filed by # triage task prematurely without the grouper having a chance to run on this # testcase. testcase.timestamp = utils.utcnow() # Add new leaks to global blacklist to avoid detecting duplicates. # Only add if testcase has a direct leak crash and if it's reproducible. is_lsan_enabled = output.uworker_input.uworker_env.get('LSAN') if is_lsan_enabled: leak_blacklist.add_crash_to_global_blacklist_if_needed(testcase) # Update the testcase values. testcase.put() # Update the upload metadata. testcase_upload_metadata.security_flag = testcase.security_flag testcase_upload_metadata.put() _add_default_issue_metadata(testcase, output.issue_metadata) logs.log('Creating post-analyze tasks.') # 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 crashes (stack). task_creation.create_tasks(testcase)
Trusted: Cleans up after a uworker execute_task, writing anything needed to the db.
157,188
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 `get_unsymbolized_crash_stacktrace` function. Write a Python function `def get_unsymbolized_crash_stacktrace(stack_file_path)` to solve the following problem: Read unsymbolized crash stacktrace. Here is the function: def get_unsymbolized_crash_stacktrace(stack_file_path): """Read unsymbolized crash stacktrace.""" with open(stack_file_path, 'rb') as f: return utils.decode_to_unicode(f.read())
Read unsymbolized crash stacktrace.
157,189
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 `find_main_crash` function. Write a Python function `def find_main_crash(crashes, full_fuzzer_name, test_timeout)` to solve the following problem: Find the first reproducible crash or the first valid crash. And return the crash and the one_time_crasher_flag. Here is the function: def find_main_crash(crashes, full_fuzzer_name, test_timeout): """Find the first reproducible crash or the first valid crash. And return the crash and the one_time_crasher_flag.""" for crash in crashes: # Archiving testcase to blobstore when we need to because it's expensive. crash.archive_testcase_in_blobstore() # We need to check again if the crash is valid. In other words, we check # if archiving to blobstore succeeded. if not crash.is_valid(): continue # We pass an empty expected crash state since our initial stack from fuzzing # can be incomplete. So, make a judgement on reproducibility based on passed # security flag and crash state generated from re-running testcase in # test_for_reproducibility. Minimize task will later update the new crash # type and crash state parameters. fuzz_target = data_handler.get_fuzz_target(full_fuzzer_name) if testcase_manager.test_for_reproducibility( fuzz_target, crash.file_path, crash.crash_type, None, crash.security_flag, test_timeout, crash.http_flag, crash.gestures, arguments=crash.arguments): return crash, False # All crashes are non-reproducible. Therefore, we get the first valid one. for crash in crashes: if crash.is_valid(): return crash, True return None, None
Find the first reproducible crash or the first valid crash. And return the crash and the one_time_crasher_flag.
157,190
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 `_track_build_run_result` function. Write a Python function `def _track_build_run_result(job_type, _, is_bad_build)` to solve the following problem: Track build run result. Here is the function: def _track_build_run_result(job_type, _, is_bad_build): """Track build run result.""" # FIXME: Add support for |crash_revision| as part of state. monitoring_metrics.JOB_BAD_BUILD_COUNT.increment({ 'job': job_type, 'bad_build': is_bad_build })
Track build run result.
157,191
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 `_last_sync_time` function. Write a Python function `def _last_sync_time(sync_file_path)` to solve the following problem: Read and parse the last sync file for the GCS corpus. Here is the function: def _last_sync_time(sync_file_path): """Read and parse the last sync file for the GCS corpus.""" if not os.path.exists(sync_file_path): return None file_contents = utils.read_data_from_file(sync_file_path, eval_data=False) if not file_contents: logs.log_warn('Empty last sync file.', path=sync_file_path) return None last_sync_time = None try: last_sync_time = datetime.datetime.utcfromtimestamp(float(file_contents)) except Exception as e: logs.log_error( 'Malformed last sync file: "%s".' % str(e), path=sync_file_path, contents=file_contents) return last_sync_time
Read and parse the last sync file for the GCS corpus.
157,192
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 `upload_testcase_run_stats` function. Write a Python function `def upload_testcase_run_stats(testcase_run)` to solve the following problem: Upload TestcaseRun stats. Here is the function: def upload_testcase_run_stats(testcase_run): """Upload TestcaseRun stats.""" fuzzer_stats.upload_stats([testcase_run])
Upload TestcaseRun stats.
157,193
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 `add_additional_testcase_run_data` function. Write a Python function `def add_additional_testcase_run_data(testcase_run, fully_qualified_fuzzer_name, job_type, revision)` to solve the following problem: Add additional testcase run data. Here is the function: def add_additional_testcase_run_data(testcase_run, fully_qualified_fuzzer_name, job_type, revision): """Add additional testcase run data.""" testcase_run['fuzzer'] = fully_qualified_fuzzer_name testcase_run['job'] = job_type testcase_run['build_revision'] = revision
Add additional testcase run data.
157,194
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 FUZZER_METADATA_REGEX = re.compile(r'metadata::(\w+):\s*(.*)') The provided code snippet includes necessary dependencies for implementing the `get_fuzzer_metadata_from_output` function. Write a Python function `def get_fuzzer_metadata_from_output(fuzzer_output)` to solve the following problem: Extract metadata from fuzzer output. Here is the function: def get_fuzzer_metadata_from_output(fuzzer_output): """Extract metadata from fuzzer output.""" metadata = {} for line in fuzzer_output.splitlines(): match = FUZZER_METADATA_REGEX.match(line) if match: metadata[match.group(1)] = match.group(2) return metadata
Extract metadata from fuzzer output.
157,195
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 `get_testcases` function. Write a Python function `def get_testcases(testcase_count, testcase_directory, data_directory)` to solve the following problem: Return fuzzed testcases from the data directories. Here is the function: def get_testcases(testcase_count, testcase_directory, data_directory): """Return fuzzed testcases from the data directories.""" logs.log('Locating generated test cases.') # Get the list of testcase files. testcase_directories = [testcase_directory, data_directory] testcase_file_paths = testcase_manager.get_testcases_from_directories( testcase_directories) # If the fuzzer created a bot-specific files list, add those now. bot_testcases_file_path = utils.get_bot_testcases_file_path(data_directory) if os.path.exists(bot_testcases_file_path): bot_testcases_file_content = utils.read_data_from_file( bot_testcases_file_path, eval_data=False) shell.remove_file(bot_testcases_file_path) if bot_testcases_file_content: bot_file_paths = bot_testcases_file_content.splitlines() testcase_file_paths += [ utils.normalize_path(path) for path in bot_file_paths ] generated_testcase_count = len(testcase_file_paths) # Create output strings. generated_testcase_string = ( 'Generated %d/%d testcases.' % (generated_testcase_count, testcase_count)) # Log the number of testcases generated. logs.log(generated_testcase_string) # If we are running the same command (again and again) on this bot, # we want to be careful of scenarios when the fuzzer starts failing # or has nothing to do, causing no testcases to be generated. This # will put lot of burden on appengine remote api. if (environment.get_value('COMMAND_OVERRIDE') and generated_testcase_count == 0): logs.log('No testcases generated. Sleeping for ~30 minutes.') time.sleep(random.uniform(1800, 2100)) return (testcase_file_paths, generated_testcase_count, generated_testcase_string)
Return fuzzed testcases from the data directories.
157,196
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 DEFAULT_CHOOSE_PROBABILITY = 9 MAX_GESTURES = 30 The provided code snippet includes necessary dependencies for implementing the `pick_gestures` function. Write a Python function `def pick_gestures(test_timeout)` to solve the following problem: Return a list of random gestures. Here is the function: def pick_gestures(test_timeout): """Return a list of random gestures.""" if not environment.get_value('ENABLE_GESTURES', True): # Gestures disabled. return [] # Probability of choosing gestures. if utils.random_number(0, DEFAULT_CHOOSE_PROBABILITY): return [] gesture_count = utils.random_number(1, MAX_GESTURES) gestures = gesture_handler.get_gestures(gesture_count) if not gestures: return [] # Pick a random trigger time to run the gesture at. min_gesture_time = int( utils.random_element_from_list([0.25, 0.50, 0.50, 0.50]) * test_timeout) max_gesture_time = test_timeout - 1 gesture_time = utils.random_number(min_gesture_time, max_gesture_time) gestures.append('Trigger:%d' % gesture_time) return gestures
Return a list of random gestures.
157,197
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 Redzone = collections.namedtuple('Redzone', ['size', 'weight']) The provided code snippet includes necessary dependencies for implementing the `pick_redzone` function. Write a Python function `def pick_redzone()` to solve the following problem: Return a random size for redzone. Here is the function: def pick_redzone(): """Return a random size for redzone.""" thread_multiplier = environment.get_value('THREAD_MULTIPLIER', 1) if thread_multiplier == 1: redzone_list = [ Redzone(16, 1.0), Redzone(32, 1.0), Redzone(64, 0.5), Redzone(128, 0.5), Redzone(256, 0.25), Redzone(512, 0.25), ] else: # For beefier boxes, prioritize using bigger redzones. redzone_list = [ Redzone(16, 0.25), Redzone(32, 0.25), Redzone(64, 0.50), Redzone(128, 0.50), Redzone(256, 1.0), Redzone(512, 1.0), ] return utils.random_weighted_choice(redzone_list).size
Return a random size for redzone.
157,198
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 DEFAULT_CHOOSE_PROBABILITY = 9 The provided code snippet includes necessary dependencies for implementing the `pick_ubsan_disabled` function. Write a Python function `def pick_ubsan_disabled(job_type)` to solve the following problem: Choose whether to disable UBSan in an ASan+UBSan build. Here is the function: def pick_ubsan_disabled(job_type): """Choose whether to disable UBSan in an ASan+UBSan build.""" # This is only applicable in an ASan build. memory_tool_name = environment.get_memory_tool_name(job_type) if memory_tool_name not in ['ASAN', 'HWASAN']: return False # Check if UBSan is enabled in this ASan build. If not, can't disable it. if not environment.get_value('UBSAN'): return False return not utils.random_number(0, DEFAULT_CHOOSE_PROBABILITY)
Choose whether to disable UBSan in an ASan+UBSan build.
157,199
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 DEFAULT_CHOOSE_PROBABILITY = 9 The provided code snippet includes necessary dependencies for implementing the `pick_timeout_multiplier` function. Write a Python function `def pick_timeout_multiplier()` to solve the following problem: Return a random testcase timeout multiplier and adjust timeout. Here is the function: def pick_timeout_multiplier(): """Return a random testcase timeout multiplier and adjust timeout.""" fuzz_test_timeout = environment.get_value('FUZZ_TEST_TIMEOUT') custom_timeout_multipliers = environment.get_value( 'CUSTOM_TIMEOUT_MULTIPLIERS') timeout_multiplier = 1.0 use_multiplier = not utils.random_number(0, DEFAULT_CHOOSE_PROBABILITY) if (use_multiplier and not fuzz_test_timeout and not custom_timeout_multipliers): timeout_multiplier = utils.random_element_from_list([0.5, 1.5, 2.0, 3.0]) elif use_multiplier and custom_timeout_multipliers: # Since they are explicitly set in the job definition, it is fine to use # custom timeout multipliers even in the case where FUZZ_TEST_TIMEOUT is # set. timeout_multiplier = utils.random_element_from_list( custom_timeout_multipliers) return timeout_multiplier
Return a random testcase timeout multiplier and adjust timeout.
157,200
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 `set_test_timeout` function. Write a Python function `def set_test_timeout(timeout, multipler)` to solve the following problem: Set the test timeout based on a timeout value and multiplier. Here is the function: def set_test_timeout(timeout, multipler): """Set the test timeout based on a timeout value and multiplier.""" test_timeout = int(timeout * multipler) environment.set_value('TEST_TIMEOUT', test_timeout) return test_timeout
Set the test timeout based on a timeout value and multiplier.
157,201
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 DEFAULT_CHOOSE_PROBABILITY = 9 The provided code snippet includes necessary dependencies for implementing the `pick_window_argument` function. Write a Python function `def pick_window_argument()` to solve the following problem: Return a window argument with random size and x,y position. Here is the function: def pick_window_argument(): """Return a window argument with random size and x,y position.""" default_window_argument = environment.get_value('WINDOW_ARG', '') window_argument_change_chance = not utils.random_number( 0, DEFAULT_CHOOSE_PROBABILITY) window_argument = '' if window_argument_change_chance: window_argument = default_window_argument if window_argument: width = utils.random_number( 100, utils.random_element_from_list([256, 1280, 2048])) height = utils.random_number( 100, utils.random_element_from_list([256, 1024, 1536])) left = utils.random_number(0, width) top = utils.random_number(0, height) window_argument = window_argument.replace('$WIDTH', str(width)) window_argument = window_argument.replace('$HEIGHT', str(height)) window_argument = window_argument.replace('$LEFT', str(left)) window_argument = window_argument.replace('$TOP', str(top)) # FIXME: Random seed is currently passed along to the next job # via WINDOW_ARG. Rename it without breaking existing tests. random_seed_argument = environment.get_value('RANDOM_SEED') if random_seed_argument: if window_argument: window_argument += ' ' seed = utils.random_number(-2147483648, 2147483647) window_argument += '%s=%d' % (random_seed_argument.strip(), seed) environment.set_value('WINDOW_ARG', window_argument) return window_argument
Return a window argument with random size and x,y position.
157,202
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) 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_groups_to_crashes` function. Write a Python function `def convert_groups_to_crashes( groups: List[CrashGroup]) -> List[uworker_msg_pb2.CrashInfo]` to solve the following problem: Converts groups to crashes (in an array of uworker_msg_pb2.CrashInfo) for JobRun. Here is the function: def convert_groups_to_crashes( groups: List[CrashGroup]) -> List[uworker_msg_pb2.CrashInfo]: """Converts groups to crashes (in an array of uworker_msg_pb2.CrashInfo) for JobRun.""" return [ uworker_msg_pb2.CrashInfo( is_new=group.is_new(), count=len(group.crashes), crash_type=group.main_crash.crash_type, crash_state=group.main_crash.crash_state, security_flag=group.main_crash.security_flag) for group in groups ]
Converts groups to crashes (in an array of uworker_msg_pb2.CrashInfo) for JobRun.