github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/executor/cov_filter.h (about)

     1  // Copyright 2020 syzkaller project authors. All rights reserved.
     2  // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  #if SYZ_EXECUTOR_USES_SHMEM
     5  #include <fcntl.h>
     6  #include <sys/mman.h>
     7  #include <sys/stat.h>
     8  
     9  struct cov_filter_t {
    10  	uint32 pcstart;
    11  	uint32 pcsize;
    12  	uint8 bitmap[];
    13  };
    14  
    15  static cov_filter_t* cov_filter;
    16  
    17  static void init_coverage_filter(char* filename)
    18  {
    19  	int f = open(filename, O_RDONLY);
    20  	if (f < 0) {
    21  		// We don't fail here because we don't know yet if we should use coverage filter or not.
    22  		// We will receive the flag only in execute flags and will fail in coverage_filter if necessary.
    23  		debug("bitmap is not found, coverage filter disabled\n");
    24  		return;
    25  	}
    26  	struct stat st;
    27  	if (fstat(f, &st))
    28  		fail("faied to stat coverage filter");
    29  	// A random address for bitmap. Don't corrupt output_data.
    30  	void* preferred = (void*)0x110f230000ull;
    31  	cov_filter = (cov_filter_t*)mmap(preferred, st.st_size, PROT_READ, MAP_PRIVATE, f, 0);
    32  	if (cov_filter != preferred)
    33  		failmsg("failed to mmap coverage filter bitmap", "want=%p, got=%p", preferred, cov_filter);
    34  	if ((uint32)st.st_size != sizeof(uint32) * 2 + ((cov_filter->pcsize >> 4) / 8 + 2))
    35  		fail("bad coverage filter bitmap size");
    36  	close(f);
    37  }
    38  
    39  static bool coverage_filter(uint64 pc)
    40  {
    41  	if (!flag_coverage_filter)
    42  		return true;
    43  	if (cov_filter == NULL)
    44  		fail("coverage filter was enabled but bitmap initialization failed");
    45  	// Prevent out of bound while searching bitmap.
    46  	uint32 pc32 = (uint32)(pc & 0xffffffff);
    47  	if (pc32 < cov_filter->pcstart || pc32 > cov_filter->pcstart + cov_filter->pcsize)
    48  		return false;
    49  	// For minimizing the size of bitmap, the lowest 4-bit will be dropped.
    50  	pc32 -= cov_filter->pcstart;
    51  	pc32 = pc32 >> 4;
    52  	uint32 idx = pc32 / 8;
    53  	uint32 shift = pc32 % 8;
    54  	return (cov_filter->bitmap[idx] & (1 << shift)) > 0;
    55  }
    56  
    57  #else
    58  static void init_coverage_filter(char* filename)
    59  {
    60  }
    61  #endif