Path: blob/main/tools/test/stress2/testcases/badcode/badcode.c
39565 views
/*1* COPYRIGHT (c) 1990 BY *2* GEORGE J. CARRETTE, CONCORD, MASSACHUSETTS. *3* ALL RIGHTS RESERVED *45Permission to use, copy, modify, distribute and sell this software6and its documentation for any purpose and without fee is hereby7granted, provided that the above copyright notice appear in all copies8and that both that copyright notice and this permission notice appear9in supporting documentation, and that the name of the author10not be used in advertising or publicity pertaining to distribution11of the software without specific, written prior permission.1213THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING14ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL15HE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR16ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,17WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,18ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS19SOFTWARE.2021This code is based on crashme.c2223*/2425#include <sys/types.h>26#include <sys/mman.h>27#include <sys/param.h>28#include <sys/resource.h>29#include <sys/time.h>30#include <err.h>31#include <signal.h>32#include <stdio.h>33#include <stdlib.h>34#include <sys/wait.h>35#include <unistd.h>3637#include "stress.h"3839static pid_t pid;40static int failsafe;4142static int43tobemangled(void) {44volatile int i, j;4546j = 2;47for (i = 0; i < 100; i++)48j = j + 3;49j = j / 2;5051return (j);52}5354static void55mangle(void) { /* Change one byte in the code */56int i;57char *p = (void *)tobemangled;5859i = arc4random() % 50;60p[i] = arc4random() & 0xff;61}6263static void64hand(int i __unused) { /* handler */65_exit(1);66}6768static void69ahand(int i __unused) { /* alarm handler */70if (pid != 0) {71kill(pid, SIGKILL);72}73_exit(EXIT_SUCCESS);74}7576int77setup(int nb __unused)78{79return (0);80}8182void83cleanup(void)84{85}8687int88test(void)89{90void *st;91struct rlimit rl;9293if (failsafe)94return (0);9596while (done_testing == 0) {97signal(SIGALRM, ahand);98alarm(3);99if ((pid = fork()) == 0) {100rl.rlim_max = rl.rlim_cur = 0;101if (setrlimit(RLIMIT_CORE, &rl) == -1)102warn("setrlimit");103st = (void *)trunc_page((unsigned long)tobemangled);104if (mprotect(st, PAGE_SIZE, PROT_WRITE | PROT_READ |105PROT_EXEC) == -1)106err(1, "mprotect()");107108signal(SIGALRM, hand);109signal(SIGILL, hand);110signal(SIGFPE, hand);111signal(SIGSEGV, hand);112signal(SIGBUS, hand);113signal(SIGURG, hand);114signal(SIGSYS, hand);115signal(SIGTRAP, hand);116117mangle();118failsafe = 1;119(void)tobemangled();120121_exit(EXIT_SUCCESS);122123} else if (pid > 0) {124if (waitpid(pid, NULL, 0) == -1)125warn("waitpid(%d)", pid);126alarm(0);127} else128err(1, "fork(), %s:%d", __FILE__, __LINE__);129}130131return (0);132}133134135