file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/60880.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2011-2017 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ static void pendfunc1 (void) { int x = 0; int y = x + 4; } void pendfunc (int x) { pendfunc1 (); }
the_stack_data/232956453.c
// general protection fault in nfulnl_recv_config // https://syzkaller.appspot.com/bug?id=b7259acb8c8386e8716c66b5491883b413cf53ce // status:open // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <string.h> #include <sys/syscall.h> #include <unistd.h> long r[1]; void loop() { memset(r, -1, sizeof(r)); syscall(__NR_mmap, 0x20000000, 0xfff000, 3, 0x32, -1, 0); r[0] = syscall(__NR_socket, 0x10, 3, 0xc); *(uint64_t*)0x20dddfc8 = 0x20f8d000; *(uint32_t*)0x20dddfd0 = 0xc; *(uint64_t*)0x20dddfd8 = 0x208a7000; *(uint64_t*)0x20dddfe0 = 1; *(uint64_t*)0x20dddfe8 = 0; *(uint64_t*)0x20dddff0 = 0; *(uint32_t*)0x20dddff8 = 0; *(uint16_t*)0x20f8d000 = 0x10; *(uint16_t*)0x20f8d002 = 0; *(uint32_t*)0x20f8d004 = 0; *(uint32_t*)0x20f8d008 = 0; *(uint64_t*)0x208a7000 = 0x2023df9c; *(uint64_t*)0x208a7008 = 0x2c; *(uint32_t*)0x2023df9c = 0x2c; *(uint8_t*)0x2023dfa0 = 1; *(uint8_t*)0x2023dfa1 = 4; *(uint16_t*)0x2023dfa2 = 0x101; *(uint32_t*)0x2023dfa4 = 0; *(uint32_t*)0x2023dfa8 = 0; *(uint8_t*)0x2023dfac = 0; *(uint8_t*)0x2023dfad = 0; *(uint16_t*)0x2023dfae = htobe16(0); *(uint16_t*)0x2023dfb0 = 0xc; *(uint16_t*)0x2023dfb2 = 1; *(uint32_t*)0x2023dfb8 = htobe32(0x7f000001); *(uint16_t*)0x2023dfbc = 0xc; *(uint16_t*)0x2023dfbe = 2; memcpy((void*)0x2023dfc0, "\xbb\xaf\xad\xb6\x7d", 5); syscall(__NR_sendmsg, r[0], 0x20dddfc8, 0); } int main() { loop(); return 0; }
the_stack_data/190768469.c
#include <stdlib.h> _Bool set_done; int *ptr; void *set_x(void *arg) { *(int *)arg = 10; set_done = 1; } int main(int argc, char *argv[]) { __CPROVER_assume(argc >= sizeof(int)); ptr = malloc(argc); __CPROVER_ASYNC_1: set_x(ptr); __CPROVER_assume(set_done); assert(*ptr == 10); return 0; }
the_stack_data/92325057.c
/* PR c/80163 */ /* { dg-do compile { target int128 } } */ volatile int v; __attribute__((noinline, noclone)) void bar (void) { v++; asm volatile ("" : : : "memory"); } __attribute__((noinline, noclone)) __int128_t * foo (unsigned long **p) { a: bar (); b: bar (); static __int128_t d = (unsigned long) &&a - (unsigned long) &&b; static unsigned long e = (unsigned long) &&a - (unsigned long) &&b; *p = &e; return &d; } int main () { __int128_t *p; unsigned long *q; p = foo (&q); if (*p != *q) __builtin_abort (); return 0; }
the_stack_data/145453118.c
extern void __VERIFIER_error(); typedef int _____STARTSTRIPPINGFROMHERE_____; typedef int __cs_cond_t; typedef int __cs_mutex_t; typedef int __cs_t; typedef int size_t; typedef int __gnuc_va_list; typedef int __int8_t; typedef int __uint8_t; typedef int __int16_t; typedef int __uint16_t; typedef int __int_least16_t; typedef int __uint_least16_t; typedef int __int32_t; typedef int __uint32_t; typedef int __int_least32_t; typedef int __uint_least32_t; typedef int _LOCK_T; typedef int _LOCK_RECURSIVE_T; typedef int _off_t; typedef int __dev_t; typedef int __uid_t; typedef int __gid_t; typedef int _off64_t; typedef int _fpos_t; typedef int _ssize_t; typedef int wint_t; typedef int _mbstate_t; typedef int _flock_t; typedef int _iconv_t; typedef int __ULong; typedef int __FILE; typedef int ptrdiff_t; typedef int wchar_t; typedef int __off_t; typedef int __pid_t; typedef int __loff_t; typedef int u_char; typedef int u_short; typedef int u_int; typedef int u_long; typedef int ushort; typedef int uint; typedef int clock_t; typedef int time_t; typedef int daddr_t; typedef int caddr_t; typedef int ino_t; typedef int off_t; typedef int dev_t; typedef int uid_t; typedef int gid_t; typedef int pid_t; typedef int key_t; typedef int ssize_t; typedef int mode_t; typedef int nlink_t; typedef int fd_mask; typedef int _types_fd_set; typedef int clockid_t; typedef int timer_t; typedef int useconds_t; typedef int suseconds_t; typedef int FILE; typedef int fpos_t; typedef int cookie_read_function_t; typedef int cookie_write_function_t; typedef int cookie_seek_function_t; typedef int cookie_close_function_t; typedef int cookie_io_functions_t; typedef int div_t; typedef int ldiv_t; typedef int lldiv_t; typedef int sigset_t; typedef int _sig_func_ptr; typedef int sig_atomic_t; typedef int __tzrule_type; typedef int __tzinfo_type; typedef int mbstate_t; typedef int sem_t; typedef int pthread_t; typedef int pthread_attr_t; typedef int pthread_mutex_t; typedef int pthread_mutexattr_t; typedef int pthread_cond_t; typedef int pthread_condattr_t; typedef int pthread_key_t; typedef int pthread_once_t; typedef int pthread_rwlock_t; typedef int pthread_rwlockattr_t; typedef int pthread_spinlock_t; typedef int pthread_barrier_t; typedef int pthread_barrierattr_t; typedef int int8_t; typedef int uint8_t; typedef int int16_t; typedef int uint16_t; typedef int int32_t; typedef int uint32_t; typedef int int64_t; typedef int uint64_t; typedef _Bool bool; typedef int va_list; typedef int _____STOPSTRIPPINGFROMHERE_____; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[5]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 5) { printf("stack overflow\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top == 0) { printf("stack underflow\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 5; if (push(arr, tmp) == (-1)) error(); pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (top > 0) { if (pop(arr) == (-2)) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
the_stack_data/211080918.c
int main() { int a = 68; a = a * a * a; return a; }
the_stack_data/93887888.c
/* Trabalho de introducao a programacao. Essa e uma implementacao do jogo tic tac chess, que pode ser jogado no terminal por dois jogadores ou contra o computador. Sofia Sampaio Lacerda 12611776 Ana Julia ? */ #include <stdlib.h> #include <stdio.h> void printboard(char board[3][3]) { printf("+---+\n"); printf("|%c%c%c|\n", board[0][0], board[0][1], board[0][2]); printf("|%c%c%c|\n", board[1][0], board[1][1], board[1][2]); printf("|%c%c%c|\n", board[2][0], board[1][1], board[2][2]); printf("+---+\n"); return; } int main(void) { char board[3][3] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; for(int i = 0; ; ++i) { printboard(board); if(i % 2 == 0) { printf("vez do jogador 1 (pecas brancas)\n"); } else { printf("vez do jogador 2 (pecas pretas)\n"); } char move[4]; scanf("%s", move); int row = move[2] - 49; int column = move[1] - 97; //int column = atoi(&move[1]); //printf("%d, %d\n", row, column); board[row][column] = move[0]; } return 0; }
the_stack_data/122016097.c
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_15__ TYPE_7__ ; typedef struct TYPE_14__ TYPE_5__ ; typedef struct TYPE_13__ TYPE_3__ ; typedef struct TYPE_12__ TYPE_2__ ; typedef struct TYPE_11__ TYPE_1__ ; /* Type definitions */ struct usb_interface {int /*<<< orphan*/ dev; struct usb_host_interface* cur_altsetting; } ; struct TYPE_11__ {int bNumEndpoints; } ; struct usb_host_interface {TYPE_2__* endpoint; TYPE_1__ desc; } ; struct usb_endpoint_descriptor {int /*<<< orphan*/ wMaxPacketSize; } ; struct usb_device_id {int idVendor; int idProduct; } ; struct TYPE_14__ {int /*<<< orphan*/ release; } ; struct TYPE_15__ {int error; } ; struct TYPE_13__ {int device_caps; int /*<<< orphan*/ release; TYPE_5__* v4l2_dev; int /*<<< orphan*/ * lock; TYPE_7__* ctrl_handler; } ; struct si470x_device {int band; int* registers; int software_version; int hardware_version; int buf_size; struct si470x_device* usb_buf; struct si470x_device* int_in_buffer; int /*<<< orphan*/ int_in_urb; TYPE_5__ v4l2_dev; TYPE_7__ hdl; struct si470x_device* buffer; TYPE_3__ videodev; int /*<<< orphan*/ read_queue; scalar_t__ rd_index; scalar_t__ wr_index; int /*<<< orphan*/ lock; int /*<<< orphan*/ usbdev; struct usb_endpoint_descriptor* int_in_endpoint; int /*<<< orphan*/ vidioc_querycap; int /*<<< orphan*/ fops_release; int /*<<< orphan*/ fops_open; int /*<<< orphan*/ set_register; int /*<<< orphan*/ get_register; int /*<<< orphan*/ completion; struct usb_interface* intf; } ; struct TYPE_12__ {struct usb_endpoint_descriptor desc; } ; /* Variables and functions */ int /*<<< orphan*/ BLINK_GREEN_LED ; size_t DEVICEID ; int EIO ; int ENODEV ; int ENOMEM ; double FREQ_MUL ; int /*<<< orphan*/ GFP_KERNEL ; int /*<<< orphan*/ HID_REQ_GET_REPORT ; int MAX_REPORT_SIZE ; int RADIO_FW_VERSION ; int RADIO_HW_VERSION ; size_t SI_CHIPID ; int SI_CHIPID_FIRMWARE ; int USB_DIR_IN ; int USB_RECIP_INTERFACE ; int USB_TYPE_CLASS ; int V4L2_CAP_HW_FREQ_SEEK ; int V4L2_CAP_RADIO ; int V4L2_CAP_RDS_CAPTURE ; int V4L2_CAP_READWRITE ; int V4L2_CAP_TUNER ; int /*<<< orphan*/ V4L2_CID_AUDIO_MUTE ; int /*<<< orphan*/ V4L2_CID_AUDIO_VOLUME ; int /*<<< orphan*/ VFL_TYPE_RADIO ; int /*<<< orphan*/ dev_err (int /*<<< orphan*/ *,char*) ; int /*<<< orphan*/ dev_info (int /*<<< orphan*/ *,char*,...) ; int /*<<< orphan*/ dev_warn (int /*<<< orphan*/ *,char*,...) ; int get_unaligned_be16 (struct si470x_device*) ; int /*<<< orphan*/ init_completion (int /*<<< orphan*/ *) ; int /*<<< orphan*/ init_waitqueue_head (int /*<<< orphan*/ *) ; int /*<<< orphan*/ interface_to_usbdev (struct usb_interface*) ; int /*<<< orphan*/ kfree (struct si470x_device*) ; void* kmalloc (int,int /*<<< orphan*/ ) ; struct si470x_device* kzalloc (int,int /*<<< orphan*/ ) ; int le16_to_cpu (int /*<<< orphan*/ ) ; int /*<<< orphan*/ mutex_init (int /*<<< orphan*/ *) ; int /*<<< orphan*/ radio_nr ; int rds_buf ; int /*<<< orphan*/ si470x_ctrl_ops ; int /*<<< orphan*/ si470x_fops_open ; int /*<<< orphan*/ si470x_fops_release ; scalar_t__ si470x_get_all_registers (struct si470x_device*) ; int /*<<< orphan*/ si470x_get_register ; scalar_t__ si470x_get_scratch_page_versions (struct si470x_device*) ; int /*<<< orphan*/ si470x_set_freq (struct si470x_device*,double) ; int /*<<< orphan*/ si470x_set_led_state (struct si470x_device*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ si470x_set_register ; int si470x_start_usb (struct si470x_device*) ; int /*<<< orphan*/ si470x_usb_release ; TYPE_3__ si470x_viddev_template ; int /*<<< orphan*/ si470x_vidioc_querycap ; int /*<<< orphan*/ usb_alloc_urb (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int usb_control_msg (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int,int,int,struct si470x_device*,int,int) ; scalar_t__ usb_endpoint_is_int_in (struct usb_endpoint_descriptor*) ; int /*<<< orphan*/ usb_free_urb (int /*<<< orphan*/ ) ; int /*<<< orphan*/ usb_kill_urb (int /*<<< orphan*/ ) ; int /*<<< orphan*/ usb_rcvctrlpipe (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ usb_set_intfdata (struct usb_interface*,struct si470x_device*) ; int /*<<< orphan*/ v4l2_ctrl_handler_free (TYPE_7__*) ; int /*<<< orphan*/ v4l2_ctrl_handler_init (TYPE_7__*,int) ; int /*<<< orphan*/ v4l2_ctrl_new_std (TYPE_7__*,int /*<<< orphan*/ *,int /*<<< orphan*/ ,int /*<<< orphan*/ ,int,int,int) ; int v4l2_device_register (int /*<<< orphan*/ *,TYPE_5__*) ; int /*<<< orphan*/ v4l2_device_unregister (TYPE_5__*) ; int /*<<< orphan*/ video_device_release_empty ; int video_register_device (TYPE_3__*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ video_set_drvdata (TYPE_3__*,struct si470x_device*) ; __attribute__((used)) static int si470x_usb_driver_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct si470x_device *radio; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int i, int_end_size, retval; unsigned char version_warning = 0; /* private data allocation and initialization */ radio = kzalloc(sizeof(struct si470x_device), GFP_KERNEL); if (!radio) { retval = -ENOMEM; goto err_initial; } radio->usb_buf = kmalloc(MAX_REPORT_SIZE, GFP_KERNEL); if (radio->usb_buf == NULL) { retval = -ENOMEM; goto err_radio; } radio->usbdev = interface_to_usbdev(intf); radio->intf = intf; radio->band = 1; /* Default to 76 - 108 MHz */ mutex_init(&radio->lock); init_completion(&radio->completion); radio->get_register = si470x_get_register; radio->set_register = si470x_set_register; radio->fops_open = si470x_fops_open; radio->fops_release = si470x_fops_release; radio->vidioc_querycap = si470x_vidioc_querycap; iface_desc = intf->cur_altsetting; /* Set up interrupt endpoint information. */ for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (usb_endpoint_is_int_in(endpoint)) radio->int_in_endpoint = endpoint; } if (!radio->int_in_endpoint) { dev_info(&intf->dev, "could not find interrupt in endpoint\n"); retval = -EIO; goto err_usbbuf; } int_end_size = le16_to_cpu(radio->int_in_endpoint->wMaxPacketSize); radio->int_in_buffer = kmalloc(int_end_size, GFP_KERNEL); if (!radio->int_in_buffer) { dev_info(&intf->dev, "could not allocate int_in_buffer"); retval = -ENOMEM; goto err_usbbuf; } radio->int_in_urb = usb_alloc_urb(0, GFP_KERNEL); if (!radio->int_in_urb) { retval = -ENOMEM; goto err_intbuffer; } radio->v4l2_dev.release = si470x_usb_release; /* * The si470x SiLabs reference design uses the same USB IDs as * 'Thanko's Raremono' si4734 based receiver. So check here which we * have: attempt to read the device ID from the si470x: the lower 12 * bits should be 0x0242 for the si470x. * * We use this check to determine which device we are dealing with. */ if (id->idVendor == 0x10c4 && id->idProduct == 0x818a) { retval = usb_control_msg(radio->usbdev, usb_rcvctrlpipe(radio->usbdev, 0), HID_REQ_GET_REPORT, USB_TYPE_CLASS | USB_RECIP_INTERFACE | USB_DIR_IN, 1, 2, radio->usb_buf, 3, 500); if (retval != 3 || (get_unaligned_be16(&radio->usb_buf[1]) & 0xfff) != 0x0242) { dev_info(&intf->dev, "this is not a si470x device.\n"); retval = -ENODEV; goto err_urb; } } retval = v4l2_device_register(&intf->dev, &radio->v4l2_dev); if (retval < 0) { dev_err(&intf->dev, "couldn't register v4l2_device\n"); goto err_urb; } v4l2_ctrl_handler_init(&radio->hdl, 2); v4l2_ctrl_new_std(&radio->hdl, &si470x_ctrl_ops, V4L2_CID_AUDIO_MUTE, 0, 1, 1, 1); v4l2_ctrl_new_std(&radio->hdl, &si470x_ctrl_ops, V4L2_CID_AUDIO_VOLUME, 0, 15, 1, 15); if (radio->hdl.error) { retval = radio->hdl.error; dev_err(&intf->dev, "couldn't register control\n"); goto err_dev; } radio->videodev = si470x_viddev_template; radio->videodev.ctrl_handler = &radio->hdl; radio->videodev.lock = &radio->lock; radio->videodev.v4l2_dev = &radio->v4l2_dev; radio->videodev.release = video_device_release_empty; radio->videodev.device_caps = V4L2_CAP_HW_FREQ_SEEK | V4L2_CAP_READWRITE | V4L2_CAP_TUNER | V4L2_CAP_RADIO | V4L2_CAP_RDS_CAPTURE; video_set_drvdata(&radio->videodev, radio); /* get device and chip versions */ if (si470x_get_all_registers(radio) < 0) { retval = -EIO; goto err_ctrl; } dev_info(&intf->dev, "DeviceID=0x%4.4hx ChipID=0x%4.4hx\n", radio->registers[DEVICEID], radio->registers[SI_CHIPID]); if ((radio->registers[SI_CHIPID] & SI_CHIPID_FIRMWARE) < RADIO_FW_VERSION) { dev_warn(&intf->dev, "This driver is known to work with firmware version %hu,\n", RADIO_FW_VERSION); dev_warn(&intf->dev, "but the device has firmware version %hu.\n", radio->registers[SI_CHIPID] & SI_CHIPID_FIRMWARE); version_warning = 1; } /* get software and hardware versions */ if (si470x_get_scratch_page_versions(radio) < 0) { retval = -EIO; goto err_ctrl; } dev_info(&intf->dev, "software version %d, hardware version %d\n", radio->software_version, radio->hardware_version); if (radio->hardware_version < RADIO_HW_VERSION) { dev_warn(&intf->dev, "This driver is known to work with hardware version %hu,\n", RADIO_HW_VERSION); dev_warn(&intf->dev, "but the device has hardware version %hu.\n", radio->hardware_version); version_warning = 1; } /* give out version warning */ if (version_warning == 1) { dev_warn(&intf->dev, "If you have some trouble using this driver,\n"); dev_warn(&intf->dev, "please report to V4L ML at [email protected]\n"); } /* set led to connect state */ si470x_set_led_state(radio, BLINK_GREEN_LED); /* rds buffer allocation */ radio->buf_size = rds_buf * 3; radio->buffer = kmalloc(radio->buf_size, GFP_KERNEL); if (!radio->buffer) { retval = -EIO; goto err_ctrl; } /* rds buffer configuration */ radio->wr_index = 0; radio->rd_index = 0; init_waitqueue_head(&radio->read_queue); usb_set_intfdata(intf, radio); /* start radio */ retval = si470x_start_usb(radio); if (retval < 0) goto err_buf; /* set initial frequency */ si470x_set_freq(radio, 87.5 * FREQ_MUL); /* available in all regions */ /* register video device */ retval = video_register_device(&radio->videodev, VFL_TYPE_RADIO, radio_nr); if (retval) { dev_err(&intf->dev, "Could not register video device\n"); goto err_all; } return 0; err_all: usb_kill_urb(radio->int_in_urb); err_buf: kfree(radio->buffer); err_ctrl: v4l2_ctrl_handler_free(&radio->hdl); err_dev: v4l2_device_unregister(&radio->v4l2_dev); err_urb: usb_free_urb(radio->int_in_urb); err_intbuffer: kfree(radio->int_in_buffer); err_usbbuf: kfree(radio->usb_buf); err_radio: kfree(radio); err_initial: return retval; }
the_stack_data/50137575.c
/* Copyright (c) 2014, Matthias Schiffer <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* tplink-safeloader Image generation tool for the TP-LINK SafeLoader as seen on TP-LINK Pharos devices (CPE210/220/510/520) */ #include <assert.h> #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include "md5.h" #define ALIGN(x,a) ({ typeof(a) __a = (a); (((x) + __a - 1) & ~(__a - 1)); }) #define MAX_PARTITIONS 32 /** An image partition table entry */ struct image_partition_entry { const char *name; size_t size; uint8_t *data; }; /** A flash partition table entry */ struct flash_partition_entry { const char *name; uint32_t base; uint32_t size; }; /** Firmware layout description */ struct device_info { const char *id; const char *vendor; const char *support_list; char support_trail; const char *soft_ver; const struct flash_partition_entry partitions[MAX_PARTITIONS+1]; const char *first_sysupgrade_partition; const char *last_sysupgrade_partition; }; /** The content of the soft-version structure */ struct __attribute__((__packed__)) soft_version { uint32_t magic; uint32_t zero; uint8_t pad1; uint8_t version_major; uint8_t version_minor; uint8_t version_patch; uint8_t year_hi; uint8_t year_lo; uint8_t month; uint8_t day; uint32_t rev; uint8_t pad2; }; static const uint8_t jffs2_eof_mark[4] = {0xde, 0xad, 0xc0, 0xde}; /** Salt for the MD5 hash Fortunately, TP-LINK seems to use the same salt for most devices which use the new image format. */ static const uint8_t md5_salt[16] = { 0x7a, 0x2b, 0x15, 0xed, 0x9b, 0x98, 0x59, 0x6d, 0xe5, 0x04, 0xab, 0x44, 0xac, 0x2a, 0x9f, 0x4e, }; /** Firmware layout table */ static struct device_info boards[] = { /** Firmware layout for the CPE210/220 */ { .id = "CPE210", .vendor = "CPE510(TP-LINK|UN|N300-5):1.0\r\n", .support_list = "SupportList:\r\n" "CPE210(TP-LINK|UN|N300-2):1.0\r\n" "CPE210(TP-LINK|UN|N300-2):1.1\r\n" "CPE210(TP-LINK|US|N300-2):1.1\r\n" "CPE210(TP-LINK|EU|N300-2):1.1\r\n" "CPE220(TP-LINK|UN|N300-2):1.1\r\n" "CPE220(TP-LINK|US|N300-2):1.1\r\n" "CPE220(TP-LINK|EU|N300-2):1.1\r\n", .support_trail = '\xff', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"partition-table", 0x20000, 0x02000}, {"default-mac", 0x30000, 0x00020}, {"product-info", 0x31100, 0x00100}, {"signature", 0x32000, 0x00400}, {"os-image", 0x40000, 0x1c0000}, {"file-system", 0x200000, 0x5b0000}, {"soft-version", 0x7b0000, 0x00100}, {"support-list", 0x7b1000, 0x00400}, {"user-config", 0x7c0000, 0x10000}, {"default-config", 0x7d0000, 0x10000}, {"log", 0x7e0000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "support-list", }, /** Firmware layout for the CPE210 V2 */ { .id = "CPE210V2", .vendor = "CPE210(TP-LINK|UN|N300-2|00000000):2.0\r\n", .support_list = "SupportList:\r\n" "CPE210(TP-LINK|EU|N300-2|00000000):2.0\r\n" "CPE210(TP-LINK|EU|N300-2|45550000):2.0\r\n" "CPE210(TP-LINK|EU|N300-2|55530000):2.0\r\n" "CPE210(TP-LINK|UN|N300-2|00000000):2.0\r\n" "CPE210(TP-LINK|UN|N300-2|45550000):2.0\r\n" "CPE210(TP-LINK|UN|N300-2|55530000):2.0\r\n" "CPE210(TP-LINK|US|N300-2|55530000):2.0\r\n" "CPE210(TP-LINK|UN|N300-2):2.0\r\n" "CPE210(TP-LINK|EU|N300-2):2.0\r\n" "CPE210(TP-LINK|US|N300-2):2.0\r\n", .support_trail = '\xff', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"partition-table", 0x20000, 0x02000}, {"default-mac", 0x30000, 0x00020}, {"product-info", 0x31100, 0x00100}, {"device-info", 0x31400, 0x00400}, {"signature", 0x32000, 0x00400}, {"device-id", 0x33000, 0x00100}, {"os-image", 0x40000, 0x1c0000}, {"file-system", 0x200000, 0x5b0000}, {"soft-version", 0x7b0000, 0x00100}, {"support-list", 0x7b1000, 0x01000}, {"user-config", 0x7c0000, 0x10000}, {"default-config", 0x7d0000, 0x10000}, {"log", 0x7e0000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "support-list", }, /** Firmware layout for the CPE510/520 */ { .id = "CPE510", .vendor = "CPE510(TP-LINK|UN|N300-5):1.0\r\n", .support_list = "SupportList:\r\n" "CPE510(TP-LINK|UN|N300-5):1.0\r\n" "CPE510(TP-LINK|UN|N300-5):1.1\r\n" "CPE510(TP-LINK|UN|N300-5):1.1\r\n" "CPE510(TP-LINK|US|N300-5):1.1\r\n" "CPE510(TP-LINK|EU|N300-5):1.1\r\n" "CPE520(TP-LINK|UN|N300-5):1.1\r\n" "CPE520(TP-LINK|US|N300-5):1.1\r\n" "CPE520(TP-LINK|EU|N300-5):1.1\r\n", .support_trail = '\xff', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"partition-table", 0x20000, 0x02000}, {"default-mac", 0x30000, 0x00020}, {"product-info", 0x31100, 0x00100}, {"signature", 0x32000, 0x00400}, {"os-image", 0x40000, 0x1c0000}, {"file-system", 0x200000, 0x5b0000}, {"soft-version", 0x7b0000, 0x00100}, {"support-list", 0x7b1000, 0x00400}, {"user-config", 0x7c0000, 0x10000}, {"default-config", 0x7d0000, 0x10000}, {"log", 0x7e0000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "support-list", }, { .id = "WBS210", .vendor = "CPE510(TP-LINK|UN|N300-5):1.0\r\n", .support_list = "SupportList:\r\n" "WBS210(TP-LINK|UN|N300-2):1.20\r\n" "WBS210(TP-LINK|US|N300-2):1.20\r\n" "WBS210(TP-LINK|EU|N300-2):1.20\r\n", .support_trail = '\xff', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"partition-table", 0x20000, 0x02000}, {"default-mac", 0x30000, 0x00020}, {"product-info", 0x31100, 0x00100}, {"signature", 0x32000, 0x00400}, {"os-image", 0x40000, 0x1c0000}, {"file-system", 0x200000, 0x5b0000}, {"soft-version", 0x7b0000, 0x00100}, {"support-list", 0x7b1000, 0x00400}, {"user-config", 0x7c0000, 0x10000}, {"default-config", 0x7d0000, 0x10000}, {"log", 0x7e0000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "support-list", }, { .id = "WBS510", .vendor = "CPE510(TP-LINK|UN|N300-5):1.0\r\n", .support_list = "SupportList:\r\n" "WBS510(TP-LINK|UN|N300-5):1.20\r\n" "WBS510(TP-LINK|US|N300-5):1.20\r\n" "WBS510(TP-LINK|EU|N300-5):1.20\r\n", .support_trail = '\xff', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"partition-table", 0x20000, 0x02000}, {"default-mac", 0x30000, 0x00020}, {"product-info", 0x31100, 0x00100}, {"signature", 0x32000, 0x00400}, {"os-image", 0x40000, 0x1c0000}, {"file-system", 0x200000, 0x5b0000}, {"soft-version", 0x7b0000, 0x00100}, {"support-list", 0x7b1000, 0x00400}, {"user-config", 0x7c0000, 0x10000}, {"default-config", 0x7d0000, 0x10000}, {"log", 0x7e0000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "support-list", }, /** Firmware layout for the C2600 */ { .id = "C2600", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:Archer C2600,product_ver:1.0.0,special_id:00000000}\r\n", .support_trail = '\x00', .soft_ver = NULL, /** We use a bigger os-image partition than the stock images (and thus smaller file-system), as our kernel doesn't fit in the stock firmware's 2 MB os-image since kernel 4.14. */ .partitions = { {"SBL1", 0x00000, 0x20000}, {"MIBIB", 0x20000, 0x20000}, {"SBL2", 0x40000, 0x20000}, {"SBL3", 0x60000, 0x30000}, {"DDRCONFIG", 0x90000, 0x10000}, {"SSD", 0xa0000, 0x10000}, {"TZ", 0xb0000, 0x30000}, {"RPM", 0xe0000, 0x20000}, {"fs-uboot", 0x100000, 0x70000}, {"uboot-env", 0x170000, 0x40000}, {"radio", 0x1b0000, 0x40000}, {"os-image", 0x1f0000, 0x400000}, /* Stock: base 0x1f0000 size 0x200000 */ {"file-system", 0x5f0000, 0x1900000}, /* Stock: base 0x3f0000 size 0x1b00000 */ {"default-mac", 0x1ef0000, 0x00200}, {"pin", 0x1ef0200, 0x00200}, {"product-info", 0x1ef0400, 0x0fc00}, {"partition-table", 0x1f00000, 0x10000}, {"soft-version", 0x1f10000, 0x10000}, {"support-list", 0x1f20000, 0x10000}, {"profile", 0x1f30000, 0x10000}, {"default-config", 0x1f40000, 0x10000}, {"user-config", 0x1f50000, 0x40000}, {"qos-db", 0x1f90000, 0x40000}, {"usb-config", 0x1fd0000, 0x10000}, {"log", 0x1fe0000, 0x20000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the C25v1 */ { .id = "ARCHER-C25-V1", .support_list = "SupportList:\n" "{product_name:ArcherC25,product_ver:1.0.0,special_id:00000000}\n" "{product_name:ArcherC25,product_ver:1.0.0,special_id:55530000}\n" "{product_name:ArcherC25,product_ver:1.0.0,special_id:45550000}\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", /** We use a bigger os-image partition than the stock images (and thus smaller file-system), as our kernel doesn't fit in the stock firmware's 1MB os-image. */ .partitions = { {"factory-boot", 0x00000, 0x20000}, {"fs-uboot", 0x20000, 0x10000}, {"os-image", 0x30000, 0x180000}, /* Stock: base 0x30000 size 0x100000 */ {"file-system", 0x1b0000, 0x620000}, /* Stock: base 0x130000 size 0x6a0000 */ {"user-config", 0x7d0000, 0x04000}, {"default-mac", 0x7e0000, 0x00100}, {"device-id", 0x7e0100, 0x00100}, {"extra-para", 0x7e0200, 0x00100}, {"pin", 0x7e0300, 0x00100}, {"support-list", 0x7e0400, 0x00400}, {"soft-version", 0x7e0800, 0x00400}, {"product-info", 0x7e0c00, 0x01400}, {"partition-table", 0x7e2000, 0x01000}, {"profile", 0x7e3000, 0x01000}, {"default-config", 0x7e4000, 0x04000}, {"merge-config", 0x7ec000, 0x02000}, {"qos-db", 0x7ee000, 0x02000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C58v1 */ { .id = "ARCHER-C58-V1", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:Archer C58,product_ver:1.0.0,special_id:00000000}\r\n" "{product_name:Archer C58,product_ver:1.0.0,special_id:45550000}\r\n" "{product_name:Archer C58,product_ver:1.0.0,special_id:55530000}\r\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", .partitions = { {"fs-uboot", 0x00000, 0x10000}, {"default-mac", 0x10000, 0x00200}, {"pin", 0x10200, 0x00200}, {"product-info", 0x10400, 0x00100}, {"partition-table", 0x10500, 0x00800}, {"soft-version", 0x11300, 0x00200}, {"support-list", 0x11500, 0x00100}, {"device-id", 0x11600, 0x00100}, {"profile", 0x11700, 0x03900}, {"default-config", 0x15000, 0x04000}, {"user-config", 0x19000, 0x04000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0x648000}, {"certyficate", 0x7e8000, 0x08000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C59v1 */ { .id = "ARCHER-C59-V1", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:Archer C59,product_ver:1.0.0,special_id:00000000}\r\n" "{product_name:Archer C59,product_ver:1.0.0,special_id:45550000}\r\n" "{product_name:Archer C59,product_ver:1.0.0,special_id:52550000}\r\n" "{product_name:Archer C59,product_ver:1.0.0,special_id:55530000}\r\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", .partitions = { {"fs-uboot", 0x00000, 0x10000}, {"default-mac", 0x10000, 0x00200}, {"pin", 0x10200, 0x00200}, {"device-id", 0x10400, 0x00100}, {"product-info", 0x10500, 0x0fb00}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0xcb0000}, {"partition-table", 0xe50000, 0x10000}, {"soft-version", 0xe60000, 0x10000}, {"support-list", 0xe70000, 0x10000}, {"profile", 0xe80000, 0x10000}, {"default-config", 0xe90000, 0x10000}, {"user-config", 0xea0000, 0x40000}, {"usb-config", 0xee0000, 0x10000}, {"certificate", 0xef0000, 0x10000}, {"qos-db", 0xf00000, 0x40000}, {"log", 0xfe0000, 0x10000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C60v1 */ { .id = "ARCHER-C60-V1", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:Archer C60,product_ver:1.0.0,special_id:00000000}\r\n" "{product_name:Archer C60,product_ver:1.0.0,special_id:45550000}\r\n" "{product_name:Archer C60,product_ver:1.0.0,special_id:55530000}\r\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", .partitions = { {"fs-uboot", 0x00000, 0x10000}, {"default-mac", 0x10000, 0x00200}, {"pin", 0x10200, 0x00200}, {"product-info", 0x10400, 0x00100}, {"partition-table", 0x10500, 0x00800}, {"soft-version", 0x11300, 0x00200}, {"support-list", 0x11500, 0x00100}, {"device-id", 0x11600, 0x00100}, {"profile", 0x11700, 0x03900}, {"default-config", 0x15000, 0x04000}, {"user-config", 0x19000, 0x04000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0x648000}, {"certyficate", 0x7e8000, 0x08000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C60v2 */ { .id = "ARCHER-C60-V2", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:Archer C60,product_ver:2.0.0,special_id:42520000}\r\n" "{product_name:Archer C60,product_ver:2.0.0,special_id:45550000}\r\n" "{product_name:Archer C60,product_ver:2.0.0,special_id:55530000}\r\n", .support_trail = '\x00', .soft_ver = "soft_ver:2.0.0\n", .partitions = { {"factory-boot", 0x00000, 0x1fb00}, {"default-mac", 0x1fb00, 0x00200}, {"pin", 0x1fd00, 0x00100}, {"product-info", 0x1fe00, 0x00100}, {"device-id", 0x1ff00, 0x00100}, {"fs-uboot", 0x20000, 0x10000}, {"os-image", 0x30000, 0x180000}, {"file-system", 0x1b0000, 0x620000}, {"soft-version", 0x7d9500, 0x00100}, {"support-list", 0x7d9600, 0x00100}, {"extra-para", 0x7d9700, 0x00100}, {"profile", 0x7d9800, 0x03000}, {"default-config", 0x7dc800, 0x03000}, {"partition-table", 0x7df800, 0x00800}, {"user-config", 0x7e0000, 0x0c000}, {"certificate", 0x7ec000, 0x04000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C5 */ { .id = "ARCHER-C5-V2", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:ArcherC5,product_ver:2.0.0,special_id:00000000}\r\n" "{product_name:ArcherC5,product_ver:2.0.0,special_id:55530000}\r\n" "{product_name:ArcherC5,product_ver:2.0.0,special_id:4A500000}\r\n", /* JP version */ .support_trail = '\x00', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x40000}, {"os-image", 0x40000, 0x200000}, {"file-system", 0x240000, 0xc00000}, {"default-mac", 0xe40000, 0x00200}, {"pin", 0xe40200, 0x00200}, {"product-info", 0xe40400, 0x00200}, {"partition-table", 0xe50000, 0x10000}, {"soft-version", 0xe60000, 0x00200}, {"support-list", 0xe61000, 0x0f000}, {"profile", 0xe70000, 0x10000}, {"default-config", 0xe80000, 0x10000}, {"user-config", 0xe90000, 0x50000}, {"log", 0xee0000, 0x100000}, {"radio_bk", 0xfe0000, 0x10000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the C7 */ { .id = "ARCHER-C7-V4", .support_list = "SupportList:\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:00000000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:41550000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:45550000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:4B520000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:42520000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:4A500000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:52550000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:54570000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:55530000}\n" "{product_name:Archer C7,product_ver:4.0.0,special_id:43410000}\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", /** We use a bigger os-image partition than the stock images (and thus smaller file-system), as our kernel doesn't fit in the stock firmware's 1MB os-image. */ .partitions = { {"factory-boot", 0x00000, 0x20000}, {"fs-uboot", 0x20000, 0x20000}, {"os-image", 0x40000, 0x180000}, /* Stock: base 0x40000 size 0x120000 */ {"file-system", 0x1c0000, 0xd40000}, /* Stock: base 0x160000 size 0xda0000 */ {"default-mac", 0xf00000, 0x00200}, {"pin", 0xf00200, 0x00200}, {"device-id", 0xf00400, 0x00100}, {"product-info", 0xf00500, 0x0fb00}, {"soft-version", 0xf10000, 0x00100}, {"extra-para", 0xf11000, 0x01000}, {"support-list", 0xf12000, 0x0a000}, {"profile", 0xf1c000, 0x04000}, {"default-config", 0xf20000, 0x10000}, {"user-config", 0xf30000, 0x40000}, {"qos-db", 0xf70000, 0x40000}, {"certificate", 0xfb0000, 0x10000}, {"partition-table", 0xfc0000, 0x10000}, {"log", 0xfd0000, 0x20000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C7 v5*/ { .id = "ARCHER-C7-V5", .support_list = "SupportList:\n" "{product_name:Archer C7,product_ver:5.0.0,special_id:00000000}\n" "{product_name:Archer C7,product_ver:5.0.0,special_id:45550000}\n" "{product_name:Archer C7,product_ver:5.0.0,special_id:55530000}\n" "{product_name:Archer C7,product_ver:5.0.0,special_id:43410000}\n" "{product_name:Archer C7,product_ver:5.0.0,special_id:4A500000}\n" "{product_name:Archer C7,product_ver:5.0.0,special_id:54570000}\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", /** We use a bigger os-image partition than the stock images (and thus smaller file-system), as our kernel doesn't fit in the stock firmware's 1MB os-image. */ .partitions = { {"factory-boot", 0x00000, 0x20000}, {"fs-uboot", 0x20000, 0x20000}, {"partition-table", 0x40000, 0x10000}, {"radio", 0x50000, 0x10000}, {"default-mac", 0x60000, 0x00200}, {"pin", 0x60200, 0x00200}, {"device-id", 0x60400, 0x00100}, {"product-info", 0x60500, 0x0fb00}, {"soft-version", 0x70000, 0x01000}, {"extra-para", 0x71000, 0x01000}, {"support-list", 0x72000, 0x0a000}, {"profile", 0x7c000, 0x04000}, {"user-config", 0x80000, 0x40000}, {"os-image", 0xc0000, 0x180000}, /* Stock: base 0xc0000 size 0x120000 */ {"file-system", 0x240000, 0xd80000}, /* Stock: base 0x1e0000 size 0xde0000 */ {"log", 0xfc0000, 0x20000}, {"certificate", 0xfe0000, 0x10000}, {"default-config", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the C9 */ { .id = "ARCHERC9", .vendor = "", .support_list = "SupportList:\n" "{product_name:ArcherC9," "product_ver:1.0.0," "special_id:00000000}\n", .support_trail = '\x00', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x40000}, {"os-image", 0x40000, 0x200000}, {"file-system", 0x240000, 0xc00000}, {"default-mac", 0xe40000, 0x00200}, {"pin", 0xe40200, 0x00200}, {"product-info", 0xe40400, 0x00200}, {"partition-table", 0xe50000, 0x10000}, {"soft-version", 0xe60000, 0x00200}, {"support-list", 0xe61000, 0x0f000}, {"profile", 0xe70000, 0x10000}, {"default-config", 0xe80000, 0x10000}, {"user-config", 0xe90000, 0x50000}, {"log", 0xee0000, 0x100000}, {"radio_bk", 0xfe0000, 0x10000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the EAP120 */ { .id = "EAP120", .vendor = "EAP120(TP-LINK|UN|N300-2):1.0\r\n", .support_list = "SupportList:\r\n" "EAP120(TP-LINK|UN|N300-2):1.0\r\n", .support_trail = '\xff', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"partition-table", 0x20000, 0x02000}, {"default-mac", 0x30000, 0x00020}, {"support-list", 0x31000, 0x00100}, {"product-info", 0x31100, 0x00100}, {"soft-version", 0x32000, 0x00100}, {"os-image", 0x40000, 0x180000}, {"file-system", 0x1c0000, 0x600000}, {"user-config", 0x7c0000, 0x10000}, {"backup-config", 0x7d0000, 0x10000}, {"log", 0x7e0000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the TL-WA850RE v2 */ { .id = "TLWA850REV2", .vendor = "", .support_list = "SupportList:\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:55530000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:00000000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:55534100}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:45550000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:4B520000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:42520000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:4A500000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:43410000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:41550000}\n" "{product_name:TL-WA850RE,product_ver:2.0.0,special_id:52550000}\n", .support_trail = '\x00', .soft_ver = NULL, /** 576KB were moved from file-system to os-image in comparison to the stock image */ .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x150000}, {"file-system", 0x170000, 0x240000}, {"partition-table", 0x3b0000, 0x02000}, {"default-mac", 0x3c0000, 0x00020}, {"pin", 0x3c0100, 0x00020}, {"product-info", 0x3c1000, 0x01000}, {"soft-version", 0x3c2000, 0x00100}, {"support-list", 0x3c3000, 0x01000}, {"profile", 0x3c4000, 0x08000}, {"user-config", 0x3d0000, 0x10000}, {"default-config", 0x3e0000, 0x10000}, {"radio", 0x3f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the TL-WA855RE v1 */ { .id = "TLWA855REV1", .vendor = "", .support_list = "SupportList:\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:00000000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:55530000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:45550000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:4B520000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:42520000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:4A500000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:43410000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:41550000}\n" "{product_name:TL-WA855RE,product_ver:1.0.0,special_id:52550000}\n", .support_trail = '\x00', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x150000}, {"file-system", 0x170000, 0x240000}, {"partition-table", 0x3b0000, 0x02000}, {"default-mac", 0x3c0000, 0x00020}, {"pin", 0x3c0100, 0x00020}, {"product-info", 0x3c1000, 0x01000}, {"soft-version", 0x3c2000, 0x00100}, {"support-list", 0x3c3000, 0x01000}, {"profile", 0x3c4000, 0x08000}, {"user-config", 0x3d0000, 0x10000}, {"default-config", 0x3e0000, 0x10000}, {"radio", 0x3f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the TL-WR1043 v5 */ { .id = "TLWR1043NV5", .vendor = "", .support_list = "SupportList:\n" "{product_name:TL-WR1043N,product_ver:5.0.0,special_id:45550000}\n" "{product_name:TL-WR1043N,product_ver:5.0.0,special_id:55530000}\n", .support_trail = '\x00', .soft_ver = "soft_ver:1.0.0\n", .partitions = { {"factory-boot", 0x00000, 0x20000}, {"fs-uboot", 0x20000, 0x20000}, {"os-image", 0x40000, 0x180000}, {"file-system", 0x1c0000, 0xd40000}, {"default-mac", 0xf00000, 0x00200}, {"pin", 0xf00200, 0x00200}, {"device-id", 0xf00400, 0x00100}, {"product-info", 0xf00500, 0x0fb00}, {"soft-version", 0xf10000, 0x01000}, {"extra-para", 0xf11000, 0x01000}, {"support-list", 0xf12000, 0x0a000}, {"profile", 0xf1c000, 0x04000}, {"default-config", 0xf20000, 0x10000}, {"user-config", 0xf30000, 0x40000}, {"qos-db", 0xf70000, 0x40000}, {"certificate", 0xfb0000, 0x10000}, {"partition-table", 0xfc0000, 0x10000}, {"log", 0xfd0000, 0x20000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the TL-WR1043 v4 */ { .id = "TLWR1043NDV4", .vendor = "", .support_list = "SupportList:\n" "{product_name:TL-WR1043ND,product_ver:4.0.0,special_id:45550000}\n", .support_trail = '\x00', .soft_ver = NULL, /** We use a bigger os-image partition than the stock images (and thus smaller file-system), as our kernel doesn't fit in the stock firmware's 1MB os-image. */ .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0xdb0000}, {"default-mac", 0xf50000, 0x00200}, {"pin", 0xf50200, 0x00200}, {"product-info", 0xf50400, 0x0fc00}, {"soft-version", 0xf60000, 0x0b000}, {"support-list", 0xf6b000, 0x04000}, {"profile", 0xf70000, 0x04000}, {"default-config", 0xf74000, 0x0b000}, {"user-config", 0xf80000, 0x40000}, {"partition-table", 0xfc0000, 0x10000}, {"log", 0xfd0000, 0x20000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the TL-WR902AC v1 */ { .id = "TL-WR902AC-V1", .vendor = "", .support_list = "SupportList:\n" "{product_name:TL-WR902AC,product_ver:1.0.0,special_id:45550000}\n" "{product_name:TL-WR902AC,product_ver:1.0.0,special_id:55530000}\n", .support_trail = '\x00', .soft_ver = NULL, /** 384KB were moved from file-system to os-image in comparison to the stock image */ .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0x5b0000}, {"default-mac", 0x750000, 0x00200}, {"pin", 0x750200, 0x00200}, {"product-info", 0x750400, 0x0fc00}, {"soft-version", 0x760000, 0x0b000}, {"support-list", 0x76b000, 0x04000}, {"profile", 0x770000, 0x04000}, {"default-config", 0x774000, 0x0b000}, {"user-config", 0x780000, 0x40000}, {"partition-table", 0x7c0000, 0x10000}, {"log", 0x7d0000, 0x20000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the TL-WR942N V1 */ { .id = "TLWR942NV1", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:TL-WR942N,product_ver:1.0.0,special_id:00000000}\r\n" "{product_name:TL-WR942N,product_ver:1.0.0,special_id:52550000}\r\n", .support_trail = '\x00', .soft_ver = NULL, .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0xca0000}, {"default-mac", 0xe40000, 0x00200}, {"pin", 0xe40200, 0x00200}, {"product-info", 0xe40400, 0x0fc00}, {"partition-table", 0xe50000, 0x10000}, {"soft-version", 0xe60000, 0x10000}, {"support-list", 0xe70000, 0x10000}, {"profile", 0xe80000, 0x10000}, {"default-config", 0xe90000, 0x10000}, {"user-config", 0xea0000, 0x40000}, {"qos-db", 0xee0000, 0x40000}, {"certificate", 0xf20000, 0x10000}, {"usb-config", 0xfb0000, 0x10000}, {"log", 0xfc0000, 0x20000}, {"radio-bk", 0xfe0000, 0x10000}, {"radio", 0xff0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system", }, /** Firmware layout for the RE350 v1 */ { .id = "RE350-V1", .vendor = "", .support_list = "SupportList:\n" "{product_name:RE350,product_ver:1.0.0,special_id:45550000}\n" "{product_name:RE350,product_ver:1.0.0,special_id:00000000}\n" "{product_name:RE350,product_ver:1.0.0,special_id:41550000}\n" "{product_name:RE350,product_ver:1.0.0,special_id:55530000}\n" "{product_name:RE350,product_ver:1.0.0,special_id:43410000}\n" "{product_name:RE350,product_ver:1.0.0,special_id:4b520000}\n" "{product_name:RE350,product_ver:1.0.0,special_id:4a500000}\n", .support_trail = '\x00', .soft_ver = NULL, /** The original os-image partition is too small, so we enlarge it to 1.75M */ .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x1c0000}, {"file-system", 0x1e0000, 0x420000}, {"partition-table", 0x600000, 0x02000}, {"default-mac", 0x610000, 0x00020}, {"pin", 0x610100, 0x00020}, {"product-info", 0x611100, 0x01000}, {"soft-version", 0x620000, 0x01000}, {"support-list", 0x621000, 0x01000}, {"profile", 0x622000, 0x08000}, {"user-config", 0x630000, 0x10000}, {"default-config", 0x640000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the RE355 */ { .id = "RE355", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:00000000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:55530000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:45550000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:4A500000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:43410000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:41550000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:4B520000}\r\n" "{product_name:RE355,product_ver:1.0.0,special_id:55534100}\r\n", .support_trail = '\x00', .soft_ver = NULL, /** The flash partition table for RE355; it is almost the same as the one used by the stock images, 576KB were moved from file-system to os-image. */ .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0x460000}, {"partition-table", 0x600000, 0x02000}, {"default-mac", 0x610000, 0x00020}, {"pin", 0x610100, 0x00020}, {"product-info", 0x611100, 0x01000}, {"soft-version", 0x620000, 0x01000}, {"support-list", 0x621000, 0x01000}, {"profile", 0x622000, 0x08000}, {"user-config", 0x630000, 0x10000}, {"default-config", 0x640000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, /** Firmware layout for the RE450 */ { .id = "RE450", .vendor = "", .support_list = "SupportList:\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:00000000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:55530000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:45550000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:4A500000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:43410000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:41550000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:4B520000}\r\n" "{product_name:RE450,product_ver:1.0.0,special_id:55534100}\r\n", .support_trail = '\x00', .soft_ver = NULL, /** The flash partition table for RE450; it is almost the same as the one used by the stock images, 576KB were moved from file-system to os-image. */ .partitions = { {"fs-uboot", 0x00000, 0x20000}, {"os-image", 0x20000, 0x180000}, {"file-system", 0x1a0000, 0x460000}, {"partition-table", 0x600000, 0x02000}, {"default-mac", 0x610000, 0x00020}, {"pin", 0x610100, 0x00020}, {"product-info", 0x611100, 0x01000}, {"soft-version", 0x620000, 0x01000}, {"support-list", 0x621000, 0x01000}, {"profile", 0x622000, 0x08000}, {"user-config", 0x630000, 0x10000}, {"default-config", 0x640000, 0x10000}, {"radio", 0x7f0000, 0x10000}, {NULL, 0, 0} }, .first_sysupgrade_partition = "os-image", .last_sysupgrade_partition = "file-system" }, {} }; #define error(_ret, _errno, _str, ...) \ do { \ fprintf(stderr, _str ": %s\n", ## __VA_ARGS__, \ strerror(_errno)); \ if (_ret) \ exit(_ret); \ } while (0) /** Stores a uint32 as big endian */ static inline void put32(uint8_t *buf, uint32_t val) { buf[0] = val >> 24; buf[1] = val >> 16; buf[2] = val >> 8; buf[3] = val; } /** Allocates a new image partition */ static struct image_partition_entry alloc_image_partition(const char *name, size_t len) { struct image_partition_entry entry = {name, len, malloc(len)}; if (!entry.data) error(1, errno, "malloc"); return entry; } /** Frees an image partition */ static void free_image_partition(struct image_partition_entry entry) { free(entry.data); } static time_t source_date_epoch = -1; static void set_source_date_epoch() { char *env = getenv("SOURCE_DATE_EPOCH"); char *endptr = env; errno = 0; if (env && *env) { source_date_epoch = strtoull(env, &endptr, 10); if (errno || (endptr && *endptr != '\0')) { fprintf(stderr, "Invalid SOURCE_DATE_EPOCH"); exit(1); } } } /** Generates the partition-table partition */ static struct image_partition_entry make_partition_table(const struct flash_partition_entry *p) { struct image_partition_entry entry = alloc_image_partition("partition-table", 0x800); char *s = (char *)entry.data, *end = (char *)(s+entry.size); *(s++) = 0x00; *(s++) = 0x04; *(s++) = 0x00; *(s++) = 0x00; size_t i; for (i = 0; p[i].name; i++) { size_t len = end-s; size_t w = snprintf(s, len, "partition %s base 0x%05x size 0x%05x\n", p[i].name, p[i].base, p[i].size); if (w > len-1) error(1, 0, "flash partition table overflow?"); s += w; } s++; memset(s, 0xff, end-s); return entry; } /** Generates a binary-coded decimal representation of an integer in the range [0, 99] */ static inline uint8_t bcd(uint8_t v) { return 0x10 * (v/10) + v%10; } /** Generates the soft-version partition */ static struct image_partition_entry make_soft_version(uint32_t rev) { struct image_partition_entry entry = alloc_image_partition("soft-version", sizeof(struct soft_version)); struct soft_version *s = (struct soft_version *)entry.data; time_t t; if (source_date_epoch != -1) t = source_date_epoch; else if (time(&t) == (time_t)(-1)) error(1, errno, "time"); struct tm *tm = localtime(&t); s->magic = htonl(0x0000000c); s->zero = 0; s->pad1 = 0xff; s->version_major = 0; s->version_minor = 0; s->version_patch = 0; s->year_hi = bcd((1900+tm->tm_year)/100); s->year_lo = bcd(tm->tm_year%100); s->month = bcd(tm->tm_mon+1); s->day = bcd(tm->tm_mday); s->rev = htonl(rev); s->pad2 = 0xff; return entry; } static struct image_partition_entry make_soft_version_from_string(const char *soft_ver) { /** String length _including_ the terminating zero byte */ uint32_t ver_len = strlen(soft_ver) + 1; /** Partition contains 64 bit header, the version string, and one additional null byte */ size_t partition_len = 2*sizeof(uint32_t) + ver_len + 1; struct image_partition_entry entry = alloc_image_partition("soft-version", partition_len); uint32_t *len = (uint32_t *)entry.data; len[0] = htonl(ver_len); len[1] = 0; memcpy(&len[2], soft_ver, ver_len); entry.data[partition_len - 1] = 0; return entry; } /** Generates the support-list partition */ static struct image_partition_entry make_support_list(const struct device_info *info) { size_t len = strlen(info->support_list); struct image_partition_entry entry = alloc_image_partition("support-list", len + 9); put32(entry.data, len); memset(entry.data+4, 0, 4); memcpy(entry.data+8, info->support_list, len); entry.data[len+8] = info->support_trail; return entry; } /** Creates a new image partition with an arbitrary name from a file */ static struct image_partition_entry read_file(const char *part_name, const char *filename, bool add_jffs2_eof) { struct stat statbuf; if (stat(filename, &statbuf) < 0) error(1, errno, "unable to stat file `%s'", filename); size_t len = statbuf.st_size; if (add_jffs2_eof) len = ALIGN(len, 0x10000) + sizeof(jffs2_eof_mark); struct image_partition_entry entry = alloc_image_partition(part_name, len); FILE *file = fopen(filename, "rb"); if (!file) error(1, errno, "unable to open file `%s'", filename); if (fread(entry.data, statbuf.st_size, 1, file) != 1) error(1, errno, "unable to read file `%s'", filename); if (add_jffs2_eof) { uint8_t *eof = entry.data + statbuf.st_size, *end = entry.data+entry.size; memset(eof, 0xff, end - eof - sizeof(jffs2_eof_mark)); memcpy(end - sizeof(jffs2_eof_mark), jffs2_eof_mark, sizeof(jffs2_eof_mark)); } fclose(file); return entry; } /** Creates a new image partition from arbitrary data */ static struct image_partition_entry put_data(const char *part_name, const char *datain, size_t len) { struct image_partition_entry entry = alloc_image_partition(part_name, len); memcpy(entry.data, datain, len); return entry; } /** Copies a list of image partitions into an image buffer and generates the image partition table while doing so Example image partition table: fwup-ptn partition-table base 0x00800 size 0x00800 fwup-ptn os-image base 0x01000 size 0x113b45 fwup-ptn file-system base 0x114b45 size 0x1d0004 fwup-ptn support-list base 0x2e4b49 size 0x000d1 Each line of the partition table is terminated with the bytes 09 0d 0a ("\t\r\n"), the end of the partition table is marked with a zero byte. The firmware image must contain at least the partition-table and support-list partitions to be accepted. There aren't any alignment constraints for the image partitions. The partition-table partition contains the actual flash layout; partitions from the image partition table are mapped to the corresponding flash partitions during the firmware upgrade. The support-list partition contains a list of devices supported by the firmware image. The base offsets in the firmware partition table are relative to the end of the vendor information block, so the partition-table partition will actually start at offset 0x1814 of the image. I think partition-table must be the first partition in the firmware image. */ static void put_partitions(uint8_t *buffer, const struct flash_partition_entry *flash_parts, const struct image_partition_entry *parts) { size_t i, j; char *image_pt = (char *)buffer, *end = image_pt + 0x800; size_t base = 0x800; for (i = 0; parts[i].name; i++) { for (j = 0; flash_parts[j].name; j++) { if (!strcmp(flash_parts[j].name, parts[i].name)) { if (parts[i].size > flash_parts[j].size) error(1, 0, "%s partition too big (more than %u bytes)", flash_parts[j].name, (unsigned)flash_parts[j].size); break; } } assert(flash_parts[j].name); memcpy(buffer + base, parts[i].data, parts[i].size); size_t len = end-image_pt; size_t w = snprintf(image_pt, len, "fwup-ptn %s base 0x%05x size 0x%05x\t\r\n", parts[i].name, (unsigned)base, (unsigned)parts[i].size); if (w > len-1) error(1, 0, "image partition table overflow?"); image_pt += w; base += parts[i].size; } } /** Generates and writes the image MD5 checksum */ static void put_md5(uint8_t *md5, uint8_t *buffer, unsigned int len) { MD5_CTX ctx; MD5_Init(&ctx); MD5_Update(&ctx, md5_salt, (unsigned int)sizeof(md5_salt)); MD5_Update(&ctx, buffer, len); MD5_Final(md5, &ctx); } /** Generates the firmware image in factory format Image format: Bytes (hex) Usage ----------- ----- 0000-0003 Image size (4 bytes, big endian) 0004-0013 MD5 hash (hash of a 16 byte salt and the image data starting with byte 0x14) 0014-0017 Vendor information length (without padding) (4 bytes, big endian) 0018-1013 Vendor information (4092 bytes, padded with 0xff; there seem to be older (VxWorks-based) TP-LINK devices which use a smaller vendor information block) 1014-1813 Image partition table (2048 bytes, padded with 0xff) 1814-xxxx Firmware partitions */ static void * generate_factory_image(const struct device_info *info, const struct image_partition_entry *parts, size_t *len) { *len = 0x1814; size_t i; for (i = 0; parts[i].name; i++) *len += parts[i].size; uint8_t *image = malloc(*len); if (!image) error(1, errno, "malloc"); memset(image, 0xff, *len); put32(image, *len); if (info->vendor) { size_t vendor_len = strlen(info->vendor); put32(image+0x14, vendor_len); memcpy(image+0x18, info->vendor, vendor_len); } put_partitions(image + 0x1014, info->partitions, parts); put_md5(image+0x04, image+0x14, *len-0x14); return image; } /** Generates the firmware image in sysupgrade format This makes some assumptions about the provided flash and image partition tables and should be generalized when TP-LINK starts building its safeloader into hardware with different flash layouts. */ static void * generate_sysupgrade_image(const struct device_info *info, const struct image_partition_entry *image_parts, size_t *len) { size_t i, j; size_t flash_first_partition_index = 0; size_t flash_last_partition_index = 0; const struct flash_partition_entry *flash_first_partition = NULL; const struct flash_partition_entry *flash_last_partition = NULL; const struct image_partition_entry *image_last_partition = NULL; /** Find first and last partitions */ for (i = 0; info->partitions[i].name; i++) { if (!strcmp(info->partitions[i].name, info->first_sysupgrade_partition)) { flash_first_partition = &info->partitions[i]; flash_first_partition_index = i; } else if (!strcmp(info->partitions[i].name, info->last_sysupgrade_partition)) { flash_last_partition = &info->partitions[i]; flash_last_partition_index = i; } } assert(flash_first_partition && flash_last_partition); assert(flash_first_partition_index < flash_last_partition_index); /** Find last partition from image to calculate needed size */ for (i = 0; image_parts[i].name; i++) { if (!strcmp(image_parts[i].name, info->last_sysupgrade_partition)) { image_last_partition = &image_parts[i]; break; } } assert(image_last_partition); *len = flash_last_partition->base - flash_first_partition->base + image_last_partition->size; uint8_t *image = malloc(*len); if (!image) error(1, errno, "malloc"); memset(image, 0xff, *len); for (i = flash_first_partition_index; i <= flash_last_partition_index; i++) { for (j = 0; image_parts[j].name; j++) { if (!strcmp(info->partitions[i].name, image_parts[j].name)) { if (image_parts[j].size > info->partitions[i].size) error(1, 0, "%s partition too big (more than %u bytes)", info->partitions[i].name, (unsigned)info->partitions[i].size); memcpy(image + info->partitions[i].base - flash_first_partition->base, image_parts[j].data, image_parts[j].size); break; } assert(image_parts[j].name); } } return image; } /** Generates an image according to a given layout and writes it to a file */ static void build_image(const char *output, const char *kernel_image, const char *rootfs_image, uint32_t rev, bool add_jffs2_eof, bool sysupgrade, const struct device_info *info) { struct image_partition_entry parts[7] = {}; parts[0] = make_partition_table(info->partitions); if (info->soft_ver) parts[1] = make_soft_version_from_string(info->soft_ver); else parts[1] = make_soft_version(rev); parts[2] = make_support_list(info); parts[3] = read_file("os-image", kernel_image, false); parts[4] = read_file("file-system", rootfs_image, add_jffs2_eof); /* Some devices need the extra-para partition to accept the firmware */ if (strcasecmp(info->id, "ARCHER-C25-V1") == 0 || strcasecmp(info->id, "ARCHER-C60-V2") == 0 || strcasecmp(info->id, "TLWR1043NV5") == 0) { const char mdat[11] = {0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}; parts[5] = put_data("extra-para", mdat, 11); } else if (strcasecmp(info->id, "ARCHER-C7-V4") == 0 || strcasecmp(info->id, "ARCHER-C7-V5") == 0) { const char mdat[11] = {0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0xca, 0x00, 0x01, 0x00, 0x00}; parts[5] = put_data("extra-para", mdat, 11); } size_t len; void *image; if (sysupgrade) image = generate_sysupgrade_image(info, parts, &len); else image = generate_factory_image(info, parts, &len); FILE *file = fopen(output, "wb"); if (!file) error(1, errno, "unable to open output file"); if (fwrite(image, len, 1, file) != 1) error(1, 0, "unable to write output file"); fclose(file); free(image); size_t i; for (i = 0; parts[i].name; i++) free_image_partition(parts[i]); } /** Usage output */ static void usage(const char *argv0) { fprintf(stderr, "Usage: %s [OPTIONS...]\n" "\n" "Options:\n" " -h show this help\n" "\n" "Create a new image:\n" " -B <board> create image for the board specified with <board>\n" " -k <file> read kernel image from the file <file>\n" " -r <file> read rootfs image from the file <file>\n" " -o <file> write output to the file <file>\n" " -V <rev> sets the revision number to <rev>\n" " -j add jffs2 end-of-filesystem markers\n" " -S create sysupgrade instead of factory image\n" "Extract an old image:\n" " -x <file> extract all oem firmware partition\n" " -d <dir> destination to extract the firmware partition\n" " -z <file> convert an oem firmware into a sysupgade file. Use -o for output file\n", argv0 ); }; static const struct device_info *find_board(const char *id) { struct device_info *board = NULL; for (board = boards; board->id != NULL; board++) if (strcasecmp(id, board->id) == 0) return board; return NULL; } static int add_flash_partition( struct flash_partition_entry *part_list, size_t max_entries, const char *name, unsigned long base, unsigned long size) { int ptr; /* check if the list has a free entry */ for (ptr = 0; ptr < max_entries; ptr++, part_list++) { if (part_list->name == NULL && part_list->base == 0 && part_list->size == 0) break; } if (ptr == max_entries) { error(1, 0, "No free flash part entry available."); } part_list->name = calloc(1, strlen(name) + 1); memcpy((char *)part_list->name, name, strlen(name)); part_list->base = base; part_list->size = size; return 0; } /** read the partition table into struct flash_partition_entry */ static int read_partition_table( FILE *file, long offset, struct flash_partition_entry *entries, size_t max_entries, int type) { char buf[2048]; char *ptr, *end; const char *parthdr = NULL; const char *fwuphdr = "fwup-ptn"; const char *flashhdr = "partition"; /* TODO: search for the partition table */ switch(type) { case 0: parthdr = fwuphdr; break; case 1: parthdr = flashhdr; break; default: error(1, 0, "Invalid partition table"); } if (fseek(file, offset, SEEK_SET) < 0) error(1, errno, "Can not seek in the firmware"); if (fread(buf, 1, 2048, file) < 0) error(1, errno, "Can not read fwup-ptn from the firmware"); buf[2047] = '\0'; /* look for the partition header */ if (memcmp(buf, parthdr, strlen(parthdr)) != 0) { fprintf(stderr, "DEBUG: can not find fwuphdr\n"); return 1; } ptr = buf; end = buf + sizeof(buf); while ((ptr + strlen(parthdr)) < end && memcmp(ptr, parthdr, strlen(parthdr)) == 0) { char *end_part; char *end_element; char name[32] = { 0 }; int name_len = 0; unsigned long base = 0; unsigned long size = 0; end_part = memchr(ptr, '\n', (end - ptr)); if (end_part == NULL) { /* in theory this should never happen, because a partition always ends with 0x09, 0x0D, 0x0A */ break; } for (int i = 0; i <= 4; i++) { if (end_part <= ptr) break; end_element = memchr(ptr, 0x20, (end_part - ptr)); if (end_element == NULL) { error(1, errno, "Ignoring the rest of the partition entries."); break; } switch (i) { /* partition header */ case 0: ptr = end_element + 1; continue; /* name */ case 1: name_len = (end_element - ptr) > 31 ? 31 : (end_element - ptr); strncpy(name, ptr, name_len); name[name_len] = '\0'; ptr = end_element + 1; continue; /* string "base" */ case 2: ptr = end_element + 1; continue; /* actual base */ case 3: base = strtoul(ptr, NULL, 16); ptr = end_element + 1; continue; /* string "size" */ case 4: ptr = end_element + 1; /* actual size. The last element doesn't have a sepeartor */ size = strtoul(ptr, NULL, 16); /* the part ends with 0x09, 0x0d, 0x0a */ ptr = end_part + 1; add_flash_partition(entries, max_entries, name, base, size); continue; } } } return 0; } static void write_partition( FILE *input_file, size_t firmware_offset, struct flash_partition_entry *entry, FILE *output_file) { char buf[4096]; size_t offset; fseek(input_file, entry->base + firmware_offset, SEEK_SET); for (offset = 0; sizeof(buf) + offset <= entry->size; offset += sizeof(buf)) { if (fread(buf, sizeof(buf), 1, input_file) < 0) error(1, errno, "Can not read partition from input_file"); if (fwrite(buf, sizeof(buf), 1, output_file) < 0) error(1, errno, "Can not write partition to output_file"); } /* write last chunk smaller than buffer */ if (offset < entry->size) { offset = entry->size - offset; if (fread(buf, offset, 1, input_file) < 0) error(1, errno, "Can not read partition from input_file"); if (fwrite(buf, offset, 1, output_file) < 0) error(1, errno, "Can not write partition to output_file"); } } static int extract_firmware_partition(FILE *input_file, size_t firmware_offset, struct flash_partition_entry *entry, const char *output_directory) { FILE *output_file; char output[PATH_MAX]; snprintf(output, PATH_MAX, "%s/%s", output_directory, entry->name); output_file = fopen(output, "wb+"); if (output_file == NULL) { error(1, errno, "Can not open output file %s", output); } write_partition(input_file, firmware_offset, entry, output_file); fclose(output_file); return 0; } /** extract all partitions from the firmware file */ static int extract_firmware(const char *input, const char *output_directory) { struct flash_partition_entry entries[16] = { 0 }; size_t max_entries = 16; size_t firmware_offset = 0x1014; FILE *input_file; struct stat statbuf; /* check input file */ if (stat(input, &statbuf)) { error(1, errno, "Can not read input firmware %s", input); } /* check if output directory exists */ if (stat(output_directory, &statbuf)) { error(1, errno, "Failed to stat output directory %s", output_directory); } if ((statbuf.st_mode & S_IFMT) != S_IFDIR) { error(1, errno, "Given output directory is not a directory %s", output_directory); } input_file = fopen(input, "rb"); if (read_partition_table(input_file, firmware_offset, entries, 16, 0) != 0) { error(1, 0, "Error can not read the partition table (fwup-ptn)"); } for (int i = 0; i < max_entries; i++) { if (entries[i].name == NULL && entries[i].base == 0 && entries[i].size == 0) continue; extract_firmware_partition(input_file, firmware_offset, &entries[i], output_directory); } return 0; } static struct flash_partition_entry *find_partition( struct flash_partition_entry *entries, size_t max_entries, const char *name, const char *error_msg) { for (int i = 0; i < max_entries; i++, entries++) { if (strcmp(entries->name, name) == 0) return entries; } error(1, 0, "%s", error_msg); return NULL; } static void write_ff(FILE *output_file, size_t size) { char buf[4096]; int offset; memset(buf, 0xff, sizeof(buf)); for (offset = 0; offset + sizeof(buf) < size ; offset += sizeof(buf)) { if (fwrite(buf, sizeof(buf), 1, output_file) < 0) error(1, errno, "Can not write 0xff to output_file"); } /* write last chunk smaller than buffer */ if (offset < size) { offset = size - offset; if (fwrite(buf, offset, 1, output_file) < 0) error(1, errno, "Can not write partition to output_file"); } } static void convert_firmware(const char *input, const char *output) { struct flash_partition_entry fwup[MAX_PARTITIONS] = { 0 }; struct flash_partition_entry flash[MAX_PARTITIONS] = { 0 }; struct flash_partition_entry *fwup_os_image = NULL, *fwup_file_system = NULL; struct flash_partition_entry *flash_os_image = NULL, *flash_file_system = NULL; struct flash_partition_entry *fwup_partition_table = NULL; size_t firmware_offset = 0x1014; FILE *input_file, *output_file; struct stat statbuf; /* check input file */ if (stat(input, &statbuf)) { error(1, errno, "Can not read input firmware %s", input); } input_file = fopen(input, "rb"); if (!input_file) error(1, 0, "Can not open input firmware %s", input); output_file = fopen(output, "wb"); if (!output_file) error(1, 0, "Can not open output firmware %s", output); if (read_partition_table(input_file, firmware_offset, fwup, MAX_PARTITIONS, 0) != 0) { error(1, 0, "Error can not read the partition table (fwup-ptn)"); } fwup_os_image = find_partition(fwup, MAX_PARTITIONS, "os-image", "Error can not find os-image partition (fwup)"); fwup_file_system = find_partition(fwup, MAX_PARTITIONS, "file-system", "Error can not find file-system partition (fwup)"); fwup_partition_table = find_partition(fwup, MAX_PARTITIONS, "partition-table", "Error can not find partition-table partition"); /* the flash partition table has a 0x00000004 magic haeder */ if (read_partition_table(input_file, firmware_offset + fwup_partition_table->base + 4, flash, MAX_PARTITIONS, 1) != 0) error(1, 0, "Error can not read the partition table (flash)"); flash_os_image = find_partition(flash, MAX_PARTITIONS, "os-image", "Error can not find os-image partition (flash)"); flash_file_system = find_partition(flash, MAX_PARTITIONS, "file-system", "Error can not find file-system partition (flash)"); /* write os_image to 0x0 */ write_partition(input_file, firmware_offset, fwup_os_image, output_file); write_ff(output_file, flash_os_image->size - fwup_os_image->size); /* write file-system behind os_image */ fseek(output_file, flash_file_system->base - flash_os_image->base, SEEK_SET); write_partition(input_file, firmware_offset, fwup_file_system, output_file); write_ff(output_file, flash_file_system->size - fwup_file_system->size); fclose(output_file); fclose(input_file); } int main(int argc, char *argv[]) { const char *board = NULL, *kernel_image = NULL, *rootfs_image = NULL, *output = NULL; const char *extract_image = NULL, *output_directory = NULL, *convert_image = NULL; bool add_jffs2_eof = false, sysupgrade = false; unsigned rev = 0; const struct device_info *info; set_source_date_epoch(); while (true) { int c; c = getopt(argc, argv, "B:k:r:o:V:jSh:x:d:z:"); if (c == -1) break; switch (c) { case 'B': board = optarg; break; case 'k': kernel_image = optarg; break; case 'r': rootfs_image = optarg; break; case 'o': output = optarg; break; case 'V': sscanf(optarg, "r%u", &rev); break; case 'j': add_jffs2_eof = true; break; case 'S': sysupgrade = true; break; case 'h': usage(argv[0]); return 0; case 'd': output_directory = optarg; break; case 'x': extract_image = optarg; break; case 'z': convert_image = optarg; break; default: usage(argv[0]); return 1; } } if (extract_image || output_directory) { if (!extract_image) error(1, 0, "No factory/oem image given via -x <file>. Output directory is only valid with -x"); if (!output_directory) error(1, 0, "Can not extract an image without output directory. Use -d <dir>"); extract_firmware(extract_image, output_directory); } else if (convert_image) { if (!output) error(1, 0, "Can not convert a factory/oem image into sysupgrade image without output file. Use -o <file>"); convert_firmware(convert_image, output); } else { if (!board) error(1, 0, "no board has been specified"); if (!kernel_image) error(1, 0, "no kernel image has been specified"); if (!rootfs_image) error(1, 0, "no rootfs image has been specified"); if (!output) error(1, 0, "no output filename has been specified"); info = find_board(board); if (info == NULL) error(1, 0, "unsupported board %s", board); build_image(output, kernel_image, rootfs_image, rev, add_jffs2_eof, sysupgrade, info); } return 0; }
the_stack_data/64199893.c
void foo(void); void foo(void) { char c = 1 == 2; }
the_stack_data/37638806.c
/** Sample program to read a N integer and insert in a ordered array until receive -1, or reach the maximum array size 100 numbers. @author Erick Santos **/ #include <stdio.h> // Used to get in/ out data // Find the position traversing the array from end to start // checking if current i poisition is greather than new number // if not, still traversing doing a shift with the current i index // to i+1 index, then when find the number less than new number // the posiiton is ready to receive the new number int insertOrdered(int arr[], int n, int newNum) { int pos = n; for (int i = n-1; i >= 0 && arr[i] > newNum; i--) { arr[i+1] = arr[i]; pos--; } arr[pos] = newNum; } void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("\n"); } int main() { // array used to store the n integer number int arr[101]; // used to count if reach maximum size and pass to // insert function the current index. int i = 0; // used to store temporary number inserted by user int value; // read the number from user input scanf("%d", &value); // loop until array reach the maximum index, or user insert the value -1 while (value != -1 && i < 100) { insertOrdered(arr, i, value); printArray(arr, ++i); // read next number from user input scanf("%d", &value); } return 0; }
the_stack_data/107952364.c
/* hw14_2 */ #include<stdio.h> #include<stdlib.h> int main(void) { int *ptr,*i; ptr=(int *)malloc(3*sizeof(int)); i=(int *)malloc(sizeof(int)); *ptr=12; *(ptr+1)=35; *(ptr+2)=140; for((*i)=0;(*i)<3;(*i)++) printf("*ptr+%d=%d\n",*i,*(ptr+(*i))); free(ptr); free(i); system("pause"); return 0; } /* *ptr+0=12 *ptr+1=35 Press any key to continue . . . */
the_stack_data/82095.c
void f() { g(1); h(0); i(1); } void g(double v) {} void h(const char* s) {} void i(double p);
the_stack_data/90762878.c
// KASAN: use-after-free Read in cbq_enqueue // https://syzkaller.appspot.com/bug?id=70d05c46d18c01bba7dcd332cf71100c66d1ae76 // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <sched.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> #include <linux/capability.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <linux/if_link.h> #include <linux/if_tun.h> #include <linux/in6.h> #include <linux/ip.h> #include <linux/neighbour.h> #include <linux/net.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/tcp.h> #include <linux/veth.h> unsigned long long procid; static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static struct { char* pos; int nesting; struct nlattr* nested[8]; char buf[1024]; } nlmsg; static void netlink_init(int typ, int flags, const void* data, int size) { memset(&nlmsg, 0, sizeof(nlmsg)); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg.buf; hdr->nlmsg_type = typ; hdr->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | flags; memcpy(hdr + 1, data, size); nlmsg.pos = (char*)(hdr + 1) + NLMSG_ALIGN(size); } static void netlink_attr(int typ, const void* data, int size) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_len = sizeof(*attr) + size; attr->nla_type = typ; memcpy(attr + 1, data, size); nlmsg.pos += NLMSG_ALIGN(attr->nla_len); } static void netlink_nest(int typ) { struct nlattr* attr = (struct nlattr*)nlmsg.pos; attr->nla_type = typ; nlmsg.pos += sizeof(*attr); nlmsg.nested[nlmsg.nesting++] = attr; } static void netlink_done(void) { struct nlattr* attr = nlmsg.nested[--nlmsg.nesting]; attr->nla_len = nlmsg.pos - (char*)attr; } static int netlink_send(int sock) { if (nlmsg.pos > nlmsg.buf + sizeof(nlmsg.buf) || nlmsg.nesting) exit(1); struct nlmsghdr* hdr = (struct nlmsghdr*)nlmsg.buf; hdr->nlmsg_len = nlmsg.pos - nlmsg.buf; struct sockaddr_nl addr; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; unsigned n = sendto(sock, nlmsg.buf, hdr->nlmsg_len, 0, (struct sockaddr*)&addr, sizeof(addr)); if (n != hdr->nlmsg_len) exit(1); n = recv(sock, nlmsg.buf, sizeof(nlmsg.buf), 0); if (n < sizeof(struct nlmsghdr) + sizeof(struct nlmsgerr)) exit(1); if (hdr->nlmsg_type != NLMSG_ERROR) exit(1); return -((struct nlmsgerr*)(hdr + 1))->error; } static void netlink_add_device_impl(const char* type, const char* name) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); netlink_init(RTM_NEWLINK, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); if (name) netlink_attr(IFLA_IFNAME, name, strlen(name)); netlink_nest(IFLA_LINKINFO); netlink_attr(IFLA_INFO_KIND, type, strlen(type)); } static void netlink_add_device(int sock, const char* type, const char* name) { netlink_add_device_impl(type, name); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_veth(int sock, const char* name, const char* peer) { netlink_add_device_impl("veth", name); netlink_nest(IFLA_INFO_DATA); netlink_nest(VETH_INFO_PEER); nlmsg.pos += sizeof(struct ifinfomsg); netlink_attr(IFLA_IFNAME, peer, strlen(peer)); netlink_done(); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_add_hsr(int sock, const char* name, const char* slave1, const char* slave2) { netlink_add_device_impl("hsr", name); netlink_nest(IFLA_INFO_DATA); int ifindex1 = if_nametoindex(slave1); netlink_attr(IFLA_HSR_SLAVE1, &ifindex1, sizeof(ifindex1)); int ifindex2 = if_nametoindex(slave2); netlink_attr(IFLA_HSR_SLAVE2, &ifindex2, sizeof(ifindex2)); netlink_done(); netlink_done(); int err = netlink_send(sock); (void)err; } static void netlink_device_change(int sock, const char* name, bool up, const char* master, const void* mac, int macsize) { struct ifinfomsg hdr; memset(&hdr, 0, sizeof(hdr)); if (up) hdr.ifi_flags = hdr.ifi_change = IFF_UP; netlink_init(RTM_NEWLINK, 0, &hdr, sizeof(hdr)); netlink_attr(IFLA_IFNAME, name, strlen(name)); if (master) { int ifindex = if_nametoindex(master); netlink_attr(IFLA_MASTER, &ifindex, sizeof(ifindex)); } if (macsize) netlink_attr(IFLA_ADDRESS, mac, macsize); int err = netlink_send(sock); (void)err; } static int netlink_add_addr(int sock, const char* dev, const void* addr, int addrsize) { struct ifaddrmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ifa_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ifa_prefixlen = addrsize == 4 ? 24 : 120; hdr.ifa_scope = RT_SCOPE_UNIVERSE; hdr.ifa_index = if_nametoindex(dev); netlink_init(RTM_NEWADDR, NLM_F_CREATE | NLM_F_REPLACE, &hdr, sizeof(hdr)); netlink_attr(IFA_LOCAL, addr, addrsize); netlink_attr(IFA_ADDRESS, addr, addrsize); return netlink_send(sock); } static void netlink_add_addr4(int sock, const char* dev, const char* addr) { struct in_addr in_addr; inet_pton(AF_INET, addr, &in_addr); int err = netlink_add_addr(sock, dev, &in_addr, sizeof(in_addr)); (void)err; } static void netlink_add_addr6(int sock, const char* dev, const char* addr) { struct in6_addr in6_addr; inet_pton(AF_INET6, addr, &in6_addr); int err = netlink_add_addr(sock, dev, &in6_addr, sizeof(in6_addr)); (void)err; } static void netlink_add_neigh(int sock, const char* name, const void* addr, int addrsize, const void* mac, int macsize) { struct ndmsg hdr; memset(&hdr, 0, sizeof(hdr)); hdr.ndm_family = addrsize == 4 ? AF_INET : AF_INET6; hdr.ndm_ifindex = if_nametoindex(name); hdr.ndm_state = NUD_PERMANENT; netlink_init(RTM_NEWNEIGH, NLM_F_EXCL | NLM_F_CREATE, &hdr, sizeof(hdr)); netlink_attr(NDA_DST, addr, addrsize); netlink_attr(NDA_LLADDR, mac, macsize); int err = netlink_send(sock); (void)err; } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC 0xaaaaaaaaaaaa #define REMOTE_MAC 0xaaaaaaaaaabb #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 240; if (dup2(tunfd, kTunFd) < 0) exit(1); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) exit(1); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) exit(1); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; char sysctl[64]; sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/accept_dad", TUN_IFACE); write_file(sysctl, "0"); sprintf(sysctl, "/proc/sys/net/ipv6/conf/%s/router_solicitations", TUN_IFACE); write_file(sysctl, "0"); int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); netlink_add_addr4(sock, TUN_IFACE, LOCAL_IPV4); netlink_add_addr6(sock, TUN_IFACE, LOCAL_IPV6); uint64_t macaddr = REMOTE_MAC; struct in_addr in_addr; inet_pton(AF_INET, REMOTE_IPV4, &in_addr); netlink_add_neigh(sock, TUN_IFACE, &in_addr, sizeof(in_addr), &macaddr, ETH_ALEN); struct in6_addr in6_addr; inet_pton(AF_INET6, REMOTE_IPV6, &in6_addr); netlink_add_neigh(sock, TUN_IFACE, &in6_addr, sizeof(in6_addr), &macaddr, ETH_ALEN); macaddr = LOCAL_MAC; netlink_device_change(sock, TUN_IFACE, true, 0, &macaddr, ETH_ALEN); close(sock); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02x" #define DEV_MAC 0x00aaaaaaaaaa static void initialize_netdevices(void) { char netdevsim[16]; sprintf(netdevsim, "netdevsim%d", (int)procid); struct { const char* type; const char* dev; } devtypes[] = { {"ip6gretap", "ip6gretap0"}, {"bridge", "bridge0"}, {"vcan", "vcan0"}, {"bond", "bond0"}, {"team", "team0"}, {"dummy", "dummy0"}, {"nlmon", "nlmon0"}, {"caif", "caif0"}, {"batadv", "batadv0"}, {"vxcan", "vxcan1"}, {"netdevsim", netdevsim}, {"veth", 0}, }; const char* devmasters[] = {"bridge", "bond", "team"}; struct { const char* name; int macsize; bool noipv6; } devices[] = { {"lo", ETH_ALEN}, {"sit0", 0}, {"bridge0", ETH_ALEN}, {"vcan0", 0, true}, {"tunl0", 0}, {"gre0", 0}, {"gretap0", ETH_ALEN}, {"ip_vti0", 0}, {"ip6_vti0", 0}, {"ip6tnl0", 0}, {"ip6gre0", 0}, {"ip6gretap0", ETH_ALEN}, {"erspan0", ETH_ALEN}, {"bond0", ETH_ALEN}, {"veth0", ETH_ALEN}, {"veth1", ETH_ALEN}, {"team0", ETH_ALEN}, {"veth0_to_bridge", ETH_ALEN}, {"veth1_to_bridge", ETH_ALEN}, {"veth0_to_bond", ETH_ALEN}, {"veth1_to_bond", ETH_ALEN}, {"veth0_to_team", ETH_ALEN}, {"veth1_to_team", ETH_ALEN}, {"veth0_to_hsr", ETH_ALEN}, {"veth1_to_hsr", ETH_ALEN}, {"hsr0", 0}, {"dummy0", ETH_ALEN}, {"nlmon0", 0}, {"vxcan1", 0, true}, {"caif0", ETH_ALEN}, {"batadv0", ETH_ALEN}, {netdevsim, ETH_ALEN}, }; int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) netlink_add_device(sock, devtypes[i].type, devtypes[i].dev); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { char master[32], slave0[32], veth0[32], slave1[32], veth1[32]; sprintf(slave0, "%s_slave_0", devmasters[i]); sprintf(veth0, "veth0_to_%s", devmasters[i]); netlink_add_veth(sock, slave0, veth0); sprintf(slave1, "%s_slave_1", devmasters[i]); sprintf(veth1, "veth1_to_%s", devmasters[i]); netlink_add_veth(sock, slave1, veth1); sprintf(master, "%s0", devmasters[i]); netlink_device_change(sock, slave0, false, master, 0, 0); netlink_device_change(sock, slave1, false, master, 0, 0); } netlink_device_change(sock, "bridge_slave_0", true, 0, 0, 0); netlink_device_change(sock, "bridge_slave_1", true, 0, 0, 0); netlink_add_veth(sock, "hsr_slave_0", "veth0_to_hsr"); netlink_add_veth(sock, "hsr_slave_1", "veth1_to_hsr"); netlink_add_hsr(sock, "hsr0", "hsr_slave_0", "hsr_slave_1"); netlink_device_change(sock, "hsr_slave_0", true, 0, 0, 0); netlink_device_change(sock, "hsr_slave_1", true, 0, 0, 0); for (i = 0; i < sizeof(devices) / (sizeof(devices[0])); i++) { char addr[32]; sprintf(addr, DEV_IPV4, i + 10); netlink_add_addr4(sock, devices[i].name, addr); if (!devices[i].noipv6) { sprintf(addr, DEV_IPV6, i + 10); netlink_add_addr6(sock, devices[i].name, addr); } uint64_t macaddr = DEV_MAC + ((i + 10ull) << 40); netlink_device_change(sock, devices[i].name, true, 0, &macaddr, devices[i].macsize); } close(sock); } static void initialize_netdevices_init(void) { int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (sock == -1) exit(1); struct { const char* type; int macsize; bool noipv6; bool noup; } devtypes[] = { {"nr", 7, true}, {"rose", 5, true, true}, }; unsigned i; for (i = 0; i < sizeof(devtypes) / sizeof(devtypes[0]); i++) { char dev[32], addr[32]; sprintf(dev, "%s%d", devtypes[i].type, (int)procid); sprintf(addr, "172.30.%d.%d", i, (int)procid + 1); netlink_add_addr4(sock, dev, addr); if (!devtypes[i].noipv6) { sprintf(addr, "fe88::%02x:%02x", i, (int)procid + 1); netlink_add_addr6(sock, dev, addr); } int macsize = devtypes[i].macsize; uint64_t macaddr = 0xbbbbbb + ((unsigned long long)i << (8 * (macsize - 2))) + (procid << (8 * (macsize - 1))); netlink_device_change(sock, dev, !devtypes[i].noup, 0, &macaddr, macsize); } close(sock); } static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static void drop_caps(void) { struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) exit(1); const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE); cap_data[0].effective &= ~drop; cap_data[0].permitted &= ~drop; cap_data[0].inheritable &= ~drop; if (syscall(SYS_capset, &cap_hdr, &cap_data)) exit(1); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); drop_caps(); initialize_netdevices_init(); if (unshare(CLONE_NEWNET)) { } initialize_tun(); initialize_netdevices(); loop(); exit(1); } uint64_t r[8] = { 0xffffffffffffffff, 0xffffffffffffffff, 0x0, 0x0, 0xffffffffffffffff, 0xffffffffffffffff, 0x0, 0xffffffffffffffff}; void loop(void) { intptr_t res = 0; res = syscall(__NR_socket, 0x10, 3, 0); if (res != -1) r[0] = res; res = syscall(__NR_socket, 0x11, 3, 0x300); if (res != -1) r[1] = res; memcpy((void*)0x20000000, "batadv0\000\000\000\000\000\000\000\000\000", 16); *(uint32_t*)0x20000010 = 0; res = syscall(__NR_ioctl, r[1], 0x8933, 0x20000000); if (res != -1) r[2] = *(uint32_t*)0x20000010; *(uint16_t*)0x20000640 = 0x11; *(uint16_t*)0x20000642 = htobe16(0); *(uint32_t*)0x20000644 = r[2]; *(uint16_t*)0x20000648 = 1; *(uint8_t*)0x2000064a = 0; *(uint8_t*)0x2000064b = 6; *(uint8_t*)0x2000064c = 1; *(uint8_t*)0x2000064d = 0x80; *(uint8_t*)0x2000064e = 0xc2; *(uint8_t*)0x2000064f = 0; *(uint8_t*)0x20000650 = 0; *(uint8_t*)0x20000651 = 0; *(uint8_t*)0x20000652 = 0; *(uint8_t*)0x20000653 = 0; syscall(__NR_bind, r[1], 0x20000640, 0x14); *(uint32_t*)0x20000140 = 0x14; res = syscall(__NR_getsockname, r[1], 0x20000100, 0x20000140); if (res != -1) r[3] = *(uint32_t*)0x20000104; *(uint64_t*)0x20000240 = 0; *(uint32_t*)0x20000248 = 0; *(uint64_t*)0x20000250 = 0x20000080; *(uint64_t*)0x20000080 = 0x20001800; *(uint32_t*)0x20001800 = 0x45c; *(uint16_t*)0x20001804 = 0x24; *(uint16_t*)0x20001806 = 0x507; *(uint32_t*)0x20001808 = 0; *(uint32_t*)0x2000180c = 0; *(uint8_t*)0x20001810 = 0; *(uint32_t*)0x20001814 = r[3]; *(uint16_t*)0x20001818 = 0; *(uint16_t*)0x2000181a = 0; *(uint16_t*)0x2000181c = -1; *(uint16_t*)0x2000181e = -1; *(uint16_t*)0x20001820 = 0; *(uint16_t*)0x20001822 = 0; *(uint16_t*)0x20001824 = 8; *(uint16_t*)0x20001826 = 1; memcpy((void*)0x20001828, "cbq\000", 4); *(uint16_t*)0x2000182c = 0x430; *(uint16_t*)0x2000182e = 2; *(uint16_t*)0x20001830 = 0x404; *(uint16_t*)0x20001832 = 6; *(uint32_t*)0x20001834 = 0; *(uint32_t*)0x20001838 = 0; *(uint32_t*)0x2000183c = 0; *(uint32_t*)0x20001840 = 0; *(uint32_t*)0x20001844 = 0; *(uint32_t*)0x20001848 = 0; *(uint32_t*)0x2000184c = 0; *(uint32_t*)0x20001850 = 0; *(uint32_t*)0x20001854 = 0; *(uint32_t*)0x20001858 = 0; *(uint32_t*)0x2000185c = 0; *(uint32_t*)0x20001860 = 0; *(uint32_t*)0x20001864 = 0; *(uint32_t*)0x20001868 = 0; *(uint32_t*)0x2000186c = 0; *(uint32_t*)0x20001870 = 0; *(uint32_t*)0x20001874 = 0; *(uint32_t*)0x20001878 = 0; *(uint32_t*)0x2000187c = 0; *(uint32_t*)0x20001880 = 0; *(uint32_t*)0x20001884 = 0; *(uint32_t*)0x20001888 = 0; *(uint32_t*)0x2000188c = 0; *(uint32_t*)0x20001890 = 0; *(uint32_t*)0x20001894 = 0; *(uint32_t*)0x20001898 = 0; *(uint32_t*)0x2000189c = 0; *(uint32_t*)0x200018a0 = 0; *(uint32_t*)0x200018a4 = 0; *(uint32_t*)0x200018a8 = 0; *(uint32_t*)0x200018ac = 0; *(uint32_t*)0x200018b0 = 0; *(uint32_t*)0x200018b4 = 0; *(uint32_t*)0x200018b8 = 0; *(uint32_t*)0x200018bc = 0; *(uint32_t*)0x200018c0 = 0; *(uint32_t*)0x200018c4 = 0; *(uint32_t*)0x200018c8 = 0; *(uint32_t*)0x200018cc = 0; *(uint32_t*)0x200018d0 = 0; *(uint32_t*)0x200018d4 = 0; *(uint32_t*)0x200018d8 = 0; *(uint32_t*)0x200018dc = 0; *(uint32_t*)0x200018e0 = 0; *(uint32_t*)0x200018e4 = 0; *(uint32_t*)0x200018e8 = 0; *(uint32_t*)0x200018ec = 0; *(uint32_t*)0x200018f0 = 0; *(uint32_t*)0x200018f4 = 0; *(uint32_t*)0x200018f8 = 0; *(uint32_t*)0x200018fc = 0; *(uint32_t*)0x20001900 = 0; *(uint32_t*)0x20001904 = 0; *(uint32_t*)0x20001908 = 0; *(uint32_t*)0x2000190c = 0; *(uint32_t*)0x20001910 = 0; *(uint32_t*)0x20001914 = 0; *(uint32_t*)0x20001918 = 0; *(uint32_t*)0x2000191c = 0; *(uint32_t*)0x20001920 = 0; *(uint32_t*)0x20001924 = 0; *(uint32_t*)0x20001928 = 0; *(uint32_t*)0x2000192c = 0; *(uint32_t*)0x20001930 = 0; *(uint32_t*)0x20001934 = 0; *(uint32_t*)0x20001938 = 0; *(uint32_t*)0x2000193c = 0; *(uint32_t*)0x20001940 = 0; *(uint32_t*)0x20001944 = 0; *(uint32_t*)0x20001948 = 0; *(uint32_t*)0x2000194c = 0; *(uint32_t*)0x20001950 = 0; *(uint32_t*)0x20001954 = 0; *(uint32_t*)0x20001958 = 0; *(uint32_t*)0x2000195c = 0; *(uint32_t*)0x20001960 = 0; *(uint32_t*)0x20001964 = 0; *(uint32_t*)0x20001968 = 0; *(uint32_t*)0x2000196c = 0; *(uint32_t*)0x20001970 = 0; *(uint32_t*)0x20001974 = 0; *(uint32_t*)0x20001978 = 0; *(uint32_t*)0x2000197c = 0; *(uint32_t*)0x20001980 = 0; *(uint32_t*)0x20001984 = 0; *(uint32_t*)0x20001988 = 0; *(uint32_t*)0x2000198c = 0; *(uint32_t*)0x20001990 = 0; *(uint32_t*)0x20001994 = 0; *(uint32_t*)0x20001998 = 0; *(uint32_t*)0x2000199c = 0; *(uint32_t*)0x200019a0 = 0; *(uint32_t*)0x200019a4 = 0; *(uint32_t*)0x200019a8 = 0; *(uint32_t*)0x200019ac = 0; *(uint32_t*)0x200019b0 = 0; *(uint32_t*)0x200019b4 = 0; *(uint32_t*)0x200019b8 = 0; *(uint32_t*)0x200019bc = 0; *(uint32_t*)0x200019c0 = 0; *(uint32_t*)0x200019c4 = 0; *(uint32_t*)0x200019c8 = 0; *(uint32_t*)0x200019cc = 0; *(uint32_t*)0x200019d0 = 0; *(uint32_t*)0x200019d4 = 0; *(uint32_t*)0x200019d8 = 0; *(uint32_t*)0x200019dc = 0; *(uint32_t*)0x200019e0 = 0; *(uint32_t*)0x200019e4 = 0; *(uint32_t*)0x200019e8 = 0; *(uint32_t*)0x200019ec = 0; *(uint32_t*)0x200019f0 = 0; *(uint32_t*)0x200019f4 = 0; *(uint32_t*)0x200019f8 = 0; *(uint32_t*)0x200019fc = 0; *(uint32_t*)0x20001a00 = 0; *(uint32_t*)0x20001a04 = 0; *(uint32_t*)0x20001a08 = 0; *(uint32_t*)0x20001a0c = 0; *(uint32_t*)0x20001a10 = 0; *(uint32_t*)0x20001a14 = 0; *(uint32_t*)0x20001a18 = 0; *(uint32_t*)0x20001a1c = 0; *(uint32_t*)0x20001a20 = 0; *(uint32_t*)0x20001a24 = 0; *(uint32_t*)0x20001a28 = 0; *(uint32_t*)0x20001a2c = 0; *(uint32_t*)0x20001a30 = 0; *(uint32_t*)0x20001a34 = 0; *(uint32_t*)0x20001a38 = 0; *(uint32_t*)0x20001a3c = 0; *(uint32_t*)0x20001a40 = 0; *(uint32_t*)0x20001a44 = 0; *(uint32_t*)0x20001a48 = 0; *(uint32_t*)0x20001a4c = 0; *(uint32_t*)0x20001a50 = 0; *(uint32_t*)0x20001a54 = 0; *(uint32_t*)0x20001a58 = 0; *(uint32_t*)0x20001a5c = 0; *(uint32_t*)0x20001a60 = 0; *(uint32_t*)0x20001a64 = 0; *(uint32_t*)0x20001a68 = 0; *(uint32_t*)0x20001a6c = 0; *(uint32_t*)0x20001a70 = 0; *(uint32_t*)0x20001a74 = 0; *(uint32_t*)0x20001a78 = 0; *(uint32_t*)0x20001a7c = 0; *(uint32_t*)0x20001a80 = 0; *(uint32_t*)0x20001a84 = 0; *(uint32_t*)0x20001a88 = 0; *(uint32_t*)0x20001a8c = 0; *(uint32_t*)0x20001a90 = 0; *(uint32_t*)0x20001a94 = 0; *(uint32_t*)0x20001a98 = 0; *(uint32_t*)0x20001a9c = 0; *(uint32_t*)0x20001aa0 = 0; *(uint32_t*)0x20001aa4 = 0; *(uint32_t*)0x20001aa8 = 0; *(uint32_t*)0x20001aac = 0; *(uint32_t*)0x20001ab0 = 0; *(uint32_t*)0x20001ab4 = 0; *(uint32_t*)0x20001ab8 = 0; *(uint32_t*)0x20001abc = 0; *(uint32_t*)0x20001ac0 = 0; *(uint32_t*)0x20001ac4 = 0; *(uint32_t*)0x20001ac8 = 0; *(uint32_t*)0x20001acc = 0; *(uint32_t*)0x20001ad0 = 0; *(uint32_t*)0x20001ad4 = 0; *(uint32_t*)0x20001ad8 = 0; *(uint32_t*)0x20001adc = 0; *(uint32_t*)0x20001ae0 = 0; *(uint32_t*)0x20001ae4 = 0; *(uint32_t*)0x20001ae8 = 0; *(uint32_t*)0x20001aec = 0; *(uint32_t*)0x20001af0 = 0; *(uint32_t*)0x20001af4 = 0; *(uint32_t*)0x20001af8 = 0; *(uint32_t*)0x20001afc = 0; *(uint32_t*)0x20001b00 = 0; *(uint32_t*)0x20001b04 = 0; *(uint32_t*)0x20001b08 = 0; *(uint32_t*)0x20001b0c = 0; *(uint32_t*)0x20001b10 = 0; *(uint32_t*)0x20001b14 = 0; *(uint32_t*)0x20001b18 = 0; *(uint32_t*)0x20001b1c = 0; *(uint32_t*)0x20001b20 = 0; *(uint32_t*)0x20001b24 = 0; *(uint32_t*)0x20001b28 = 0; *(uint32_t*)0x20001b2c = 0; *(uint32_t*)0x20001b30 = 0; *(uint32_t*)0x20001b34 = 0; *(uint32_t*)0x20001b38 = 0; *(uint32_t*)0x20001b3c = 0; *(uint32_t*)0x20001b40 = 0; *(uint32_t*)0x20001b44 = 0; *(uint32_t*)0x20001b48 = 0; *(uint32_t*)0x20001b4c = 0; *(uint32_t*)0x20001b50 = 0; *(uint32_t*)0x20001b54 = 0; *(uint32_t*)0x20001b58 = 0; *(uint32_t*)0x20001b5c = 0; *(uint32_t*)0x20001b60 = 0; *(uint32_t*)0x20001b64 = 0; *(uint32_t*)0x20001b68 = 0; *(uint32_t*)0x20001b6c = 0; *(uint32_t*)0x20001b70 = 0; *(uint32_t*)0x20001b74 = 0; *(uint32_t*)0x20001b78 = 0; *(uint32_t*)0x20001b7c = 0; *(uint32_t*)0x20001b80 = 0; *(uint32_t*)0x20001b84 = 0; *(uint32_t*)0x20001b88 = 0; *(uint32_t*)0x20001b8c = 0; *(uint32_t*)0x20001b90 = 0; *(uint32_t*)0x20001b94 = 0; *(uint32_t*)0x20001b98 = 0; *(uint32_t*)0x20001b9c = 0; *(uint32_t*)0x20001ba0 = 0; *(uint32_t*)0x20001ba4 = 0; *(uint32_t*)0x20001ba8 = 0; *(uint32_t*)0x20001bac = 0; *(uint32_t*)0x20001bb0 = 0; *(uint32_t*)0x20001bb4 = 0; *(uint32_t*)0x20001bb8 = 0; *(uint32_t*)0x20001bbc = 0; *(uint32_t*)0x20001bc0 = 0; *(uint32_t*)0x20001bc4 = 0; *(uint32_t*)0x20001bc8 = 0; *(uint32_t*)0x20001bcc = 0; *(uint32_t*)0x20001bd0 = 0; *(uint32_t*)0x20001bd4 = 0; *(uint32_t*)0x20001bd8 = 0; *(uint32_t*)0x20001bdc = 0; *(uint32_t*)0x20001be0 = 0; *(uint32_t*)0x20001be4 = 0; *(uint32_t*)0x20001be8 = 0; *(uint32_t*)0x20001bec = 0; *(uint32_t*)0x20001bf0 = 0; *(uint32_t*)0x20001bf4 = 0; *(uint32_t*)0x20001bf8 = 0; *(uint32_t*)0x20001bfc = 0; *(uint32_t*)0x20001c00 = 0; *(uint32_t*)0x20001c04 = 0; *(uint32_t*)0x20001c08 = 0; *(uint32_t*)0x20001c0c = 0; *(uint32_t*)0x20001c10 = 0; *(uint32_t*)0x20001c14 = 0; *(uint32_t*)0x20001c18 = 0; *(uint32_t*)0x20001c1c = 0; *(uint32_t*)0x20001c20 = 0; *(uint32_t*)0x20001c24 = 0; *(uint32_t*)0x20001c28 = 0; *(uint32_t*)0x20001c2c = 0; *(uint32_t*)0x20001c30 = 0; *(uint16_t*)0x20001c34 = 0x10; *(uint16_t*)0x20001c36 = 5; *(uint8_t*)0x20001c38 = 5; *(uint8_t*)0x20001c39 = 0; *(uint16_t*)0x20001c3a = 0; *(uint16_t*)0x20001c3c = 0; *(uint16_t*)0x20001c3e = 0; *(uint32_t*)0x20001c40 = 0x10000; *(uint16_t*)0x20001c44 = 0x18; *(uint16_t*)0x20001c46 = 1; *(uint8_t*)0x20001c48 = 0; *(uint8_t*)0x20001c49 = 0; *(uint8_t*)0x20001c4a = 0; *(uint8_t*)0x20001c4b = 0; *(uint32_t*)0x20001c4c = 0; *(uint32_t*)0x20001c50 = 0; *(uint32_t*)0x20001c54 = 0; *(uint32_t*)0x20001c58 = 0; *(uint64_t*)0x20000088 = 0x45c; *(uint64_t*)0x20000258 = 1; *(uint64_t*)0x20000260 = 0; *(uint64_t*)0x20000268 = 0; *(uint32_t*)0x20000270 = 0; syscall(__NR_sendmsg, r[0], 0x20000240, 0); res = syscall(__NR_socket, 0x10, 0x80002, 0); if (res != -1) r[4] = res; res = syscall(__NR_socket, 0x11, 2, 0x300); if (res != -1) r[5] = res; memcpy((void*)0x20000000, "batadv0\000\000\000\000\000\000\000\000\000", 16); *(uint32_t*)0x20000010 = 0; res = syscall(__NR_ioctl, r[5], 0x8933, 0x20000000); if (res != -1) r[6] = *(uint32_t*)0x20000010; *(uint16_t*)0x20000640 = 0x11; *(uint16_t*)0x20000642 = htobe16(0); *(uint32_t*)0x20000644 = r[6]; *(uint16_t*)0x20000648 = 1; *(uint8_t*)0x2000064a = 0; *(uint8_t*)0x2000064b = 6; *(uint8_t*)0x2000064c = 1; *(uint8_t*)0x2000064d = 0x80; *(uint8_t*)0x2000064e = 0xc2; *(uint8_t*)0x2000064f = 0; *(uint8_t*)0x20000650 = 0; *(uint8_t*)0x20000651 = 0; *(uint8_t*)0x20000652 = 0; *(uint8_t*)0x20000653 = 0; syscall(__NR_bind, r[5], 0x20000640, 0x14); *(uint32_t*)0x20000140 = 0x14; res = syscall(__NR_getsockname, r[5], 0x20000100, 0x20000140); if (res != -1) r[7] = *(uint32_t*)0x20000104; *(uint64_t*)0x20000240 = 0; *(uint32_t*)0x20000248 = 0; *(uint64_t*)0x20000250 = 0x200000c0; *(uint64_t*)0x200000c0 = 0x20000280; memcpy((void*)0x20000280, "\x48\x00\x00\x00\x28\x00\x07\x05\x00\x00\x00\x00" "\x00\x00\x00\x00\x02\x00\x00\x00", 20); *(uint32_t*)0x20000294 = r[7]; memcpy((void*)0x20000298, "\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00\x08\x00\x01\x00\x68" "\x74\x62\x00\x1c\x00\x02\x00\x18\x00\x02\x00\xb4\x85\xd4\x0c\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x64\x5a\x38" "\xd4\x71\x20\x4e\xaa\xbb\x54\xf7\x3b\x1f\xfe\x22\xa3\xb6\xf1\xc4\x75" "\x7e\xe7\x55\x26\xb6\xd2\xc3\xff\xbb\x06\x32\x59\x9c\x72\xfc\xf9\x4e" "\x5e\xbc\x20\xf8\xf3\xc0\x5c\xfb\xc8\x1f\x0a\x6a\x15\xa8\x1a\x3c\x91" "\x20\x34\x13\xfb\x9c\xf2\x85\xbb\x46\x63\xea\x0c\x9e\xb6\x7b\x45\x08" "\x39\x26\xf8\xff\xe6\x61\x70\x54\x19\x7f\x0a\xa5\x9a\x65\x39\x89\xff" "\xeb\xe7\x1a\xab\x0b\xa4\x07\x57\x5f\x4b\xf0\xf9\xf0\x0b\x8f\xaa\x86" "\x73\xb1\x28\xc1\x6d\xe0\x3d\x09\xa1\x46\x90\xcd\xee\x11\x4e\x57\xc5" "\x75\xf1\xac\x6b\x1d\xce\x0a\xe5\xb2\xba\xa8\xbe\xb7\x03\x73\x70\xcb" "\xd7\xf3\xc0\xdb\x8e\x41\x42\x05\xda\xab\x4b\xb3\xbc\x6a\x83\x4f\xb5" "\x5b\xfe\x98\x6c\x39\xef\x4b\x0e\xce\x4d\xe1\x16\xcd\x45\x68\xab\x18" "\x7b\xc7\x22\x7c\x89\xd1\xf3\x00\x59\x98\x97\x49\xed\xfa\x62\x73\xb0" "\x8c\x00\x00\x00\x00", 243); *(uint64_t*)0x200000c8 = 0x48; *(uint64_t*)0x20000258 = 1; *(uint64_t*)0x20000260 = 0; *(uint64_t*)0x20000268 = 0; *(uint32_t*)0x20000270 = 0; syscall(__NR_sendmsg, -1, 0x20000240, 0); syscall(__NR_sendmmsg, r[4], 0x20000140, 0x332, 0); } int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); do_sandbox_none(); return 0; }
the_stack_data/232954900.c
/* * Program to convert Fahrenheit to Celsius scale. * @Date 27-05-2021 */ #include <stdio.h> int main() { float celsius, fahrenheit; printf("Please Enter the temperature in Fahrenheit :"); scanf("%f", &fahrenheit); celsius = (fahrenheit - 32) * 5 / 9; printf("\nTemperature in Celsius = %.2f", celsius); return 0; }
the_stack_data/665769.c
#ifdef HMAC_MD5 #ifndef LINT static const char rcsid[] = "$Header: /proj/cvs/prod/DHCP/dst/hmac_link.c,v 1.1 2001-02-22 07:22:08 mellon Exp $"; #endif /* * Portions Copyright (c) 1995-1998 by Trusted Information Systems, Inc. * * Permission to use, copy modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND TRUSTED INFORMATION SYSTEMS * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * TRUSTED INFORMATION SYSTEMS BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THE SOFTWARE. */ /* * This file contains an implementation of the HMAC-MD5 algorithm. */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include <sys/param.h> #include <sys/time.h> #include <netinet/in.h> #include <sys/socket.h> #include "minires/minires.h" #include "arpa/nameser.h" #include "dst_internal.h" #ifdef USE_MD5 # include "md5.h" # ifndef _MD5_H_ # define _MD5_H_ 1 /* make sure we do not include rsaref md5.h file */ # endif #endif #define HMAC_LEN 64 #define HMAC_IPAD 0x36 #define HMAC_OPAD 0x5c #define MD5_LEN 16 typedef struct hmackey { u_char hk_ipad[64], hk_opad[64]; } HMAC_Key; /************************************************************************** * dst_hmac_md5_sign * Call HMAC signing functions to sign a block of data. * There are three steps to signing, INIT (initialize structures), * UPDATE (hash (more) data), FINAL (generate a signature). This * routine performs one or more of these steps. * Parameters * mode SIG_MODE_INIT, SIG_MODE_UPDATE and/or SIG_MODE_FINAL. * priv_key key to use for signing. * context the context to be used in this digest * data data to be signed. * len length in bytes of data. * signature location to store signature. * sig_len size of the signature location * returns * N Success on SIG_MODE_FINAL = returns signature length in bytes * 0 Success on SIG_MODE_INIT and UPDATE * <0 Failure */ static int dst_hmac_md5_sign(const int mode, DST_KEY *d_key, void **context, const u_char *data, const unsigned len, u_char *signature, const unsigned sig_len) { HMAC_Key *key; int sign_len = 0; MD5_CTX *ctx = NULL; if (mode & SIG_MODE_INIT) ctx = (MD5_CTX *) malloc(sizeof(*ctx)); else if (context) ctx = (MD5_CTX *) *context; if (ctx == NULL) return (-1); if (d_key == NULL || d_key->dk_KEY_struct == NULL) return (-1); key = (HMAC_Key *) d_key->dk_KEY_struct; if (mode & SIG_MODE_INIT) { MD5Init(ctx); MD5Update(ctx, key->hk_ipad, HMAC_LEN); } if ((mode & SIG_MODE_UPDATE) && (data && len > 0)) MD5Update(ctx, (const unsigned char *)data, len); if (mode & SIG_MODE_FINAL) { if (signature == NULL || sig_len < MD5_LEN) return (SIGN_FINAL_FAILURE); MD5Final(signature, ctx); /* perform outer MD5 */ MD5Init(ctx); MD5Update(ctx, key->hk_opad, HMAC_LEN); MD5Update(ctx, signature, MD5_LEN); MD5Final(signature, ctx); sign_len = MD5_LEN; SAFE_FREE(ctx); } else { if (context == NULL) return (-1); *context = (void *) ctx; } return (sign_len); } /************************************************************************** * dst_hmac_md5_verify() * Calls HMAC verification routines. There are three steps to * verification, INIT (initialize structures), UPDATE (hash (more) data), * FINAL (generate a signature). This routine performs one or more of * these steps. * Parameters * mode SIG_MODE_INIT, SIG_MODE_UPDATE and/or SIG_MODE_FINAL. * dkey key to use for verify. * data data signed. * len length in bytes of data. * signature signature. * sig_len length in bytes of signature. * returns * 0 Success * <0 Failure */ static int dst_hmac_md5_verify(const int mode, DST_KEY *d_key, void **context, const u_char *data, const unsigned len, const u_char *signature, const unsigned sig_len) { HMAC_Key *key; MD5_CTX *ctx = NULL; if (mode & SIG_MODE_INIT) ctx = (MD5_CTX *) malloc(sizeof(*ctx)); else if (context) ctx = (MD5_CTX *) *context; if (ctx == NULL) return (-1); if (d_key == NULL || d_key->dk_KEY_struct == NULL) return (-1); key = (HMAC_Key *) d_key->dk_KEY_struct; if (mode & SIG_MODE_INIT) { MD5Init(ctx); MD5Update(ctx, key->hk_ipad, HMAC_LEN); } if ((mode & SIG_MODE_UPDATE) && (data && len > 0)) MD5Update(ctx, (const unsigned char *)data, len); if (mode & SIG_MODE_FINAL) { u_char digest[MD5_LEN]; if (signature == NULL || key == NULL || sig_len != MD5_LEN) return (VERIFY_FINAL_FAILURE); MD5Final(digest, ctx); /* perform outer MD5 */ MD5Init(ctx); MD5Update(ctx, key->hk_opad, HMAC_LEN); MD5Update(ctx, digest, MD5_LEN); MD5Final(digest, ctx); SAFE_FREE(ctx); if (memcmp(digest, signature, MD5_LEN) != 0) return (VERIFY_FINAL_FAILURE); } else { if (context == NULL) return (-1); *context = (void *) ctx; } return (0); } /************************************************************************** * dst_buffer_to_hmac_md5 * Converts key from raw data to an HMAC Key * This function gets in a pointer to the data * Parameters * hkey the HMAC key to be filled in * key the key in raw format * keylen the length of the key * Return * 0 Success * <0 Failure */ static int dst_buffer_to_hmac_md5(DST_KEY *dkey, const u_char *key, const unsigned keylen) { int i; HMAC_Key *hkey = NULL; MD5_CTX ctx; unsigned local_keylen = keylen; if (dkey == NULL || key == NULL || keylen < 0) return (-1); if ((hkey = (HMAC_Key *) malloc(sizeof(HMAC_Key))) == NULL) return (-2); memset(hkey->hk_ipad, 0, sizeof(hkey->hk_ipad)); memset(hkey->hk_opad, 0, sizeof(hkey->hk_opad)); /* if key is longer than HMAC_LEN bytes reset it to key=MD5(key) */ if (keylen > HMAC_LEN) { u_char tk[MD5_LEN]; MD5Init(&ctx); MD5Update(&ctx, (const unsigned char *)key, keylen); MD5Final(tk, &ctx); memset((void *) &ctx, 0, sizeof(ctx)); key = tk; local_keylen = MD5_LEN; } /* start out by storing key in pads */ memcpy(hkey->hk_ipad, key, local_keylen); memcpy(hkey->hk_opad, key, local_keylen); /* XOR key with hk_ipad and opad values */ for (i = 0; i < HMAC_LEN; i++) { hkey->hk_ipad[i] ^= HMAC_IPAD; hkey->hk_opad[i] ^= HMAC_OPAD; } dkey->dk_key_size = local_keylen; dkey->dk_KEY_struct = (void *) hkey; return (1); } /************************************************************************** * dst_hmac_md5_key_to_file_format * Encodes an HMAC Key into the portable file format. * Parameters * hkey HMAC KEY structure * buff output buffer * buff_len size of output buffer * Return * 0 Failure - null input hkey * -1 Failure - not enough space in output area * N Success - Length of data returned in buff */ static int dst_hmac_md5_key_to_file_format(const DST_KEY *dkey, char *buff, const unsigned buff_len) { char *bp; int i; unsigned len, b_len, key_len; u_char key[HMAC_LEN]; HMAC_Key *hkey; if (dkey == NULL || dkey->dk_KEY_struct == NULL) return (0); if (buff == NULL || buff_len <= (int) strlen(key_file_fmt_str)) return (-1); /* no OR not enough space in output area */ hkey = (HMAC_Key *) dkey->dk_KEY_struct; memset(buff, 0, buff_len); /* just in case */ /* write file header */ sprintf(buff, key_file_fmt_str, KEY_FILE_FORMAT, KEY_HMAC_MD5, "HMAC"); bp = (char *) strchr(buff, '\0'); b_len = buff_len - (bp - buff); memset(key, 0, HMAC_LEN); for (i = 0; i < HMAC_LEN; i++) key[i] = hkey->hk_ipad[i] ^ HMAC_IPAD; for (i = HMAC_LEN - 1; i >= 0; i--) if (key[i] != 0) break; key_len = i + 1; strcat(bp, "Key: "); bp += strlen("Key: "); b_len = buff_len - (bp - buff); len = b64_ntop(key, key_len, bp, b_len); if (len < 0) return (-1); bp += len; *(bp++) = '\n'; *bp = '\0'; b_len = buff_len - (bp - buff); return (buff_len - b_len); } /************************************************************************** * dst_hmac_md5_key_from_file_format * Converts contents of a key file into an HMAC key. * Parameters * hkey structure to put key into * buff buffer containing the encoded key * buff_len the length of the buffer * Return * n >= 0 Foot print of the key converted * n < 0 Error in conversion */ static int dst_hmac_md5_key_from_file_format(DST_KEY *dkey, const char *buff, const unsigned buff_len) { const char *p = buff, *eol; u_char key[HMAC_LEN+1]; /* b64_pton needs more than 64 bytes do decode * it should probably be fixed rather than doing * this */ u_char *tmp; unsigned key_len, len; if (dkey == NULL) return (-2); if (buff == NULL) return (-1); memset(key, 0, sizeof(key)); if (!dst_s_verify_str(&p, "Key: ")) return (-3); eol = strchr(p, '\n'); if (eol == NULL) return (-4); len = eol - p; tmp = malloc(len + 2); memcpy(tmp, p, len); *(tmp + len) = 0x0; key_len = b64_pton((char *)tmp, key, HMAC_LEN+1); /* see above */ SAFE_FREE2(tmp, len + 2); if (dst_buffer_to_hmac_md5(dkey, key, key_len) < 0) { return (-6); } return (0); } /* * dst_hmac_md5_to_dns_key() * function to extract hmac key from DST_KEY structure * intput: * in_key: HMAC-MD5 key * output: * out_str: buffer to write ot * out_len: size of output buffer * returns: * number of bytes written to output buffer */ static int dst_hmac_md5_to_dns_key(const DST_KEY *in_key, u_char *out_str, const unsigned out_len) { HMAC_Key *hkey; int i; if (in_key == NULL || in_key->dk_KEY_struct == NULL || out_len <= in_key->dk_key_size || out_str == NULL) return (-1); hkey = (HMAC_Key *) in_key->dk_KEY_struct; for (i = 0; i < in_key->dk_key_size; i++) out_str[i] = hkey->hk_ipad[i] ^ HMAC_IPAD; return (i); } /************************************************************************** * dst_hmac_md5_compare_keys * Compare two keys for equality. * Return * 0 The keys are equal * NON-ZERO The keys are not equal */ static int dst_hmac_md5_compare_keys(const DST_KEY *key1, const DST_KEY *key2) { HMAC_Key *hkey1 = (HMAC_Key *) key1->dk_KEY_struct; HMAC_Key *hkey2 = (HMAC_Key *) key2->dk_KEY_struct; return memcmp(hkey1->hk_ipad, hkey2->hk_ipad, HMAC_LEN); } /************************************************************************** * dst_hmac_md5_free_key_structure * Frees all (none) dynamically allocated structures in hkey */ static void * dst_hmac_md5_free_key_structure(void *key) { HMAC_Key *hkey = key; SAFE_FREE(hkey); return (NULL); } /*************************************************************************** * dst_hmac_md5_generate_key * Creates a HMAC key of size size with a maximum size of 63 bytes * generating a HMAC key larger than 63 bytes makes no sense as that key * is digested before use. */ static int dst_hmac_md5_generate_key(DST_KEY *key, const int nothing) { u_char *buff; int n; unsigned size, len; if (key == NULL || key->dk_alg != KEY_HMAC_MD5) return (0); size = (key->dk_key_size + 7) / 8; /* convert to bytes */ if (size <= 0) return(0); len = size > 64 ? 64 : size; buff = malloc(len+8); n = dst_random(DST_RAND_SEMI, len, buff); n += dst_random(DST_RAND_KEY, len, buff); if (n <= len) { /* failed getting anything */ SAFE_FREE2(buff, len); return (-1); } n = dst_buffer_to_hmac_md5(key, buff, len); SAFE_FREE2(buff, len); if (n <= 0) return (n); return (1); } /* * dst_hmac_md5_init() Function to answer set up function pointers for HMAC * related functions */ int dst_hmac_md5_init() { if (dst_t_func[KEY_HMAC_MD5] != NULL) return (1); dst_t_func[KEY_HMAC_MD5] = malloc(sizeof(struct dst_func)); if (dst_t_func[KEY_HMAC_MD5] == NULL) return (0); memset(dst_t_func[KEY_HMAC_MD5], 0, sizeof(struct dst_func)); dst_t_func[KEY_HMAC_MD5]->sign = dst_hmac_md5_sign; dst_t_func[KEY_HMAC_MD5]->verify = dst_hmac_md5_verify; dst_t_func[KEY_HMAC_MD5]->compare = dst_hmac_md5_compare_keys; dst_t_func[KEY_HMAC_MD5]->generate = dst_hmac_md5_generate_key; dst_t_func[KEY_HMAC_MD5]->destroy = dst_hmac_md5_free_key_structure; dst_t_func[KEY_HMAC_MD5]->to_dns_key = dst_hmac_md5_to_dns_key; dst_t_func[KEY_HMAC_MD5]->from_dns_key = dst_buffer_to_hmac_md5; dst_t_func[KEY_HMAC_MD5]->to_file_fmt = dst_hmac_md5_key_to_file_format; dst_t_func[KEY_HMAC_MD5]->from_file_fmt = dst_hmac_md5_key_from_file_format; return (1); } #else int dst_hmac_md5_init(){ return (0); } #endif
the_stack_data/104827614.c
/* DES "desk calculator" * Phil Karn * January 1987 */ #include <stdio.h> #include <ctype.h> main() { char key[8],work[8]; char line[80]; int keyset = 0; if(desinit(0) == -1){ printf("DES initialization failed\n"); exit(1); } printf("Enter in hexadecimal:\nk <key>\np <plaintext>\nc <ciphertext>\n"); printf("s - standard DES mode\n"); printf("f - fast mode (no IP)\n"); for(;;){ gets(line); if(feof(stdin)) break; if(isupper(line[0])) line[0] = tolower(line[0]); switch(line[0]){ case 's': desdone(); desinit(0); if(keyset) setkey(key); break; case 'f': desdone(); desinit(1); if(keyset) setkey(key); break; case 'k': /* Set key */ get8(&line[1],key); setkey(key); keyset = 1; break; case 'c': /* Decrypt ciphertext */ if(!keyset){ printf("Enter key\n"); break; } get8(&line[1],work); dedes(work); printf("Plaintext: "); put8(work); printf("\n"); break; case 'p': /* Encrypt plaintext */ if(!keyset){ printf("Enter key\n"); break; } get8(&line[1],work); endes(work); printf("Ciphertext: "); put8(work); printf("\n"); break; default: printf("eh?\n"); break; } } } get8(buf,cp) char *buf; register char *cp; { int ikey[8],i; sscanf(buf,"%2x%2x%2x%2x%2x%2x%2x%2x",&ikey[0],&ikey[1],&ikey[2], &ikey[3],&ikey[4],&ikey[5],&ikey[6],&ikey[7]); for(i=0;i<8;i++) *cp++ = ikey[i]; } put8(cp) register char *cp; { int i; for(i=0;i<8;i++){ printf("%02x ",*cp++ & 0xff); } }
the_stack_data/45295.c
struct A{int a; int b;}; int test183(){ struct A; return 174;}
the_stack_data/29824403.c
// // Created by Rahul on 6/19/2019. // int power(int base,int n) { int p; for(p=1;n>0;--n) { p=p*base; } return p; }
the_stack_data/54825681.c
#include <stdio.h> int main() { while(1); return 0; }
the_stack_data/57951079.c
// RUN: %clam -m32 --crab-inter --crab-track=sing-mem --crab-dom=int --crab-check=assert --crab-sanity-checks --crab-heap-analysis=cs-sea-dsa-types "%s" 2>&1 | OutputCheck %s // CHECK: ^7 Number of total safe checks$ // CHECK: ^1 Number of total warning checks$ extern int int_nd(void); extern char* name_nd(void); extern void __CRAB_assume(int); extern void __CRAB_assert(int); typedef struct { int x; int y; } S1; #define N 20 S1 a[N]; int b[10]; void check(S1* s1, int *s2, int flag) { if (flag > 0) { __CRAB_assert(s1[4].x >= 0); __CRAB_assert(s1[4].x <= 1); __CRAB_assert(s2[5] >= 0); __CRAB_assert(s2[5] <= 1); } else { __CRAB_assert(s1[8].y >= 0); __CRAB_assert(s1[8].y <= 1); __CRAB_assert(s2[9] >= 0); __CRAB_assert(s2[9] <= 1); } } int main(){ int i; for(i=0;i<N;++i) { if (int_nd()) { a[i].x = 1; } } if (int_nd()) a[0].y = 1; if (int_nd()) a[1].y = 1; if (int_nd()) a[2].y = 1; if (int_nd()) a[3].y = 1; if (int_nd()) a[4].y = 1; if (int_nd()) a[5].y = 1; if (int_nd()) a[6].y = 1; if (int_nd()) a[7].y = 1; if (int_nd()) a[8].y = 1; if (int_nd()) a[9].y = 1; if (int_nd()) b[0] = 1; if (int_nd()) b[1] = 1; if (int_nd()) b[2] = 1; if (int_nd()) b[3] = 1; if (int_nd()) b[4] = 1; if (int_nd()) b[5] = 1; if (int_nd()) b[6] = 1; if (int_nd()) b[7] = 1; if (int_nd()) b[8] = 1; if (int_nd()) b[9] = 1; if (int_nd()) b[5] = 5; check(&a[0], &b[0], int_nd()); return 0; }
the_stack_data/3156.c
#include <stdio.h> int main() { int i, n; int t1 = 0, t2 = 1; int arr[100] = {0, 1}; int nextTerm = t1 + t2; printf("Enter the number of terms: "); scanf("%d", &n); for (i = 2; i <= n; ++i) { arr[i] = nextTerm; t1 = t2; t2 = nextTerm; nextTerm = t1 + t2; } int it; for(it = 0; it < n; it++) { if(arr[it] % 2 == 0) { printf("%d = even \n", arr[it]); } else { printf("%d = odd \n", arr[it]); } } return 0; }
the_stack_data/54824509.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2014-2019 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <unistd.h> static void after_sleep (void) { return; /* after sleep */ } int main (void) { sleep (3); after_sleep (); return 0; }
the_stack_data/1003102.c
#ifdef H5_LDOUBLE_TO_LONG_SPECIAL_TEST #include <string.h> #include <stdlib.h> int main(void) { long double ld = 20041683600089727.779961L; long ll; unsigned long ull; unsigned char s[16]; unsigned char s2[8]; int ret = 1; if(sizeof(long double) == 16 && sizeof(long) == 8) { /*make sure the long double type has 16 bytes in size and * 11 bits of exponent. If it is, *the bit sequence should be like below. It's not *a decent way to check but this info isn't available. */ memcpy(s, &ld, 16); if(s[0]==0x43 && s[1]==0x51 && s[2]==0xcc && s[3]==0xf3 && s[4]==0x85 && s[5]==0xeb && s[6]==0xc8 && s[7]==0xa0 && s[8]==0xbf && s[9]==0xcc && s[10]==0x2a && s[11]==0x3c) { /* Assign the hexadecimal value of long double type. */ s[0]=0x43; s[1]=0x51; s[2]=0xcc; s[3]=0xf3; s[4]=0x85; s[5]=0xeb; s[6]=0xc8; s[7]=0xa0; s[8]=0xbf; s[9]=0xcc; s[10]=0x2a; s[11]=0x3c; s[12]=0x3d; s[13]=0x85; s[14]=0x56; s[15]=0x20; memcpy(&ld, s, 16); ll = (long)ld; memcpy(s2, &ll, 8); /* The library's algorithm converts it to 0x 00 47 33 ce 17 af 22 82 * and gets wrong value 20041683600089730 on the IBM Power6 Linux. * But the IBM Power6 Linux converts it to 0x00 47 33 ce 17 af 22 7f * and gets the correct value 20041683600089727. It uses some special * algorithm. We're going to define the macro and skip the test until * we can figure out how they do it. */ if(s2[0]==0x00 && s2[1]==0x47 && s2[2]==0x33 && s2[3]==0xce && s2[4]==0x17 && s2[5]==0xaf && s2[6]==0x22 && s2[7]==0x7f) ret = 0; ull = (unsigned long)ld; memcpy(s2, &ull, 8); /* The unsigned long is the same as signed long. */ if(s2[0]==0x00 && s2[1]==0x47 && s2[2]==0x33 && s2[3]==0xce && s2[4]==0x17 && s2[5]==0xaf && s2[6]==0x22 && s2[7]==0x7f) ret = 0; } } done: exit(ret); } #endif #ifdef H5_LONG_TO_LDOUBLE_SPECIAL_TEST #include <string.h> #include <stdlib.h> int main(void) { long double ld; long ll; unsigned long ull; unsigned char s[16]; int flag=0, ret=1; /*Determine if long double has 16 byte in size, 11 bit exponent, and *the bias is 0x3ff */ if(sizeof(long double) == 16) { ld = 1.0L; memcpy(s, &ld, 16); if(s[0]==0x3f && s[1]==0xf0 && s[2]==0x00 && s[3]==0x00 && s[4]==0x00 && s[5]==0x00 && s[6]==0x00 && s[7]==0x00) flag = 1; } if(flag==1 && sizeof(long)==8) { ll = 0x003fffffffffffffL; ld = (long double)ll; memcpy(s, &ld, 16); /* The library converts the value to 0x434fffffffffffff8000000000000000. * In decimal it is 18014398509481982.000000, one value short of the original. * The IBM Power6 Linux converts it to 0x4350000000000000bff0000000000000. * The value is correct in decimal. It uses some special * algorithm. We're going to define the macro and skip the test until * we can figure out how they do it. */ if(s[0]==0x43 && s[1]==0x50 && s[2]==0x00 && s[3]==0x00 && s[4]==0x00 && s[5]==0x00 && s[6]==0x00 && s[7]==0x00 && s[8]==0xbf && s[9]==0xf0 && s[10]==0x00 && s[11]==0x00 && s[12]==0x00 && s[13]==0x00 && s[14]==0x00 && s[15]==0x00) ret = 0; } if(flag==1 && sizeof(unsigned long)==8) { ull = 0xffffffffffffffffUL; ld = (long double)ull; memcpy(s, &ld, 16); /* Use a different value from signed long to test. The problem is the same * for both long and unsigned long. The value is 18446744073709551615. * The library converts the value to 0x43effffffffffffffe000000000000000. * In decimal it's 18446744073709548544.000000, very different from the original. * The IBM Power6 Linux converts it to 0x43f0000000000000bff0000000000000. * The value is correct in decimal. It uses some special * algorithm. We're going to define the macro and skip the test until * we can figure out how they do it. */ if(s[0]==0x43 && s[1]==0xf0 && s[2]==0x00 && s[3]==0x00 && s[4]==0x00 && s[5]==0x00 && s[6]==0x00 && s[7]==0x00 && s[8]==0xbf && s[9]==0xf0 && s[10]==0x00 && s[11]==0x00 && s[12]==0x00 && s[13]==0x00 && s[14]==0x00 && s[15]==0x00) ret = 0; } done: exit(ret); } #endif #ifdef H5_LDOUBLE_TO_LLONG_ACCURATE_TEST #include <string.h> #include <stdlib.h> int main(void) { long double ld = 20041683600089727.779961L; long long ll; unsigned long long ull; unsigned char s[16]; int ret = 0; if(sizeof(long double) == 16) { /*make sure the long double type is the same as the failing type *which has 16 bytes in size and 11 bits of exponent. If it is, *the bit sequence should be like below. It's not *a decent way to check but this info isn't available. */ memcpy(s, &ld, 16); if(s[0]==0x43 && s[1]==0x51 && s[2]==0xcc && s[3]==0xf3 && s[4]==0x85 && s[5]==0xeb && s[6]==0xc8 && s[7]==0xa0 && s[8]==0xbf && s[9]==0xcc && s[10]==0x2a && s[11]==0x3c) { /*slightly adjust the bit sequence (s[8]=0xdf). The converted *values will go wild on Mac OS 10.4 and IRIX64 6.5.*/ s[0]=0x43; s[1]=0x51; s[2]=0xcc; s[3]=0xf3; s[4]=0x85; s[5]=0xeb; s[6]=0xc8; s[7]=0xa0; s[8]=0xdf; s[9]=0xcc; s[10]=0x2a; s[11]=0x3c; s[12]=0x3d; s[13]=0x85; s[14]=0x56; s[15]=0x20; memcpy(&ld, s, 16); ll = (long long)ld; ull = (unsigned long long)ld; if(ll != 20041683600089728 || ull != 20041683600089728) ret = 1; } } done: exit(ret); } #endif #ifdef H5_LLONG_TO_LDOUBLE_CORRECT_TEST #include <string.h> #include <stdlib.h> int main(void) { long double ld; long long ll; unsigned long long ull; unsigned char s[16]; int flag=0, ret=0; /*Determine if long double has 16 byte in size, 11 bit exponent, and *the bias is 0x3ff */ if(sizeof(long double) == 16) { ld = 1.0L; memcpy(s, &ld, 16); if(s[0]==0x3f && s[1]==0xf0 && s[2]==0x00 && s[3]==0x00 && s[4]==0x00 && s[5]==0x00 && s[6]==0x00 && s[7]==0x00) flag = 1; } if(flag==1 && sizeof(long long)==8) { ll = 0x01ffffffffffffffLL; ld = (long double)ll; memcpy(s, &ld, 16); /*Check if the bit sequence is as supposed to be*/ if(s[0]!=0x43 || s[1]!=0x7f || s[2]!=0xff || s[3]!=0xff || s[4]!=0xff || s[5]!=0xff || s[6]!=0xff || s[7]!=0xff || s[8]!=0xf0 || s[9]!=0x00 || s[10]!=0x00 || s[11]!=0x00) ret = 1; } if(flag==1 && sizeof(unsigned long long)==8) { ull = 0x01ffffffffffffffULL; ld = (long double)ull; memcpy(s, &ld, 16); if(s[0]!=0x43 || s[1]!=0x7f || s[2]!=0xff || s[3]!=0xff || s[4]!=0xff || s[5]!=0xff || s[6]!=0xff || s[7]!=0xff || s[8]!=0xf0 || s[9]!=0x00 || s[10]!=0x00 || s[11]!=0x00) ret = 1; } done: exit(ret); } #endif #ifdef H5_NO_ALIGNMENT_RESTRICTIONS_TEST #include <stdlib.h> #include <string.h> typedef struct { size_t len; void *p; } hvl_t; #ifdef FC_DUMMY_MAIN #ifndef FC_DUMMY_MAIN_EQ_F77 # ifdef __cplusplus extern "C" # endif int FC_DUMMY_MAIN() { return 1;} #endif #endif int main () { char *chp = "beefs"; char **chpp = malloc (2 * sizeof (char *)); char **chpp2; hvl_t vl = { 12345, (void *) chp }; hvl_t *vlp; hvl_t *vlp2; memcpy ((void *) ((char *) chpp + 1), &chp, sizeof (char *)); chpp2 = (char **) ((char *) chpp + 1); if (strcmp (*chpp2, chp)) { free (chpp); return 1; } free (chpp); vlp = malloc (2 * sizeof (hvl_t)); memcpy ((void *) ((char *) vlp + 1), &vl, sizeof (hvl_t)); vlp2 = (hvl_t *) ((char *) vlp + 1); if (vlp2->len != vl.len || vlp2->p != vl.p) { free (vlp); return 1; } free (vlp); ; return 0; } #endif
the_stack_data/72014002.c
#include <sys/types.h> #include <stdint.h> #include <stddef.h> #include "wctype.h" #undef KEY #if defined(__i386) # define KEY '_','_','i','3','8','6' #elif defined(__x86_64) # define KEY '_','_','x','8','6','_','6','4' #elif defined(__ppc__) # define KEY '_','_','p','p','c','_','_' #elif defined(__ppc64__) # define KEY '_','_','p','p','c','6','4','_','_' #endif #define SIZE (sizeof(wint_t)) char info_size[] = {'I', 'N', 'F', 'O', ':', 's','i','z','e','[', ('0' + ((SIZE / 10000)%10)), ('0' + ((SIZE / 1000)%10)), ('0' + ((SIZE / 100)%10)), ('0' + ((SIZE / 10)%10)), ('0' + (SIZE % 10)), ']', #ifdef KEY ' ','k','e','y','[', KEY, ']', #endif '\0'}; #ifdef __CLASSIC_C__ int main(argc, argv) int argc; char *argv[]; #else int main(int argc, char *argv[]) #endif { int require = 0; require += info_size[argc]; (void)argv; return require; }
the_stack_data/152668.c
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { int s1,s2,total; float average; printf("enter the marks:"); scanf("%d",&s1); printf("enter the marks:"); scanf("%d",&s2); total=s1+s2; average=total/2.0; printf("total marks =%d\n",total); printf("average marks = %.2f\n", average); return 0; }
the_stack_data/213276.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int max(int no1, int no2); int min(int no1, int no2); int multi (int no1,int no2); int main() { int no1, no2, maximum, minimum, multiply; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); maximum = max(no1, no2); minimum = min(no1, no2); multiply = multi(no1,no2); printf("\nMaximum = %d", maximum); printf("\nMinimum = %d", minimum); printf("\nMultiply = %d", multiply); return 0; } int max(int no1, int no2) { return (no1 > no2) ? no1 : no2; } int min(int no1, int no2) { return (no1 > no2) ? no2 : no1; } int multi(int no1, int no2) { return (no1* no2); }
the_stack_data/157951702.c
#include <stdio.h> int count = 1337 ; char *t= "Z\xc3"; int main(){ if(count != 1337) _exit(1); count++; char buf[48]; setvbuf(stdout,0,2,0); puts("Try your best :"); read(0,buf,128); return ; }
the_stack_data/156393662.c
#include <stdio.h> int main(void){ int i; int va[5]; int sum=0; for(i=0;i<5;i++){ printf("input va[%d]: ", i); scanf("%d", &va[i]); sum += va[i]; } printf("sum is :%d \n", sum); printf("avg is :%.2f \n", (double)sum/5); return 0; }
the_stack_data/94468.c
#include <errno.h> #include <time.h> #include "error.h" __attribute__ ((visibility ("default"))) int medusa_clock_realtime (struct timespec *timespec) { int rc; if (MEDUSA_IS_ERR_OR_NULL(timespec)) { return -EINVAL; } rc = clock_gettime(CLOCK_REALTIME, timespec); if (rc < 0) { return errno; } return 0; } __attribute__ ((visibility ("default"))) int medusa_clock_realtime_coarse (struct timespec *timespec) { int rc; if (MEDUSA_IS_ERR_OR_NULL(timespec)) { return -EINVAL; } rc = clock_gettime(CLOCK_REALTIME_COARSE, timespec); if (rc < 0) { return errno; } return 0; } __attribute__ ((visibility ("default"))) int medusa_clock_monotonic (struct timespec *timespec) { int rc; if (MEDUSA_IS_ERR_OR_NULL(timespec)) { return -EINVAL; } rc = clock_gettime(CLOCK_MONOTONIC, timespec); if (rc < 0) { return errno; } return 0; } __attribute__ ((visibility ("default"))) int medusa_clock_monotonic_raw (struct timespec *timespec) { int rc; if (MEDUSA_IS_ERR_OR_NULL(timespec)) { return -EINVAL; } rc = clock_gettime(CLOCK_MONOTONIC_RAW, timespec); if (rc < 0) { return errno; } return 0; } __attribute__ ((visibility ("default"))) int medusa_clock_monotonic_coarse (struct timespec *timespec) { int rc; if (MEDUSA_IS_ERR_OR_NULL(timespec)) { return -EINVAL; } rc = clock_gettime(CLOCK_MONOTONIC_COARSE, timespec); if (rc < 0) { return errno; } return 0; }
the_stack_data/150140900.c
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #define SERVER_PORT 6000 #define MAX_CLIENT 5 static char *readcontent(const char *filename) { char *fcontent = NULL; FILE *fp; fp = fopen(filename, "r+"); if(fp) { fseek(fp, 0, SEEK_END); long size = ftell(fp); fseek(fp, 0, SEEK_SET); rewind(fp); fcontent = (char*) malloc(sizeof(char) * size); fread(fcontent, 1, size, fp); fclose(fp); } return fcontent; } int main() { char buffer [256]; int server_socket , client_socket ; // server_address = explicit address of server //client_address = client information struct sockaddr_in server_address , client_address ; //filling the server address record server_address.sin_family=AF_INET; //IPv4 server_address.sin_port=htons(SERVER_PORT); server_address.sin_addr.s_addr=inet_addr("127.0.0.1"); //server_address.sin_addr.s_addr=INADDR_ANY; //making socket family = AF_INET, type = SOCK_STREAM , protocol = TCP server_socket = socket ( AF_INET , SOCK_STREAM , IPPROTO_TCP ); //binding socket to the server address bind ( server_socket , (struct sockaddr * ) & server_address ,sizeof(server_address) ); //listening to incoming requests from clients with backlog of 5 clients listen (server_socket , MAX_CLIENT); int clientsize = sizeof(client_address); if ((client_socket = accept ( server_socket , (struct sockaddr * ) & client_address , &(clientsize)))>=0) printf("A connection from a client is recieved\n"); else printf("Error in accepting the connection from the client\n "); char content[256]; while(1) { bzero(buffer,256); bzero(content,256); read(client_socket , buffer , 256) ; printf("(server)path = %s\n", buffer); //content = readcontent(buffer); FILE *fp; fp = fopen(buffer, "r+"); fread(content, 1, 255, fp); fclose(fp); printf("(server)File content :\n %s\n", content); printf("--------------------\n"); write(client_socket , content , 256); printf("-----------msg is sent to the client!-----------\n"); } return 0; }
the_stack_data/53668.c
#include <stdio.h> int main(){ int cat; printf("\n\n===========================Categoria de HabilitaΓ§Γ£o=============================\n"); printf("\nQual a categoria da sua Carteira?\n"); printf("1.Categoria A\n"); printf("2.Categoria B\n"); printf("3.Categoria C\n"); printf("4.Categoria D\n"); printf("5.Categoria E\n\n"); scanf("%d", &cat); switch(cat) { case 1: printf("VocΓͺ sΓ³ estΓ‘ habilitado a dirigir Motos!"); break; case 2: printf("VocΓͺ sΓ³ estΓ‘ habilitado a dirigir Carros!"); break; case 3: printf("VocΓͺ sΓ³ estΓ‘ habilitado a dirigir CaminhΓ΅es"); break; case 4: printf("VocΓͺ sΓ³ estΓ‘ habilitado a dirigir Γ”nibus"); break; case 5: printf("VocΓͺ sΓ³ estΓ‘ habilitado a dirigir Carretas"); break; } return 0; }
the_stack_data/26701283.c
/* *Β SimulationΒ ofΒ theΒ miserableΒ MOJIBAKEΒ filenamesΒ onΒ WindowsΒ operatingΒ system, Β *Β whenΒ ZIPΒ archiveΒ filesΒ createdΒ onΒ someΒ particularΒ OSΒ areΒ unzipped. Β *Β  Β *Β ThisΒ programΒ willΒ atΒ leastΒ TERRIBLYΒ andΒ IRREVERSIBLYΒ CORRUPTΒ theΒ namesΒ of *Β allΒ theΒ filesΒ inΒ theΒ currentΒ directory.Β MoreΒ badΒ thingsΒ couldΒ happenΒ asΒ well. Β *Β NEVERΒ RUNΒ THISΒ PROGURAMΒ unlessΒ aΒ TOTALΒ MESSΒ isΒ whatΒ youΒ reallyΒ want. Β * *Β PublicΒ Domain. */ #define _DEFAULT_SOURCE #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <iconv.h> int main(int argc, char** argv) { iconv_t ic; DIR *d; struct dirent *dir; struct stat sb; char bakebake[512]; char *inptr, *outptr; ssize_t inlength; size_t outlength; size_t convlength; ic = iconv_open("UTF-8", "WINDOWS-31J"); d = opendir("."); if (d != NULL) { while ((dir = readdir(d))) { stat(dir->d_name, &sb); if (S_ISREG(sb.st_mode)) { inptr = dir->d_name; outptr = bakebake; inlength = strlen(inptr); outlength = sizeof(bakebake) - 1; while (inlength > 0) { convlength = 2; iconv(ic, &inptr, &convlength, &outptr, &outlength); switch (convlength) { case 2: /* Invalid code. Emit U+30FB */ inptr += 2; inlength -= 2; if (outlength >= 3) { outlength -= 3; *outptr++ = 0xe3; *outptr++ = 0x83; *outptr++ = 0xbb; } break; case 1: /* Only the first octet was acceptable. */ /* Continue next conversion from the second octet. */ inlength -= 1; break; case 0: /* Both octets were accepted as Valid SJIS sequence. */ inlength -= 2; break; } } *outptr++ = '\0'; rename(dir->d_name, bakebake); printf("rename %s -> %s\n", dir->d_name, bakebake); } } } closedir(d); iconv_close(ic); return(0); }
the_stack_data/183095.c
/* ** A utility for printing all or part of an SQLite database file. */ #include <stdio.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if !defined(_MSC_VER) #include <unistd.h> #endif #include <stdlib.h> #include <string.h> #include "sqlite3.h" static int pagesize = 1024; /* Size of a database page */ static int db = -1; /* File descriptor for reading the DB */ static int mxPage = 0; /* Last page number */ static int perLine = 16; /* HEX elements to print per line */ typedef long long int i64; /* Datatype for 64-bit integers */ /* ** Convert the var-int format into i64. Return the number of bytes ** in the var-int. Write the var-int value into *pVal. */ static int decodeVarint(const unsigned char *z, i64 *pVal){ i64 v = 0; int i; for(i=0; i<8; i++){ v = (v<<7) + (z[i]&0x7f); if( (z[i]&0x80)==0 ){ *pVal = v; return i+1; } } v = (v<<8) + (z[i]&0xff); *pVal = v; return 9; } /* ** Extract a big-endian 32-bit integer */ static unsigned int decodeInt32(const unsigned char *z){ return (z[0]<<24) + (z[1]<<16) + (z[2]<<8) + z[3]; } /* Report an out-of-memory error and die. */ static void out_of_memory(void){ fprintf(stderr,"Out of memory...\n"); exit(1); } /* ** Read content from the file. ** ** Space to hold the content is obtained from malloc() and needs to be ** freed by the caller. */ static unsigned char *getContent(int ofst, int nByte){ unsigned char *aData; aData = malloc(nByte+32); if( aData==0 ) out_of_memory(); memset(aData, 0, nByte+32); lseek(db, ofst, SEEK_SET); read(db, aData, nByte); return aData; } /* ** Print a range of bytes as hex and as ascii. */ static unsigned char *print_byte_range( int ofst, /* First byte in the range of bytes to print */ int nByte, /* Number of bytes to print */ int printOfst /* Add this amount to the index on the left column */ ){ unsigned char *aData; int i, j; const char *zOfstFmt; if( ((printOfst+nByte)&~0xfff)==0 ){ zOfstFmt = " %03x: "; }else if( ((printOfst+nByte)&~0xffff)==0 ){ zOfstFmt = " %04x: "; }else if( ((printOfst+nByte)&~0xfffff)==0 ){ zOfstFmt = " %05x: "; }else if( ((printOfst+nByte)&~0xffffff)==0 ){ zOfstFmt = " %06x: "; }else{ zOfstFmt = " %08x: "; } aData = getContent(ofst, nByte); for(i=0; i<nByte; i += perLine){ fprintf(stdout, zOfstFmt, i+printOfst); for(j=0; j<perLine; j++){ if( i+j>nByte ){ fprintf(stdout, " "); }else{ fprintf(stdout,"%02x ", aData[i+j]); } } for(j=0; j<perLine; j++){ if( i+j>nByte ){ fprintf(stdout, " "); }else{ fprintf(stdout,"%c", isprint(aData[i+j]) ? aData[i+j] : '.'); } } fprintf(stdout,"\n"); } return aData; } /* ** Print an entire page of content as hex */ static void print_page(int iPg){ int iStart; unsigned char *aData; iStart = (iPg-1)*pagesize; fprintf(stdout, "Page %d: (offsets 0x%x..0x%x)\n", iPg, iStart, iStart+pagesize-1); aData = print_byte_range(iStart, pagesize, 0); free(aData); } /* Print a line of decode output showing a 4-byte integer. */ static void print_decode_line( unsigned char *aData, /* Content being decoded */ int ofst, int nByte, /* Start and size of decode */ const char *zMsg /* Message to append */ ){ int i, j; int val = aData[ofst]; char zBuf[100]; sprintf(zBuf, " %03x: %02x", ofst, aData[ofst]); i = strlen(zBuf); for(j=1; j<4; j++){ if( j>=nByte ){ sprintf(&zBuf[i], " "); }else{ sprintf(&zBuf[i], " %02x", aData[ofst+j]); val = val*256 + aData[ofst+j]; } i += strlen(&zBuf[i]); } sprintf(&zBuf[i], " %9d", val); printf("%s %s\n", zBuf, zMsg); } /* ** Decode the database header. */ static void print_db_header(void){ unsigned char *aData; aData = print_byte_range(0, 100, 0); printf("Decoded:\n"); print_decode_line(aData, 16, 2, "Database page size"); print_decode_line(aData, 18, 1, "File format write version"); print_decode_line(aData, 19, 1, "File format read version"); print_decode_line(aData, 20, 1, "Reserved space at end of page"); print_decode_line(aData, 24, 4, "File change counter"); print_decode_line(aData, 28, 4, "Size of database in pages"); print_decode_line(aData, 32, 4, "Page number of first freelist page"); print_decode_line(aData, 36, 4, "Number of freelist pages"); print_decode_line(aData, 40, 4, "Schema cookie"); print_decode_line(aData, 44, 4, "Schema format version"); print_decode_line(aData, 48, 4, "Default page cache size"); print_decode_line(aData, 52, 4, "Largest auto-vac root page"); print_decode_line(aData, 56, 4, "Text encoding"); print_decode_line(aData, 60, 4, "User version"); print_decode_line(aData, 64, 4, "Incremental-vacuum mode"); print_decode_line(aData, 68, 4, "Application ID"); print_decode_line(aData, 72, 4, "meta[8]"); print_decode_line(aData, 76, 4, "meta[9]"); print_decode_line(aData, 80, 4, "meta[10]"); print_decode_line(aData, 84, 4, "meta[11]"); print_decode_line(aData, 88, 4, "meta[12]"); print_decode_line(aData, 92, 4, "Change counter for version number"); print_decode_line(aData, 96, 4, "SQLite version number"); } /* ** Describe cell content. */ static int describeContent( unsigned char *a, /* Cell content */ int nLocal, /* Bytes in a[] */ char *zDesc /* Write description here */ ){ int nDesc = 0; int n, i, j; i64 x, v; const unsigned char *pData; const unsigned char *pLimit; char sep = ' '; pLimit = &a[nLocal]; n = decodeVarint(a, &x); pData = &a[x]; a += n; i = x - n; while( i>0 && pData<=pLimit ){ n = decodeVarint(a, &x); a += n; i -= n; nLocal -= n; zDesc[0] = sep; sep = ','; nDesc++; zDesc++; if( x==0 ){ sprintf(zDesc, "*"); /* NULL is a "*" */ }else if( x>=1 && x<=6 ){ v = (signed char)pData[0]; pData++; switch( x ){ case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; case 4: v = (v<<8) + pData[0]; pData++; case 3: v = (v<<8) + pData[0]; pData++; case 2: v = (v<<8) + pData[0]; pData++; } sprintf(zDesc, "%lld", v); }else if( x==7 ){ sprintf(zDesc, "real"); pData += 8; }else if( x==8 ){ sprintf(zDesc, "0"); }else if( x==9 ){ sprintf(zDesc, "1"); }else if( x>=12 ){ int size = (x-12)/2; if( (x&1)==0 ){ sprintf(zDesc, "blob(%d)", size); }else{ sprintf(zDesc, "txt(%d)", size); } pData += size; } j = strlen(zDesc); zDesc += j; nDesc += j; } return nDesc; } /* ** Compute the local payload size given the total payload size and ** the page size. */ static int localPayload(i64 nPayload, char cType){ int maxLocal; int minLocal; int surplus; int nLocal; if( cType==13 ){ /* Table leaf */ maxLocal = pagesize-35; minLocal = (pagesize-12)*32/255-23; }else{ maxLocal = (pagesize-12)*64/255-23; minLocal = (pagesize-12)*32/255-23; } if( nPayload>maxLocal ){ surplus = minLocal + (nPayload-minLocal)%(pagesize-4); if( surplus<=maxLocal ){ nLocal = surplus; }else{ nLocal = minLocal; } }else{ nLocal = nPayload; } return nLocal; } /* ** Create a description for a single cell. ** ** The return value is the local cell size. */ static int describeCell( unsigned char cType, /* Page type */ unsigned char *a, /* Cell content */ int showCellContent, /* Show cell content if true */ char **pzDesc /* Store description here */ ){ int i; int nDesc = 0; int n = 0; int leftChild; i64 nPayload; i64 rowid; int nLocal; static char zDesc[1000]; i = 0; if( cType<=5 ){ leftChild = ((a[0]*256 + a[1])*256 + a[2])*256 + a[3]; a += 4; n += 4; sprintf(zDesc, "lx: %d ", leftChild); nDesc = strlen(zDesc); } if( cType!=5 ){ i = decodeVarint(a, &nPayload); a += i; n += i; sprintf(&zDesc[nDesc], "n: %lld ", nPayload); nDesc += strlen(&zDesc[nDesc]); nLocal = localPayload(nPayload, cType); }else{ nPayload = nLocal = 0; } if( cType==5 || cType==13 ){ i = decodeVarint(a, &rowid); a += i; n += i; sprintf(&zDesc[nDesc], "r: %lld ", rowid); nDesc += strlen(&zDesc[nDesc]); } if( nLocal<nPayload ){ int ovfl; unsigned char *b = &a[nLocal]; ovfl = ((b[0]*256 + b[1])*256 + b[2])*256 + b[3]; sprintf(&zDesc[nDesc], "ov: %d ", ovfl); nDesc += strlen(&zDesc[nDesc]); n += 4; } if( showCellContent && cType!=5 ){ nDesc += describeContent(a, nLocal, &zDesc[nDesc-1]); } *pzDesc = zDesc; return nLocal+n; } /* ** Decode a btree page */ static void decode_btree_page( unsigned char *a, /* Page content */ int pgno, /* Page number */ int hdrSize, /* Size of the page header. 0 or 100 */ char *zArgs /* Flags to control formatting */ ){ const char *zType = "unknown"; int nCell; int i, j; int iCellPtr; int showCellContent = 0; int showMap = 0; char *zMap = 0; switch( a[0] ){ case 2: zType = "index interior node"; break; case 5: zType = "table interior node"; break; case 10: zType = "index leaf"; break; case 13: zType = "table leaf"; break; } while( zArgs[0] ){ switch( zArgs[0] ){ case 'c': showCellContent = 1; break; case 'm': showMap = 1; break; } zArgs++; } printf("Decode of btree page %d:\n", pgno); print_decode_line(a, 0, 1, zType); print_decode_line(a, 1, 2, "Offset to first freeblock"); print_decode_line(a, 3, 2, "Number of cells on this page"); nCell = a[3]*256 + a[4]; print_decode_line(a, 5, 2, "Offset to cell content area"); print_decode_line(a, 7, 1, "Fragmented byte count"); if( a[0]==2 || a[0]==5 ){ print_decode_line(a, 8, 4, "Right child"); iCellPtr = 12; }else{ iCellPtr = 8; } if( nCell>0 ){ printf(" key: lx=left-child n=payload-size r=rowid\n"); } if( showMap ){ zMap = malloc(pagesize); memset(zMap, '.', pagesize); memset(zMap, '1', hdrSize); memset(&zMap[hdrSize], 'H', iCellPtr); memset(&zMap[hdrSize+iCellPtr], 'P', 2*nCell); } for(i=0; i<nCell; i++){ int cofst = iCellPtr + i*2; char *zDesc; int n; cofst = a[cofst]*256 + a[cofst+1]; n = describeCell(a[0], &a[cofst-hdrSize], showCellContent, &zDesc); if( showMap ){ char zBuf[30]; memset(&zMap[cofst], '*', n); zMap[cofst] = '['; zMap[cofst+n-1] = ']'; sprintf(zBuf, "%d", i); j = strlen(zBuf); if( j<=n-2 ) memcpy(&zMap[cofst+1], zBuf, j); } printf(" %03x: cell[%d] %s\n", cofst, i, zDesc); } if( showMap ){ for(i=0; i<pagesize; i+=64){ printf(" %03x: %.64s\n", i, &zMap[i]); } free(zMap); } } /* ** Decode a freelist trunk page. */ static void decode_trunk_page( int pgno, /* The page number */ int pagesize, /* Size of each page */ int detail, /* Show leaf pages if true */ int recursive /* Follow the trunk change if true */ ){ int n, i; unsigned char *a; while( pgno>0 ){ a = getContent((pgno-1)*pagesize, pagesize); printf("Decode of freelist trunk page %d:\n", pgno); print_decode_line(a, 0, 4, "Next freelist trunk page"); print_decode_line(a, 4, 4, "Number of entries on this page"); if( detail ){ n = (int)decodeInt32(&a[4]); for(i=0; i<n; i++){ unsigned int x = decodeInt32(&a[8+4*i]); char zIdx[10]; sprintf(zIdx, "[%d]", i); printf(" %5s %7u", zIdx, x); if( i%5==4 ) printf("\n"); } if( i%5!=0 ) printf("\n"); } if( !recursive ){ pgno = 0; }else{ pgno = (int)decodeInt32(&a[0]); } free(a); } } /* ** A short text comment on the use of each page. */ static char **zPageUse; /* ** Add a comment on the use of a page. */ static void page_usage_msg(int pgno, const char *zFormat, ...){ va_list ap; char *zMsg; va_start(ap, zFormat); zMsg = sqlite3_vmprintf(zFormat, ap); va_end(ap); if( pgno<=0 || pgno>mxPage ){ printf("ERROR: page %d out of range 1..%d: %s\n", pgno, mxPage, zMsg); sqlite3_free(zMsg); return; } if( zPageUse[pgno]!=0 ){ printf("ERROR: page %d used multiple times:\n", pgno); printf("ERROR: previous: %s\n", zPageUse[pgno]); printf("ERROR: current: %s\n", zMsg); sqlite3_free(zPageUse[pgno]); } zPageUse[pgno] = zMsg; } /* ** Find overflow pages of a cell and describe their usage. */ static void page_usage_cell( unsigned char cType, /* Page type */ unsigned char *a, /* Cell content */ int pgno, /* page containing the cell */ int cellno /* Index of the cell on the page */ ){ int i; int n = 0; i64 nPayload; i64 rowid; int nLocal; i = 0; if( cType<=5 ){ a += 4; n += 4; } if( cType!=5 ){ i = decodeVarint(a, &nPayload); a += i; n += i; nLocal = localPayload(nPayload, cType); }else{ nPayload = nLocal = 0; } if( cType==5 || cType==13 ){ i = decodeVarint(a, &rowid); a += i; n += i; } if( nLocal<nPayload ){ int ovfl = decodeInt32(a+nLocal); int cnt = 0; while( ovfl && (cnt++)<mxPage ){ page_usage_msg(ovfl, "overflow %d from cell %d of page %d", cnt, cellno, pgno); a = getContent((ovfl-1)*pagesize, 4); ovfl = decodeInt32(a); free(a); } } } /* ** Describe the usages of a b-tree page */ static void page_usage_btree( int pgno, /* Page to describe */ int parent, /* Parent of this page. 0 for root pages */ int idx, /* Which child of the parent */ const char *zName /* Name of the table */ ){ unsigned char *a; const char *zType = "corrupt node"; int nCell; int i; int hdr = pgno==1 ? 100 : 0; if( pgno<=0 || pgno>mxPage ) return; a = getContent((pgno-1)*pagesize, pagesize); switch( a[hdr] ){ case 2: zType = "interior node of index"; break; case 5: zType = "interior node of table"; break; case 10: zType = "leaf of index"; break; case 13: zType = "leaf of table"; break; } if( parent ){ page_usage_msg(pgno, "%s [%s], child %d of page %d", zType, zName, idx, parent); }else{ page_usage_msg(pgno, "root %s [%s]", zType, zName); } nCell = a[hdr+3]*256 + a[hdr+4]; if( a[hdr]==2 || a[hdr]==5 ){ int cellstart = hdr+12; unsigned int child; for(i=0; i<nCell; i++){ int ofst; ofst = cellstart + i*2; ofst = a[ofst]*256 + a[ofst+1]; child = decodeInt32(a+ofst); page_usage_btree(child, pgno, i, zName); } child = decodeInt32(a+cellstart-4); page_usage_btree(child, pgno, i, zName); } if( a[hdr]==2 || a[hdr]==10 || a[hdr]==13 ){ int cellstart = hdr + 8 + 4*(a[hdr]<=5); for(i=0; i<nCell; i++){ int ofst; ofst = cellstart + i*2; ofst = a[ofst]*256 + a[ofst+1]; page_usage_cell(a[hdr], a+ofst, pgno, i); } } free(a); } /* ** Determine page usage by the freelist */ static void page_usage_freelist(int pgno){ unsigned char *a; int cnt = 0; int i; int n; int iNext; int parent = 1; while( pgno>0 && pgno<=mxPage && (cnt++)<mxPage ){ page_usage_msg(pgno, "freelist trunk #%d child of %d", cnt, parent); a = getContent((pgno-1)*pagesize, pagesize); iNext = decodeInt32(a); n = decodeInt32(a+4); for(i=0; i<n; i++){ int child = decodeInt32(a + (i*4+8)); page_usage_msg(child, "freelist leaf, child %d of trunk page %d", i, pgno); } free(a); parent = pgno; pgno = iNext; } } /* ** Determine pages used as PTRMAP pages */ static void page_usage_ptrmap(unsigned char *a){ if( a[55] ){ int usable = pagesize - a[20]; int pgno = 2; int perPage = usable/5; while( pgno<=mxPage ){ page_usage_msg(pgno, "PTRMAP page covering %d..%d", pgno+1, pgno+perPage); pgno += perPage + 1; } } } /* ** Try to figure out how every page in the database file is being used. */ static void page_usage_report(const char *zDbName){ int i, j; int rc; sqlite3 *db; sqlite3_stmt *pStmt; unsigned char *a; char zQuery[200]; /* Avoid the pathological case */ if( mxPage<1 ){ printf("empty database\n"); return; } /* Open the database file */ rc = sqlite3_open(zDbName, &db); if( rc ){ printf("cannot open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return; } /* Set up global variables zPageUse[] and mxPage to record page ** usages */ zPageUse = sqlite3_malloc( sizeof(zPageUse[0])*(mxPage+1) ); if( zPageUse==0 ) out_of_memory(); memset(zPageUse, 0, sizeof(zPageUse[0])*(mxPage+1)); /* Discover the usage of each page */ a = getContent(0, 100); page_usage_freelist(decodeInt32(a+32)); page_usage_ptrmap(a); free(a); page_usage_btree(1, 0, 0, "sqlite_master"); sqlite3_exec(db, "PRAGMA writable_schema=ON", 0, 0, 0); for(j=0; j<2; j++){ sqlite3_snprintf(sizeof(zQuery), zQuery, "SELECT type, name, rootpage FROM SQLITE_MASTER WHERE rootpage" " ORDER BY rowid %s", j?"DESC":""); rc = sqlite3_prepare_v2(db, zQuery, -1, &pStmt, 0); if( rc==SQLITE_OK ){ while( sqlite3_step(pStmt)==SQLITE_ROW ){ int pgno = sqlite3_column_int(pStmt, 2); page_usage_btree(pgno, 0, 0, (const char*)sqlite3_column_text(pStmt,1)); } }else{ printf("ERROR: cannot query database: %s\n", sqlite3_errmsg(db)); } rc = sqlite3_finalize(pStmt); if( rc==SQLITE_OK ) break; } sqlite3_close(db); /* Print the report and free memory used */ for(i=1; i<=mxPage; i++){ printf("%5d: %s\n", i, zPageUse[i] ? zPageUse[i] : "???"); sqlite3_free(zPageUse[i]); } sqlite3_free(zPageUse); zPageUse = 0; } /* ** Try to figure out how every page in the database file is being used. */ static void ptrmap_coverage_report(const char *zDbName){ unsigned int pgno; unsigned char *aHdr; unsigned char *a; int usable; int perPage; unsigned int i; /* Avoid the pathological case */ if( mxPage<1 ){ printf("empty database\n"); return; } /* Make sure PTRMAPs are used in this database */ aHdr = getContent(0, 100); if( aHdr[55]==0 ){ printf("database does not use PTRMAP pages\n"); return; } usable = pagesize - aHdr[20]; perPage = usable/5; free(aHdr); printf("%5d: root of sqlite_master\n", 1); for(pgno=2; pgno<=mxPage; pgno += perPage+1){ printf("%5d: PTRMAP page covering %d..%d\n", pgno, pgno+1, pgno+perPage); a = getContent((pgno-1)*pagesize, usable); for(i=0; i+5<=usable && pgno+1+i/5<=mxPage; i+=5){ const char *zType = "???"; unsigned int iFrom = decodeInt32(&a[i+1]); switch( a[i] ){ case 1: zType = "b-tree root page"; break; case 2: zType = "freelist page"; break; case 3: zType = "first page of overflow"; break; case 4: zType = "later page of overflow"; break; case 5: zType = "b-tree non-root page"; break; } printf("%5d: %s, parent=%u\n", pgno+1+i/5, zType, iFrom); } free(a); } } /* ** Print a usage comment */ static void usage(const char *argv0){ fprintf(stderr, "Usage %s FILENAME ?args...?\n\n", argv0); fprintf(stderr, "args:\n" " dbheader Show database header\n" " pgidx Index of how each page is used\n" " ptrmap Show all PTRMAP page content\n" " NNN..MMM Show hex of pages NNN through MMM\n" " NNN..end Show hex of pages NNN through end of file\n" " NNNb Decode btree page NNN\n" " NNNbc Decode btree page NNN and show content\n" " NNNbm Decode btree page NNN and show a layout map\n" " NNNt Decode freelist trunk page NNN\n" " NNNtd Show leaf freelist pages on the decode\n" " NNNtr Recurisvely decode freelist starting at NNN\n" ); } int main(int argc, char **argv){ struct stat sbuf; unsigned char zPgSz[2]; if( argc<2 ){ usage(argv[0]); exit(1); } db = open(argv[1], O_RDONLY); if( db<0 ){ fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]); exit(1); } zPgSz[0] = 0; zPgSz[1] = 0; lseek(db, 16, SEEK_SET); read(db, zPgSz, 2); pagesize = zPgSz[0]*256 + zPgSz[1]*65536; if( pagesize==0 ) pagesize = 1024; printf("Pagesize: %d\n", pagesize); fstat(db, &sbuf); mxPage = sbuf.st_size/pagesize; printf("Available pages: 1..%d\n", mxPage); if( argc==2 ){ int i; for(i=1; i<=mxPage; i++) print_page(i); }else{ int i; for(i=2; i<argc; i++){ int iStart, iEnd; char *zLeft; if( strcmp(argv[i], "dbheader")==0 ){ print_db_header(); continue; } if( strcmp(argv[i], "pgidx")==0 ){ page_usage_report(argv[1]); continue; } if( strcmp(argv[i], "ptrmap")==0 ){ ptrmap_coverage_report(argv[1]); continue; } if( strcmp(argv[i], "help")==0 ){ usage(argv[0]); continue; } if( !isdigit(argv[i][0]) ){ fprintf(stderr, "%s: unknown option: [%s]\n", argv[0], argv[i]); continue; } iStart = strtol(argv[i], &zLeft, 0); if( zLeft && strcmp(zLeft,"..end")==0 ){ iEnd = mxPage; }else if( zLeft && zLeft[0]=='.' && zLeft[1]=='.' ){ iEnd = strtol(&zLeft[2], 0, 0); }else if( zLeft && zLeft[0]=='b' ){ int ofst, nByte, hdrSize; unsigned char *a; if( iStart==1 ){ ofst = hdrSize = 100; nByte = pagesize-100; }else{ hdrSize = 0; ofst = (iStart-1)*pagesize; nByte = pagesize; } a = getContent(ofst, nByte); decode_btree_page(a, iStart, hdrSize, &zLeft[1]); free(a); continue; }else if( zLeft && zLeft[0]=='t' ){ int detail = 0; int recursive = 0; int i; for(i=1; zLeft[i]; i++){ if( zLeft[i]=='r' ) recursive = 1; if( zLeft[i]=='d' ) detail = 1; } decode_trunk_page(iStart, pagesize, detail, recursive); continue; }else{ iEnd = iStart; } if( iStart<1 || iEnd<iStart || iEnd>mxPage ){ fprintf(stderr, "Page argument should be LOWER?..UPPER?. Range 1 to %d\n", mxPage); exit(1); } while( iStart<=iEnd ){ print_page(iStart); iStart++; } } } close(db); return 0; }
the_stack_data/61076562.c
#define _GNU_SOURCE // What we do here (using RTLD_NEXT) is not // standard-compliant #include <dlfcn.h> #include <sys/syscall.h> #include <syslog.h> #include <unistd.h> static unsigned long (*real_compressXML)(unsigned short port, unsigned char *xmlBuf, unsigned long xmlBufLen, unsigned char *exiBuf, unsigned long exiBufLen, unsigned long bitOffset) = NULL; static unsigned long (*real_decompressEXI)(unsigned short port, unsigned char *exiBuf, unsigned long exiBufLen, unsigned char *xmlBuf, unsigned long xmlBufLen, unsigned long bitOffset) = NULL; static const char *(*real_lsdlconv_getVersion)(void) = NULL; typedef enum { direction_send, direction_receive, } direction_t; static void reportXML(const direction_t direction, unsigned short port, unsigned char *xmlBuf, unsigned long xmlLen, unsigned long exiLen) { syslog(LOG_INFO, "%s %.*s (thread_id=%lu;port=%u;xml_len=%lu;exi_len=%lu)", direction == direction_send ? "-->" : "<--", (int)xmlLen, xmlBuf, syscall(__NR_gettid), port, xmlLen, exiLen); } unsigned long compressXML(unsigned short port, unsigned char *xmlBuf, unsigned long xmlBufLen, unsigned char *exiBuf, unsigned long exiBufLen, unsigned long bitOffset) { if (!real_compressXML) { real_compressXML = dlsym(RTLD_NEXT, "compressXML"); } if (real_compressXML) { const unsigned long result = real_compressXML(port, xmlBuf, xmlBufLen, exiBuf, exiBufLen, bitOffset); reportXML(direction_send, port, xmlBuf, xmlBufLen, result); return result; } syslog(LOG_ERR, "Failed to call the real compressXML function"); return 0; } unsigned long decompressEXI(unsigned short port, unsigned char *exiBuf, unsigned long exiBufLen, unsigned char *xmlBuf, unsigned long xmlBufLen, unsigned long bitOffset) { if (!real_decompressEXI) { real_decompressEXI = dlsym(RTLD_NEXT, "decompressEXI"); } if (real_decompressEXI) { const unsigned long result = real_decompressEXI( port, exiBuf, exiBufLen, xmlBuf, xmlBufLen, bitOffset); reportXML(direction_receive, port, xmlBuf, result, exiBufLen); return result; } syslog(LOG_ERR, "Failed to call the real decompressEXI function"); return 0; } const char *lsdlconv_getVersion(void) { if (!real_lsdlconv_getVersion) { real_lsdlconv_getVersion = dlsym(RTLD_NEXT, "lsdlconv_getVersion"); } if (real_lsdlconv_getVersion) { const char *const result = real_lsdlconv_getVersion(); syslog(LOG_INFO, "lsdl-serializer version: %s", result); return result; } syslog(LOG_ERR, "Failed to call the real lsdlconv_getVersion function"); return 0; }
the_stack_data/67324571.c
/* $NetBSD: version.c,v 1.1 1997/10/03 16:40:58 christos Exp $ */ char pcap_version[] = "0.4a3";
the_stack_data/15764046.c
/* posix/_cfgetispeed Created: June 11, 1993 by Philip Homburg */ #include <termios.h> speed_t _cfgetispeed(const struct termios *termios_p) { return termios_p->c_ispeed; }
the_stack_data/144295.c
#include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <errno.h> #include <string.h> extern int errno; char *cat_help = "Usage: cat [OPTION]... [FILE]...\n" "Concatenate FILE(s) to standard output.\n\n" "With no FILE, or when FILE is -, read standard input.\n\n" " -n, --number number all output lines\n" " --help display this help and exit\n" " --version output version information and exit\n\n"; int readfile(char *file) { FILE *fp = fopen(file, "r"); if (!fp) { int err = errno; fprintf(stderr, "cat: %s: %s", file, strerror(err)); exit(1); } int c; while ((c = fgetc(fp)) != EOF) putchar(c); return 0; } void readback() { char *buf = malloc(BUFSIZ); while (1) { fgets(buf, BUFSIZ, stdin); printf(buf); } } int main(int argc, char **argv) { int f_printLine = 0; int optind = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"number", no_argument, 0, 'n'} }; int c; while ((c = getopt_long(argc, argv, "nh", long_options, &optind)) != -1) { switch (c) { case 'n': f_printLine = 1; break; case 'h': printf(cat_help); exit(0); default: fprintf(stderr, "Try 'cat --help' for more information\n"); exit(1); } } if (++optind < argc) { while (optind < argc) readfile(argv[optind++]); return 0; } readback(); return 0; }
the_stack_data/61074831.c
#include <stdio.h> int puts(const char* string) { return printf("%s\n", string); }
the_stack_data/26035.c
/* adler32.c -- compute the Adler-32 checksum of a data stream * Copyright (C) 1995-2004 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id: adler32.c,v 1.2 2006/02/21 05:55:31 bean Exp $ */ #define ZLIB_INTERNAL #include "zlib.h" #define BASE 65521UL /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); /* use NO_DIVIDE if your processor does not do division in hardware */ #ifdef NO_DIVIDE # define MOD(a) \ do { \ if (a >= (BASE << 16)) a -= (BASE << 16); \ if (a >= (BASE << 15)) a -= (BASE << 15); \ if (a >= (BASE << 14)) a -= (BASE << 14); \ if (a >= (BASE << 13)) a -= (BASE << 13); \ if (a >= (BASE << 12)) a -= (BASE << 12); \ if (a >= (BASE << 11)) a -= (BASE << 11); \ if (a >= (BASE << 10)) a -= (BASE << 10); \ if (a >= (BASE << 9)) a -= (BASE << 9); \ if (a >= (BASE << 8)) a -= (BASE << 8); \ if (a >= (BASE << 7)) a -= (BASE << 7); \ if (a >= (BASE << 6)) a -= (BASE << 6); \ if (a >= (BASE << 5)) a -= (BASE << 5); \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) # define MOD4(a) \ do { \ if (a >= (BASE << 4)) a -= (BASE << 4); \ if (a >= (BASE << 3)) a -= (BASE << 3); \ if (a >= (BASE << 2)) a -= (BASE << 2); \ if (a >= (BASE << 1)) a -= (BASE << 1); \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE # define MOD4(a) a %= BASE #endif /* ========================================================================= */ uLong ZEXPORT adler32(adler, buf, len) uLong adler; const Bytef *buf; uInt len; { unsigned long sum2; unsigned n; /* split Adler-32 into component sums */ sum2 = (adler >> 16) & 0xffff; adler &= 0xffff; /* in case user likes doing a byte at a time, keep it fast */ if (len == 1) { adler += buf[0]; if (adler >= BASE) adler -= BASE; sum2 += adler; if (sum2 >= BASE) sum2 -= BASE; return adler | (sum2 << 16); } /* initial Adler-32 value (deferred check for len == 1 speed) */ if (buf == Z_NULL) return 1L; /* in case short lengths are provided, keep it somewhat fast */ if (len < 16) { while (len--) { adler += *buf++; sum2 += adler; } if (adler >= BASE) adler -= BASE; MOD4(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } /* do length NMAX blocks -- requires just one modulo operation */ while (len >= NMAX) { len -= NMAX; n = NMAX / 16; /* NMAX is divisible by 16 */ do { DO16(buf); /* 16 sums unrolled */ buf += 16; } while (--n); MOD(adler); MOD(sum2); } /* do remaining bytes (less than NMAX, still just one modulo) */ if (len) { /* avoid modulos if none remaining */ while (len >= 16) { len -= 16; DO16(buf); buf += 16; } while (len--) { adler += *buf++; sum2 += adler; } MOD(adler); MOD(sum2); } /* return recombined sums */ return adler | (sum2 << 16); } /* ========================================================================= */ uLong ZEXPORT adler32_combine(adler1, adler2, len2) uLong adler1; uLong adler2; z_off_t len2; { unsigned long sum1; unsigned long sum2; unsigned rem; /* the derivation of this formula is left as an exercise for the reader */ rem = (unsigned)(len2 % BASE); sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); sum1 += (adler2 & 0xffff) + BASE - 1; sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; if (sum1 > BASE) sum1 -= BASE; if (sum1 > BASE) sum1 -= BASE; if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); if (sum2 > BASE) sum2 -= BASE; return sum1 | (sum2 << 16); }
the_stack_data/89877.c
/* File: par.c Copyright (c) 2012 David Hauweele <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _XOPEN_SOURCE #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <err.h> static int semid; static int shmid; #define MAX_FORK 8 #define PROJ_ID 'P' #define TOK_PREFIX "/tmp/par" #define UP() sem(+1) #define DOWN() sem(-1) static void sem(int n) { struct sembuf sem = { 0 }; sem.sem_op = n; semop(semid, &sem, 1); } /* Get IPC or create the file if necessary this function ensure that semaphore are initialised and shm attached. */ static int * ipc_creat(const char *path) { static int ipcflg = 0600; static int created; int *shm; key_t key; if((key = ftok(path, PROJ_ID)) < 0) { int fd; /* If the file doesn't exist we create it this creation along with IPC creation should be atomic. But it is not the case for now. */ if(errno != ENOENT) err(1, "ftok \"%s\"", path); fd = open(path, O_RDWR | O_CREAT, 0600); if(fd < 0) err(1, "open \"%s\"", path); close(fd); ipcflg |= IPC_CREAT | IPC_EXCL; created = 1; return ipc_creat(path); } do { /* Get IPC or create them when necessary */ semid = semget(key, 1, ipcflg); shmid = shmget(key, sizeof(int), ipcflg); /* Check ipcget results */ if((semid | shmid) < 0) { if(errno != EEXIST) err(1, "ipcget"); ipcflg = 0600; continue; } } while(0); /* Attach shared memory segment to process address space */ if((shm = shmat(shmid, NULL, 0)) == NULL) err(1, "shmat"); /* Initialise memory and semaphores if just created */ if(created) { if(semctl(semid, 0, SETVAL, 1) < 0) err(1, "semctl"); *shm = 0; } return shm; } static void usage(void) { (void)fprintf(stderr, "par [COMMAND]\n"); exit(1); } int main(int argc, char * const argv[]) { pid_t pid; bool do_fork = true; char *s_argv; char path[256]; int *shm; /* Check arguments */ if(argc < 2) usage(); /* Create the path file and get IPC */ sprintf(path, TOK_PREFIX "%x", getuid()); shm = ipc_creat(path); /* Check if we need to fork then do it when necessary and execute arguments */ DOWN(); { if(*shm <= MAX_FORK) (*shm)++; else do_fork = false; } UP(); if(!do_fork) goto EXEC; pid = fork(); if(pid < 0) err(1, "fork"); else if(pid > 0) exit(0); pid = fork(); if(pid < 0) err(1, "fork"); else if(pid > 0) { wait(NULL); DOWN(); { (*shm)--; } UP(); exit(0); } EXEC: shmdt(shm); argv++; execvp(argv[0], argv); err(1, "exec"); }
the_stack_data/178266198.c
// Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // When building for Unity Android with il2cpp backend, Unity tries to link // the __Internal PInvoke definitions (which are required by iOS) even though // the .so/.dll will be actually used. This file provides dummy stubs to // make il2cpp happy. // See https://github.com/grpc/grpc/issues/16012 #include <stdio.h> #include <stdlib.h> void grpcsharp_init() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_shutdown() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_version_string() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_initial_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_message_length() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_message_next_slice_peek() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_status_on_client_status() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_status_on_client_details() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_status_on_client_trailing_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_close_on_server_cancelled() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_reset() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_call() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_method() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_host() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_deadline() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_request_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_reset() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_composite_call_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_credentials_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_cancel() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_cancel_with_status() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_unary() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_client_streaming() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_server_streaming() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_duplex_streaming() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_message() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_close_from_client() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_status_from_server() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_recv_message() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_recv_initial_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_serverside() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_initial_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_set_credentials() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_get_peer() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_set_string() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_set_integer() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_override_default_ssl_roots() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_ssl_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_composite_channel_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_credentials_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_insecure_channel_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_secure_channel_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_create_call() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_check_connectivity_state() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_watch_connectivity_state() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_get_target() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_sizeof_grpc_event() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_create_async() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_create_sync() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_shutdown() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_next() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_pluck() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_free() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_add() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_count() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_get_key() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_get_value() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_destroy_full() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_redirect_log() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_native_callback_dispatcher_init() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_credentials_create_from_plugin() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_credentials_notify_from_plugin() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_ssl_server_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_credentials_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_register_completion_queue() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_add_insecure_http2_port() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_add_secure_http2_port() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_start() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_request_call() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_cancel_all_calls() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_shutdown_and_notify_callback() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_auth_context() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_context_peer_identity_property_name() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_context_property_iterator() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_property_iterator_next() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_context_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_slice_buffer_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_slice_buffer_adjust_tail_space() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_slice_buffer_slice_count() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_slice_buffer_slice_peek() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_slice_buffer_reset_and_unref() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_slice_buffer_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_now() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_inf_future() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_inf_past() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_convert_clock_type() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_sizeof_timespec() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_callback() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_nop() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_override_method() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_call_start_unary_echo() { fprintf(stderr, "Should never reach here"); abort(); } void dlopen() { fprintf(stderr, "Should never reach here"); abort(); } void dlerror() { fprintf(stderr, "Should never reach here"); abort(); } void dlsym() { fprintf(stderr, "Should never reach here"); abort(); }
the_stack_data/25137327.c
#include<stdio.h> void isEqual(char array[], char array2[]) { int i,j; for (i=0, j=0; array[i]!='\0' && array2[j]!='\0'; i++, j++) { if (array[i]!=array2[j]) { break; } } if (array[i]==array2[j]) printf("Equal"); else if (array[i]<array2[j]) printf("Smaller"); else printf("Bigger"); } int main() { char array[25]; char array2[25]; gets(array); gets(array2); isEqual(array, array2); return 0; }
the_stack_data/1059620.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static complex c_b1 = {1.f,0.f}; static real c_b11 = -1.f; static real c_b12 = 1.f; /* > \brief \b CPOTRF2 */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* Definition: */ /* =========== */ /* SUBROUTINE CPOTRF2( UPLO, N, A, LDA, INFO ) */ /* CHARACTER UPLO */ /* INTEGER INFO, LDA, N */ /* COMPLEX A( LDA, * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > CPOTRF2 computes the Cholesky factorization of a Hermitian */ /* > positive definite matrix A using the recursive algorithm. */ /* > */ /* > The factorization has the form */ /* > A = U**H * U, if UPLO = 'U', or */ /* > A = L * L**H, if UPLO = 'L', */ /* > where U is an upper triangular matrix and L is lower triangular. */ /* > */ /* > This is the recursive version of the algorithm. It divides */ /* > the matrix into four submatrices: */ /* > */ /* > [ A11 | A12 ] where A11 is n1 by n1 and A22 is n2 by n2 */ /* > A = [ -----|----- ] with n1 = n/2 */ /* > [ A21 | A22 ] n2 = n-n1 */ /* > */ /* > The subroutine calls itself to factor A11. Update and scale A21 */ /* > or A12, update A22 then calls itself to factor A22. */ /* > */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > = 'U': Upper triangle of A is stored; */ /* > = 'L': Lower triangle of A is stored. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] A */ /* > \verbatim */ /* > A is COMPLEX array, dimension (LDA,N) */ /* > On entry, the Hermitian matrix A. If UPLO = 'U', the leading */ /* > N-by-N upper triangular part of A contains the upper */ /* > triangular part of the matrix A, and the strictly lower */ /* > triangular part of A is not referenced. If UPLO = 'L', the */ /* > leading N-by-N lower triangular part of A contains the lower */ /* > triangular part of the matrix A, and the strictly upper */ /* > triangular part of A is not referenced. */ /* > */ /* > On exit, if INFO = 0, the factor U or L from the Cholesky */ /* > factorization A = U**H*U or A = L*L**H. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. LDA >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > > 0: if INFO = i, the leading minor of order i is not */ /* > positive definite, and the factorization could not be */ /* > completed. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date June 2016 */ /* > \ingroup complexPOcomputational */ /* ===================================================================== */ /* Subroutine */ int cpotrf2_(char *uplo, integer *n, complex *a, integer * lda, integer *info) { /* System generated locals */ integer a_dim1, a_offset, i__1; real r__1; /* Local variables */ extern /* Subroutine */ int cherk_(char *, char *, integer *, integer *, real *, complex *, integer *, real *, complex *, integer *); extern logical lsame_(char *, char *); integer iinfo; extern /* Subroutine */ int ctrsm_(char *, char *, char *, char *, integer *, integer *, complex *, complex *, integer *, complex *, integer *); logical upper; integer n1, n2; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); extern logical sisnan_(real *); real ajj; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* June 2016 */ /* ===================================================================== */ /* Test the input parameters */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } else if (*lda < f2cmax(1,*n)) { *info = -4; } if (*info != 0) { i__1 = -(*info); xerbla_("CPOTRF2", &i__1, (ftnlen)7); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* N=1 case */ if (*n == 1) { /* Test for non-positive-definiteness */ i__1 = a_dim1 + 1; ajj = a[i__1].r; if (ajj <= 0.f || sisnan_(&ajj)) { *info = 1; return 0; } /* Factor */ i__1 = a_dim1 + 1; r__1 = sqrt(ajj); a[i__1].r = r__1, a[i__1].i = 0.f; /* Use recursive code */ } else { n1 = *n / 2; n2 = *n - n1; /* Factor A11 */ cpotrf2_(uplo, &n1, &a[a_dim1 + 1], lda, &iinfo); if (iinfo != 0) { *info = iinfo; return 0; } /* Compute the Cholesky factorization A = U**H*U */ if (upper) { /* Update and scale A12 */ ctrsm_("L", "U", "C", "N", &n1, &n2, &c_b1, &a[a_dim1 + 1], lda, & a[(n1 + 1) * a_dim1 + 1], lda); /* Update and factor A22 */ cherk_(uplo, "C", &n2, &n1, &c_b11, &a[(n1 + 1) * a_dim1 + 1], lda, &c_b12, &a[n1 + 1 + (n1 + 1) * a_dim1], lda); cpotrf2_(uplo, &n2, &a[n1 + 1 + (n1 + 1) * a_dim1], lda, &iinfo); if (iinfo != 0) { *info = iinfo + n1; return 0; } /* Compute the Cholesky factorization A = L*L**H */ } else { /* Update and scale A21 */ ctrsm_("R", "L", "C", "N", &n2, &n1, &c_b1, &a[a_dim1 + 1], lda, & a[n1 + 1 + a_dim1], lda); /* Update and factor A22 */ cherk_(uplo, "N", &n2, &n1, &c_b11, &a[n1 + 1 + a_dim1], lda, & c_b12, &a[n1 + 1 + (n1 + 1) * a_dim1], lda); cpotrf2_(uplo, &n2, &a[n1 + 1 + (n1 + 1) * a_dim1], lda, &iinfo); if (iinfo != 0) { *info = iinfo + n1; return 0; } } } return 0; /* End of CPOTRF2 */ } /* cpotrf2_ */
the_stack_data/1188519.c
/* * Input: ntabs nchannels padded_size * Output: ntabs ntimes -nchannels ; ntimes < padded_size * * We process a finished tab directly, so no need to build up the full ntabs array */ void deinterleave(const char *page, char *transposed, const int ntabs, const int nchannels, const int ntimes, const int padded_size) { int tab; for (tab = 0; tab < ntabs; tab++) { int channel; #pragma omp parallel for for (channel = 0; channel < nchannels; channel+=6) { const char *channelA = &page[(tab*nchannels + channel + 0)*padded_size]; const char *channelB = &page[(tab*nchannels + channel + 1)*padded_size]; const char *channelC = &page[(tab*nchannels + channel + 2)*padded_size]; const char *channelD = &page[(tab*nchannels + channel + 3)*padded_size]; const char *channelE = &page[(tab*nchannels + channel + 4)*padded_size]; const char *channelF = &page[(tab*nchannels + channel + 5)*padded_size]; int time; for (time = 0; time < ntimes; time++) { // reverse freq order to comply with header transposed[time*nchannels+nchannels-(channel+0)-1] = channelA[time]; transposed[time*nchannels+nchannels-(channel+1)-1] = channelB[time]; transposed[time*nchannels+nchannels-(channel+2)-1] = channelC[time]; transposed[time*nchannels+nchannels-(channel+3)-1] = channelD[time]; transposed[time*nchannels+nchannels-(channel+4)-1] = channelE[time]; transposed[time*nchannels+nchannels-(channel+5)-1] = channelF[time]; } } } }
the_stack_data/39179.c
#include <stdio.h> #include <stdlib.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/err.h> #include <arpa/inet.h> /* For htonl() */ int do_evp_seal(FILE *rsa_pkey_file, FILE *in_file, FILE *out_file) { int retval = 0; RSA *rsa_pkey = NULL; EVP_PKEY *pkey = EVP_PKEY_new(); EVP_CIPHER_CTX *ctx; unsigned char buffer[4096]; unsigned char buffer_out[4096 + EVP_MAX_IV_LENGTH]; size_t len; int len_out; unsigned char *ek = NULL; int eklen; uint32_t eklen_n; unsigned char iv[EVP_MAX_IV_LENGTH]; ctx=EVP_CIPHER_CTX_new(); if (!PEM_read_RSA_PUBKEY(rsa_pkey_file, &rsa_pkey, NULL, NULL)) { fprintf(stderr, "Error loading RSA Public Key File.\n"); ERR_print_errors_fp(stderr); retval = 2; goto out; } if (!EVP_PKEY_assign_RSA(pkey, rsa_pkey)) { fprintf(stderr, "EVP_PKEY_assign_RSA: failed.\n"); retval = 3; goto out; } EVP_CIPHER_CTX_init(ctx); ek = malloc(EVP_PKEY_size(pkey)); if (!EVP_SealInit(ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &pkey, 1)) { fprintf(stderr, "EVP_SealInit: failed.\n"); retval = 3; goto out_free; } /* First we write out the encrypted key length, then the encrypted key, * then the iv (the IV length is fixed by the cipher we have chosen). */ eklen_n = htonl(eklen); if (fwrite(&eklen_n, sizeof eklen_n, 1, out_file) != 1) { perror("output file"); retval = 5; goto out_free; } if (fwrite(ek, eklen, 1, out_file) != 1) { perror("output file"); retval = 5; goto out_free; } if (fwrite(iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()), 1, out_file) != 1) { perror("output file"); retval = 5; goto out_free; } /* Now we process the input file and write the encrypted data to the * output file. */ while ((len = fread(buffer, 1, sizeof buffer, in_file)) > 0) { if (!EVP_SealUpdate(ctx, buffer_out, &len_out, buffer, len)) { fprintf(stderr, "EVP_SealUpdate: failed.\n"); retval = 3; goto out_free; } if (fwrite(buffer_out, len_out, 1, out_file) != 1) { perror("output file"); retval = 5; goto out_free; } } if (ferror(in_file)) { perror("input file"); retval = 4; goto out_free; } if (!EVP_SealFinal(ctx, buffer_out, &len_out)) { fprintf(stderr, "EVP_SealFinal: failed.\n"); retval = 3; goto out_free; } if (fwrite(buffer_out, len_out, 1, out_file) != 1) { perror("output file"); retval = 5; goto out_free; } out_free: EVP_PKEY_free(pkey); EVP_CIPHER_CTX_free(ctx); free(ek); out: return retval; } int main(int argc, char *argv[]) { FILE *rsa_pkey_file; int rv; if (argc < 2) { fprintf(stderr, "Usage: %s <PEM RSA Public Key File>\n", argv[0]); exit(1); } rsa_pkey_file = fopen(argv[1], "rb"); if (!rsa_pkey_file) { perror(argv[1]); fprintf(stderr, "Error loading PEM RSA Public Key File.\n"); exit(2); } FILE *src=fopen("chiaro","rb"); FILE *dst=fopen("cifrato","wb"); rv = do_evp_seal(rsa_pkey_file, src, dst); fclose(rsa_pkey_file); return rv; }
the_stack_data/803352.c
/* TAGS: min c */ /* LIFT_OPTS: explicit +--explicit_args +--explicit_args_count 8 */ /* LIFT_OPTS: default */ /* * Copyright (c) 2018 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <unistd.h> #include <stdlib.h> #include <stdio.h> static char someglobal = 1; static int gInt[2] = {42, 43}; int writeit() { write(2,&someglobal,1); someglobal++; write(2,&someglobal,1); return 0; } int main(void) { someglobal = 0x68; writeit(); gInt[1] = 44; printf("\n"); printf("%i, %i\n", gInt[0], gInt[1]); return 0; }
the_stack_data/23575573.c
#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define MAX_SIZE 50 int main() { /*In the lesson i, linear arrays were created on the stack this is definetely an advantage in terms of speed, but also has many drawbacks. Among them, is that the size of the array has to be specified at compile time. In this lesson, you will learn how to allocate space dinamically. The three functions that we will be using are: malloc -> This functions reserves memory of the specified size calloc -> idem, but, it also initialiazes the memory realloc -> re allocates the memory (e.g allowing arrays to grow in size) */ /*a classic array on the stack, size cannot be altered*/ int numbers[MAX_SIZE]; int cant; printf("Type a size for the array\n"); scanf("%d", &cant); /*This is an array of size cant, being this value assigned at runtime*/ size_t other_numbers_size = cant * sizeof(int); int *other_numbers = (int *)malloc(other_numbers_size); /*the content of the array isnt 0 neccesarely, as the memory wasnt initialized, it is just free memory. Therefore the whats_inside variable can contain any number*/ int whats_inside = other_numbers[0]; /*This is an array of size cant, being this value assigned at runtime*/ int *some_more_numbers = (int *)calloc(cant, sizeof(int)); /*the content of the array is 0 on each position, as the memory was initialized, Therefore the whats_inside variable will contain 0 as well*/ whats_inside = some_more_numbers[0]; /*What to do, if we would like to make the other_numbers array bigger? we use realloc, which will try to extend the given memory. */ some_more_numbers = (int *)realloc(some_more_numbers, other_numbers_size + other_numbers_size); /*Freeing the memory on the heap is very important. it avoids memory leaks and tells the system that a previously available chunk of memory is again free */ free(other_numbers); free(some_more_numbers); return 0; }
the_stack_data/117006.c
#include <stdio.h> #include <stdlib.h> int main() { char name[50]; int marks, i, num; printf("Enter number of students: "); scanf("%d", &num); FILE *fptr; fptr = (fopen("file3.txt", "r")); if(fptr == NULL) { printf("Error!"); exit(1); } for(i = 1; i <= num; ++i) { if(!feof(fptr)){ fscanf(fptr,"\nName: %s \nMarks=%d \n", name, &marks); printf("Student%d: Name: ", i); printf("%s", name); printf("\tMarks: "); printf("%d", marks); } else{ printf("\nOOPS!! There are only %d students in the file.",i-1); break; } printf("\n"); } fclose(fptr); return 0; }
the_stack_data/1189691.c
/* engines/e_capi.c */ /* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL * project. */ /* ==================================================================== * Copyright (c) 2008 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ #include <stdio.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/buffer.h> #include <openssl/bn.h> #ifdef OPENSSL_SYS_WIN32 #ifndef OPENSSL_NO_CAPIENG #include <openssl/rsa.h> #include <windows.h> #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0400 #endif #include <wincrypt.h> /* * This module uses several "new" interfaces, among which is * CertGetCertificateContextProperty. CERT_KEY_PROV_INFO_PROP_ID is * one of possible values you can pass to function in question. By * checking if it's defined we can see if wincrypt.h and accompanying * crypt32.lib are in shape. The native MingW32 headers up to and * including __W32API_VERSION 3.14 lack of struct DSSPUBKEY and the * defines CERT_STORE_PROV_SYSTEM_A and CERT_STORE_READONLY_FLAG, * so we check for these too and avoid compiling. * Yes, it's rather "weak" test and if compilation fails, * then re-configure with -DOPENSSL_NO_CAPIENG. */ #if defined(CERT_KEY_PROV_INFO_PROP_ID) && \ defined(CERT_STORE_PROV_SYSTEM_A) && \ defined(CERT_STORE_READONLY_FLAG) # define __COMPILE_CAPIENG #endif /* CERT_KEY_PROV_INFO_PROP_ID */ #endif /* OPENSSL_NO_CAPIENG */ #endif /* OPENSSL_SYS_WIN32 */ #ifdef __COMPILE_CAPIENG #undef X509_EXTENSIONS #undef X509_CERT_PAIR /* Definitions which may be missing from earlier version of headers */ #ifndef CERT_STORE_OPEN_EXISTING_FLAG #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000 #endif #ifndef CERT_STORE_CREATE_NEW_FLAG #define CERT_STORE_CREATE_NEW_FLAG 0x00002000 #endif #ifndef CERT_SYSTEM_STORE_CURRENT_USER #define CERT_SYSTEM_STORE_CURRENT_USER 0x00010000 #endif #include <openssl/engine.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include "e_capi_err.h" #include "e_capi_err.c" static const char *engine_capi_id = "capi"; static const char *engine_capi_name = "CryptoAPI ENGINE"; typedef struct CAPI_CTX_st CAPI_CTX; typedef struct CAPI_KEY_st CAPI_KEY; static void capi_addlasterror(void); static void capi_adderror(DWORD err); static void CAPI_trace(CAPI_CTX *ctx, char *format, ...); static int capi_list_providers(CAPI_CTX *ctx, BIO *out); static int capi_list_containers(CAPI_CTX *ctx, BIO *out); int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *storename); void capi_free_key(CAPI_KEY *key); static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore); CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id); static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id, UI_METHOD *ui_method, void *callback_data); static int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, const RSA *rsa); static int capi_rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); static int capi_rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding); static int capi_rsa_free(RSA *rsa); static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen, DSA *dsa); static int capi_dsa_free(DSA *dsa); static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl, STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey, STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data); static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs); #ifdef OPENSSL_CAPIENG_DIALOG static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs); #endif typedef PCCERT_CONTEXT (WINAPI *CERTDLG)(HCERTSTORE, HWND, LPCWSTR, LPCWSTR, DWORD, DWORD, void *); typedef HWND (WINAPI *GETCONSWIN)(void); /* This structure contains CAPI ENGINE specific data: * it contains various global options and affects how * other functions behave. */ #define CAPI_DBG_TRACE 2 #define CAPI_DBG_ERROR 1 struct CAPI_CTX_st { int debug_level; char *debug_file; /* Parameters to use for container lookup */ DWORD keytype; LPSTR cspname; DWORD csptype; /* Certificate store name to use */ LPSTR storename; LPSTR ssl_client_store; /* System store flags */ DWORD store_flags; /* Lookup string meanings in load_private_key */ /* Substring of subject: uses "storename" */ #define CAPI_LU_SUBSTR 1 /* Friendly name: uses storename */ #define CAPI_LU_FNAME 2 /* Container name: uses cspname, keytype */ #define CAPI_LU_CONTNAME 3 int lookup_method; /* Info to dump with dumpcerts option */ /* Issuer and serial name strings */ #define CAPI_DMP_SUMMARY 0x1 /* Friendly name */ #define CAPI_DMP_FNAME 0x2 /* Full X509_print dump */ #define CAPI_DMP_FULL 0x4 /* Dump PEM format certificate */ #define CAPI_DMP_PEM 0x8 /* Dump pseudo key (if possible) */ #define CAPI_DMP_PSKEY 0x10 /* Dump key info (if possible) */ #define CAPI_DMP_PKEYINFO 0x20 DWORD dump_flags; int (*client_cert_select)(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs); CERTDLG certselectdlg; GETCONSWIN getconswindow; }; static CAPI_CTX *capi_ctx_new(); static void capi_ctx_free(CAPI_CTX *ctx); static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check); static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx); #define CAPI_CMD_LIST_CERTS ENGINE_CMD_BASE #define CAPI_CMD_LOOKUP_CERT (ENGINE_CMD_BASE + 1) #define CAPI_CMD_DEBUG_LEVEL (ENGINE_CMD_BASE + 2) #define CAPI_CMD_DEBUG_FILE (ENGINE_CMD_BASE + 3) #define CAPI_CMD_KEYTYPE (ENGINE_CMD_BASE + 4) #define CAPI_CMD_LIST_CSPS (ENGINE_CMD_BASE + 5) #define CAPI_CMD_SET_CSP_IDX (ENGINE_CMD_BASE + 6) #define CAPI_CMD_SET_CSP_NAME (ENGINE_CMD_BASE + 7) #define CAPI_CMD_SET_CSP_TYPE (ENGINE_CMD_BASE + 8) #define CAPI_CMD_LIST_CONTAINERS (ENGINE_CMD_BASE + 9) #define CAPI_CMD_LIST_OPTIONS (ENGINE_CMD_BASE + 10) #define CAPI_CMD_LOOKUP_METHOD (ENGINE_CMD_BASE + 11) #define CAPI_CMD_STORE_NAME (ENGINE_CMD_BASE + 12) #define CAPI_CMD_STORE_FLAGS (ENGINE_CMD_BASE + 13) static const ENGINE_CMD_DEFN capi_cmd_defns[] = { {CAPI_CMD_LIST_CERTS, "list_certs", "List all certificates in store", ENGINE_CMD_FLAG_NO_INPUT}, {CAPI_CMD_LOOKUP_CERT, "lookup_cert", "Lookup and output certificates", ENGINE_CMD_FLAG_STRING}, {CAPI_CMD_DEBUG_LEVEL, "debug_level", "debug level (1=errors, 2=trace)", ENGINE_CMD_FLAG_NUMERIC}, {CAPI_CMD_DEBUG_FILE, "debug_file", "debugging filename)", ENGINE_CMD_FLAG_STRING}, {CAPI_CMD_KEYTYPE, "key_type", "Key type: 1=AT_KEYEXCHANGE (default), 2=AT_SIGNATURE", ENGINE_CMD_FLAG_NUMERIC}, {CAPI_CMD_LIST_CSPS, "list_csps", "List all CSPs", ENGINE_CMD_FLAG_NO_INPUT}, {CAPI_CMD_SET_CSP_IDX, "csp_idx", "Set CSP by index", ENGINE_CMD_FLAG_NUMERIC}, {CAPI_CMD_SET_CSP_NAME, "csp_name", "Set CSP name, (default CSP used if not specified)", ENGINE_CMD_FLAG_STRING}, {CAPI_CMD_SET_CSP_TYPE, "csp_type", "Set CSP type, (default RSA_PROV_FULL)", ENGINE_CMD_FLAG_NUMERIC}, {CAPI_CMD_LIST_CONTAINERS, "list_containers", "list container names", ENGINE_CMD_FLAG_NO_INPUT}, {CAPI_CMD_LIST_OPTIONS, "list_options", "Set list options (1=summary,2=friendly name, 4=full printout, 8=PEM output, 16=XXX, " "32=private key info)", ENGINE_CMD_FLAG_NUMERIC}, {CAPI_CMD_LOOKUP_METHOD, "lookup_method", "Set key lookup method (1=substring, 2=friendlyname, 3=container name)", ENGINE_CMD_FLAG_NUMERIC}, {CAPI_CMD_STORE_NAME, "store_name", "certificate store name, default \"MY\"", ENGINE_CMD_FLAG_STRING}, {CAPI_CMD_STORE_FLAGS, "store_flags", "Certificate store flags: 1 = system store", ENGINE_CMD_FLAG_NUMERIC}, {0, NULL, NULL, 0} }; static int capi_idx = -1; static int rsa_capi_idx = -1; static int dsa_capi_idx = -1; static int cert_capi_idx = -1; static int capi_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) { int ret = 1; CAPI_CTX *ctx; BIO *out; if (capi_idx == -1) { CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_ENGINE_NOT_INITIALIZED); return 0; } ctx = ENGINE_get_ex_data(e, capi_idx); out = BIO_new_fp(stdout, BIO_NOCLOSE); switch (cmd) { case CAPI_CMD_LIST_CSPS: ret = capi_list_providers(ctx, out); break; case CAPI_CMD_LIST_CERTS: ret = capi_list_certs(ctx, out, NULL); break; case CAPI_CMD_LOOKUP_CERT: ret = capi_list_certs(ctx, out, p); break; case CAPI_CMD_LIST_CONTAINERS: ret = capi_list_containers(ctx, out); break; case CAPI_CMD_STORE_NAME: if (ctx->storename) OPENSSL_free(ctx->storename); ctx->storename = BUF_strdup(p); CAPI_trace(ctx, "Setting store name to %s\n", p); break; case CAPI_CMD_STORE_FLAGS: if (i & 1) { ctx->store_flags |= CERT_SYSTEM_STORE_LOCAL_MACHINE; ctx->store_flags &= ~CERT_SYSTEM_STORE_CURRENT_USER; } else { ctx->store_flags |= CERT_SYSTEM_STORE_CURRENT_USER; ctx->store_flags &= ~CERT_SYSTEM_STORE_LOCAL_MACHINE; } CAPI_trace(ctx, "Setting flags to %d\n", i); break; case CAPI_CMD_DEBUG_LEVEL: ctx->debug_level = (int)i; CAPI_trace(ctx, "Setting debug level to %d\n", ctx->debug_level); break; case CAPI_CMD_DEBUG_FILE: ctx->debug_file = BUF_strdup(p); CAPI_trace(ctx, "Setting debug file to %s\n", ctx->debug_file); break; case CAPI_CMD_KEYTYPE: ctx->keytype = i; CAPI_trace(ctx, "Setting key type to %d\n", ctx->keytype); break; case CAPI_CMD_SET_CSP_IDX: ret = capi_ctx_set_provname_idx(ctx, i); break; case CAPI_CMD_LIST_OPTIONS: ctx->dump_flags = i; break; case CAPI_CMD_LOOKUP_METHOD: if (i < 1 || i > 3) { CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_INVALID_LOOKUP_METHOD); return 0; } ctx->lookup_method = i; break; case CAPI_CMD_SET_CSP_NAME: ret = capi_ctx_set_provname(ctx, p, ctx->csptype, 1); break; case CAPI_CMD_SET_CSP_TYPE: ctx->csptype = i; break; default: CAPIerr(CAPI_F_CAPI_CTRL, CAPI_R_UNKNOWN_COMMAND); ret = 0; } BIO_free(out); return ret; } static RSA_METHOD capi_rsa_method = { "CryptoAPI RSA method", 0, /* pub_enc */ 0, /* pub_dec */ capi_rsa_priv_enc, /* priv_enc */ capi_rsa_priv_dec, /* priv_dec */ 0, /* rsa_mod_exp */ 0, /* bn_mod_exp */ 0, /* init */ capi_rsa_free, /* finish */ RSA_FLAG_SIGN_VER, /* flags */ NULL, /* app_data */ capi_rsa_sign, /* rsa_sign */ 0 /* rsa_verify */ }; static DSA_METHOD capi_dsa_method = { "CryptoAPI DSA method", capi_dsa_do_sign, /* dsa_do_sign */ 0, /* dsa_sign_setup */ 0, /* dsa_do_verify */ 0, /* dsa_mod_exp */ 0, /* bn_mod_exp */ 0, /* init */ capi_dsa_free, /* finish */ 0, /* flags */ NULL, /* app_data */ 0, /* dsa_paramgen */ 0 /* dsa_keygen */ }; static int capi_init(ENGINE *e) { CAPI_CTX *ctx; const RSA_METHOD *ossl_rsa_meth; const DSA_METHOD *ossl_dsa_meth; capi_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0); cert_capi_idx = X509_get_ex_new_index(0, NULL, NULL, NULL, 0); ctx = capi_ctx_new(); if (!ctx || (capi_idx < 0)) goto memerr; ENGINE_set_ex_data(e, capi_idx, ctx); /* Setup RSA_METHOD */ rsa_capi_idx = RSA_get_ex_new_index(0, NULL, NULL, NULL, 0); ossl_rsa_meth = RSA_PKCS1_SSLeay(); capi_rsa_method.rsa_pub_enc = ossl_rsa_meth->rsa_pub_enc; capi_rsa_method.rsa_pub_dec = ossl_rsa_meth->rsa_pub_dec; capi_rsa_method.rsa_mod_exp = ossl_rsa_meth->rsa_mod_exp; capi_rsa_method.bn_mod_exp = ossl_rsa_meth->bn_mod_exp; /* Setup DSA Method */ dsa_capi_idx = DSA_get_ex_new_index(0, NULL, NULL, NULL, 0); ossl_dsa_meth = DSA_OpenSSL(); capi_dsa_method.dsa_do_verify = ossl_dsa_meth->dsa_do_verify; capi_dsa_method.dsa_mod_exp = ossl_dsa_meth->dsa_mod_exp; capi_dsa_method.bn_mod_exp = ossl_dsa_meth->bn_mod_exp; #ifdef OPENSSL_CAPIENG_DIALOG { HMODULE cryptui = LoadLibrary(TEXT("CRYPTUI.DLL")); HMODULE kernel = GetModuleHandle(TEXT("KERNEL32.DLL")); if (cryptui) ctx->certselectdlg = (CERTDLG)GetProcAddress(cryptui, "CryptUIDlgSelectCertificateFromStore"); if (kernel) ctx->getconswindow = (GETCONSWIN)GetProcAddress(kernel, "GetConsoleWindow"); if (cryptui && !OPENSSL_isservice()) ctx->client_cert_select = cert_select_dialog; } #endif return 1; memerr: CAPIerr(CAPI_F_CAPI_INIT, ERR_R_MALLOC_FAILURE); return 0; return 1; } static int capi_destroy(ENGINE *e) { ERR_unload_CAPI_strings(); return 1; } static int capi_finish(ENGINE *e) { CAPI_CTX *ctx; ctx = ENGINE_get_ex_data(e, capi_idx); capi_ctx_free(ctx); ENGINE_set_ex_data(e, capi_idx, NULL); return 1; } /* CryptoAPI key application data. This contains * a handle to the private key container (for sign operations) * and a handle to the key (for decrypt operations). */ struct CAPI_KEY_st { /* Associated certificate context (if any) */ PCCERT_CONTEXT pcert; HCRYPTPROV hprov; HCRYPTKEY key; DWORD keyspec; }; static int bind_capi(ENGINE *e) { if (!ENGINE_set_id(e, engine_capi_id) || !ENGINE_set_name(e, engine_capi_name) || !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL) || !ENGINE_set_init_function(e, capi_init) || !ENGINE_set_finish_function(e, capi_finish) || !ENGINE_set_destroy_function(e, capi_destroy) || !ENGINE_set_RSA(e, &capi_rsa_method) || !ENGINE_set_DSA(e, &capi_dsa_method) || !ENGINE_set_load_privkey_function(e, capi_load_privkey) || !ENGINE_set_load_ssl_client_cert_function(e, capi_load_ssl_client_cert) || !ENGINE_set_cmd_defns(e, capi_cmd_defns) || !ENGINE_set_ctrl_function(e, capi_ctrl)) return 0; ERR_load_CAPI_strings(); return 1; } #ifndef OPENSSL_NO_DYNAMIC_ENGINE static int bind_helper(ENGINE *e, const char *id) { if(id && (strcmp(id, engine_capi_id) != 0)) return 0; if(!bind_capi(e)) return 0; return 1; } IMPLEMENT_DYNAMIC_CHECK_FN() IMPLEMENT_DYNAMIC_BIND_FN(bind_helper) #else static ENGINE *engine_capi(void) { ENGINE *ret = ENGINE_new(); if(!ret) return NULL; if(!bind_capi(ret)) { ENGINE_free(ret); return NULL; } return ret; } void ENGINE_load_capi(void) { /* Copied from eng_[openssl|dyn].c */ ENGINE *toadd = engine_capi(); if(!toadd) return; ENGINE_add(toadd); ENGINE_free(toadd); ERR_clear_error(); } #endif static int lend_tobn(BIGNUM *bn, unsigned char *bin, int binlen) { int i; /* Reverse buffer in place: since this is a keyblob structure * that will be freed up after conversion anyway it doesn't * matter if we change it. */ for(i = 0; i < binlen / 2; i++) { unsigned char c; c = bin[i]; bin[i] = bin[binlen - i - 1]; bin[binlen - i - 1] = c; } if (!BN_bin2bn(bin, binlen, bn)) return 0; return 1; } /* Given a CAPI_KEY get an EVP_PKEY structure */ static EVP_PKEY *capi_get_pkey(ENGINE *eng, CAPI_KEY *key) { unsigned char *pubkey = NULL; DWORD len; BLOBHEADER *bh; RSA *rkey = NULL; DSA *dkey = NULL; EVP_PKEY *ret = NULL; if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, NULL, &len)) { CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_LENGTH_ERROR); capi_addlasterror(); return NULL; } pubkey = OPENSSL_malloc(len); if (!pubkey) goto memerr; if (!CryptExportKey(key->key, 0, PUBLICKEYBLOB, 0, pubkey, &len)) { CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_PUBKEY_EXPORT_ERROR); capi_addlasterror(); goto err; } bh = (BLOBHEADER *)pubkey; if (bh->bType != PUBLICKEYBLOB) { CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_PUBLIC_KEY_BLOB); goto err; } if (bh->aiKeyAlg == CALG_RSA_SIGN || bh->aiKeyAlg == CALG_RSA_KEYX) { RSAPUBKEY *rp; DWORD rsa_modlen; unsigned char *rsa_modulus; rp = (RSAPUBKEY *)(bh + 1); if (rp->magic != 0x31415352) { char magstr[10]; BIO_snprintf(magstr, 10, "%lx", rp->magic); CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_RSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER); ERR_add_error_data(2, "magic=0x", magstr); goto err; } rsa_modulus = (unsigned char *)(rp + 1); rkey = RSA_new_method(eng); if (!rkey) goto memerr; rkey->e = BN_new(); rkey->n = BN_new(); if (!rkey->e || !rkey->n) goto memerr; if (!BN_set_word(rkey->e, rp->pubexp)) goto memerr; rsa_modlen = rp->bitlen / 8; if (!lend_tobn(rkey->n, rsa_modulus, rsa_modlen)) goto memerr; RSA_set_ex_data(rkey, rsa_capi_idx, key); if (!(ret = EVP_PKEY_new())) goto memerr; EVP_PKEY_assign_RSA(ret, rkey); rkey = NULL; } else if (bh->aiKeyAlg == CALG_DSS_SIGN) { DSSPUBKEY *dp; DWORD dsa_plen; unsigned char *btmp; dp = (DSSPUBKEY *)(bh + 1); if (dp->magic != 0x31535344) { char magstr[10]; BIO_snprintf(magstr, 10, "%lx", dp->magic); CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_INVALID_DSA_PUBLIC_KEY_BLOB_MAGIC_NUMBER); ERR_add_error_data(2, "magic=0x", magstr); goto err; } dsa_plen = dp->bitlen / 8; btmp = (unsigned char *)(dp + 1); dkey = DSA_new_method(eng); if (!dkey) goto memerr; dkey->p = BN_new(); dkey->q = BN_new(); dkey->g = BN_new(); dkey->pub_key = BN_new(); if (!dkey->p || !dkey->q || !dkey->g || !dkey->pub_key) goto memerr; if (!lend_tobn(dkey->p, btmp, dsa_plen)) goto memerr; btmp += dsa_plen; if (!lend_tobn(dkey->q, btmp, 20)) goto memerr; btmp += 20; if (!lend_tobn(dkey->g, btmp, dsa_plen)) goto memerr; btmp += dsa_plen; if (!lend_tobn(dkey->pub_key, btmp, dsa_plen)) goto memerr; btmp += dsa_plen; DSA_set_ex_data(dkey, dsa_capi_idx, key); if (!(ret = EVP_PKEY_new())) goto memerr; EVP_PKEY_assign_DSA(ret, dkey); dkey = NULL; } else { char algstr[10]; BIO_snprintf(algstr, 10, "%lx", bh->aiKeyAlg); CAPIerr(CAPI_F_CAPI_GET_PKEY, CAPI_R_UNSUPPORTED_PUBLIC_KEY_ALGORITHM); ERR_add_error_data(2, "aiKeyAlg=0x", algstr); goto err; } err: if (pubkey) OPENSSL_free(pubkey); if (!ret) { if (rkey) RSA_free(rkey); if (dkey) DSA_free(dkey); } return ret; memerr: CAPIerr(CAPI_F_CAPI_GET_PKEY, ERR_R_MALLOC_FAILURE); goto err; } static EVP_PKEY *capi_load_privkey(ENGINE *eng, const char *key_id, UI_METHOD *ui_method, void *callback_data) { CAPI_CTX *ctx; CAPI_KEY *key; EVP_PKEY *ret; ctx = ENGINE_get_ex_data(eng, capi_idx); if (!ctx) { CAPIerr(CAPI_F_CAPI_LOAD_PRIVKEY, CAPI_R_CANT_FIND_CAPI_CONTEXT); return NULL; } key = capi_find_key(ctx, key_id); if (!key) return NULL; ret = capi_get_pkey(eng, key); if (!ret) capi_free_key(key); return ret; } /* CryptoAPI RSA operations */ int capi_rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_ENC, CAPI_R_FUNCTION_NOT_SUPPORTED); return -1; } int capi_rsa_sign(int dtype, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, const RSA *rsa) { ALG_ID alg; HCRYPTHASH hash; DWORD slen; unsigned int i; int ret = -1; CAPI_KEY *capi_key; CAPI_CTX *ctx; ctx = ENGINE_get_ex_data(rsa->engine, capi_idx); CAPI_trace(ctx, "Called CAPI_rsa_sign()\n"); capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); if (!capi_key) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_GET_KEY); return -1; } /* Convert the signature type to a CryptoAPI algorithm ID */ switch(dtype) { case NID_sha1: alg = CALG_SHA1; break; case NID_md5: alg = CALG_MD5; break; case NID_md5_sha1: alg = CALG_SSL3_SHAMD5; break; default: { char algstr[10]; BIO_snprintf(algstr, 10, "%lx", dtype); CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_UNSUPPORTED_ALGORITHM_NID); ERR_add_error_data(2, "NID=0x", algstr); return -1; } } /* Create the hash object */ if(!CryptCreateHash(capi_key->hprov, alg, 0, 0, &hash)) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT); capi_addlasterror(); return -1; } /* Set the hash value to the value passed */ if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)m, 0)) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_CANT_SET_HASH_VALUE); capi_addlasterror(); goto err; } /* Finally sign it */ slen = RSA_size(rsa); if(!CryptSignHashA(hash, capi_key->keyspec, NULL, 0, sigret, &slen)) { CAPIerr(CAPI_F_CAPI_RSA_SIGN, CAPI_R_ERROR_SIGNING_HASH); capi_addlasterror(); goto err; } else { ret = 1; /* Inplace byte reversal of signature */ for(i = 0; i < slen / 2; i++) { unsigned char c; c = sigret[i]; sigret[i] = sigret[slen - i - 1]; sigret[slen - i - 1] = c; } *siglen = slen; } /* Now cleanup */ err: CryptDestroyHash(hash); return ret; } int capi_rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding) { int i; unsigned char *tmpbuf; CAPI_KEY *capi_key; CAPI_CTX *ctx; ctx = ENGINE_get_ex_data(rsa->engine, capi_idx); CAPI_trace(ctx, "Called capi_rsa_priv_dec()\n"); capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); if (!capi_key) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_CANT_GET_KEY); return -1; } if(padding != RSA_PKCS1_PADDING) { char errstr[10]; BIO_snprintf(errstr, 10, "%d", padding); CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_UNSUPPORTED_PADDING); ERR_add_error_data(2, "padding=", errstr); return -1; } /* Create temp reverse order version of input */ if(!(tmpbuf = OPENSSL_malloc(flen)) ) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, ERR_R_MALLOC_FAILURE); return -1; } for(i = 0; i < flen; i++) tmpbuf[flen - i - 1] = from[i]; /* Finally decrypt it */ if(!CryptDecrypt(capi_key->key, 0, TRUE, 0, tmpbuf, &flen)) { CAPIerr(CAPI_F_CAPI_RSA_PRIV_DEC, CAPI_R_DECRYPT_ERROR); capi_addlasterror(); OPENSSL_free(tmpbuf); return -1; } else memcpy(to, tmpbuf, flen); OPENSSL_free(tmpbuf); return flen; } static int capi_rsa_free(RSA *rsa) { CAPI_KEY *capi_key; capi_key = RSA_get_ex_data(rsa, rsa_capi_idx); capi_free_key(capi_key); RSA_set_ex_data(rsa, rsa_capi_idx, 0); return 1; } /* CryptoAPI DSA operations */ static DSA_SIG *capi_dsa_do_sign(const unsigned char *digest, int dlen, DSA *dsa) { HCRYPTHASH hash; DWORD slen; DSA_SIG *ret = NULL; CAPI_KEY *capi_key; CAPI_CTX *ctx; unsigned char csigbuf[40]; ctx = ENGINE_get_ex_data(dsa->engine, capi_idx); CAPI_trace(ctx, "Called CAPI_dsa_do_sign()\n"); capi_key = DSA_get_ex_data(dsa, dsa_capi_idx); if (!capi_key) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_GET_KEY); return NULL; } if (dlen != 20) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_INVALID_DIGEST_LENGTH); return NULL; } /* Create the hash object */ if(!CryptCreateHash(capi_key->hprov, CALG_SHA1, 0, 0, &hash)) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_CREATE_HASH_OBJECT); capi_addlasterror(); return NULL; } /* Set the hash value to the value passed */ if(!CryptSetHashParam(hash, HP_HASHVAL, (unsigned char *)digest, 0)) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_CANT_SET_HASH_VALUE); capi_addlasterror(); goto err; } /* Finally sign it */ slen = sizeof(csigbuf); if(!CryptSignHashA(hash, capi_key->keyspec, NULL, 0, csigbuf, &slen)) { CAPIerr(CAPI_F_CAPI_DSA_DO_SIGN, CAPI_R_ERROR_SIGNING_HASH); capi_addlasterror(); goto err; } else { ret = DSA_SIG_new(); if (!ret) goto err; ret->r = BN_new(); ret->s = BN_new(); if (!ret->r || !ret->s) goto err; if (!lend_tobn(ret->r, csigbuf, 20) || !lend_tobn(ret->s, csigbuf + 20, 20)) { DSA_SIG_free(ret); ret = NULL; goto err; } } /* Now cleanup */ err: OPENSSL_cleanse(csigbuf, 40); CryptDestroyHash(hash); return ret; } static int capi_dsa_free(DSA *dsa) { CAPI_KEY *capi_key; capi_key = DSA_get_ex_data(dsa, dsa_capi_idx); capi_free_key(capi_key); DSA_set_ex_data(dsa, dsa_capi_idx, 0); return 1; } static void capi_vtrace(CAPI_CTX *ctx, int level, char *format, va_list argptr) { BIO *out; if (!ctx || (ctx->debug_level < level) || (!ctx->debug_file)) return; out = BIO_new_file(ctx->debug_file, "a+"); BIO_vprintf(out, format, argptr); BIO_free(out); } static void CAPI_trace(CAPI_CTX *ctx, char *format, ...) { va_list args; va_start(args, format); capi_vtrace(ctx, CAPI_DBG_TRACE, format, args); va_end(args); } static void capi_addlasterror(void) { capi_adderror(GetLastError()); } static void capi_adderror(DWORD err) { char errstr[10]; BIO_snprintf(errstr, 10, "%lX", err); ERR_add_error_data(2, "Error code= 0x", errstr); } static char *wide_to_asc(LPWSTR wstr) { char *str; int len_0,sz; if (!wstr) return NULL; len_0 = (int)wcslen(wstr)+1; /* WideCharToMultiByte expects int */ sz = WideCharToMultiByte(CP_ACP,0,wstr,len_0,NULL,0,NULL,NULL); if (!sz) { CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR); return NULL; } str = OPENSSL_malloc(sz); if (!str) { CAPIerr(CAPI_F_WIDE_TO_ASC, ERR_R_MALLOC_FAILURE); return NULL; } if (!WideCharToMultiByte(CP_ACP,0,wstr,len_0,str,sz,NULL,NULL)) { OPENSSL_free(str); CAPIerr(CAPI_F_WIDE_TO_ASC, CAPI_R_WIN32_ERROR); return NULL; } return str; } static int capi_get_provname(CAPI_CTX *ctx, LPSTR *pname, DWORD *ptype, DWORD idx) { LPSTR name; DWORD len, err; CAPI_trace(ctx, "capi_get_provname, index=%d\n", idx); if (!CryptEnumProvidersA(idx, NULL, 0, ptype, NULL, &len)) { err = GetLastError(); if (err == ERROR_NO_MORE_ITEMS) return 2; CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR); capi_adderror(err); return 0; } name = OPENSSL_malloc(len); if (!CryptEnumProvidersA(idx, NULL, 0, ptype, name, &len)) { err = GetLastError(); if (err == ERROR_NO_MORE_ITEMS) return 2; CAPIerr(CAPI_F_CAPI_GET_PROVNAME, CAPI_R_CRYPTENUMPROVIDERS_ERROR); capi_adderror(err); return 0; } *pname = name; CAPI_trace(ctx, "capi_get_provname, returned name=%s, type=%d\n", name, *ptype); return 1; } static int capi_list_providers(CAPI_CTX *ctx, BIO *out) { DWORD idx, ptype; int ret; LPSTR provname = NULL; CAPI_trace(ctx, "capi_list_providers\n"); BIO_printf(out, "Available CSPs:\n"); for(idx = 0; ; idx++) { ret = capi_get_provname(ctx, &provname, &ptype, idx); if (ret == 2) break; if (ret == 0) break; BIO_printf(out, "%d. %s, type %d\n", idx, provname, ptype); OPENSSL_free(provname); } return 1; } static int capi_list_containers(CAPI_CTX *ctx, BIO *out) { int ret = 1; HCRYPTPROV hprov; DWORD err, idx, flags, buflen = 0, clen; LPSTR cname; CAPI_trace(ctx, "Listing containers CSP=%s, type = %d\n", ctx->cspname, ctx->csptype); if (!CryptAcquireContextA(&hprov, NULL, ctx->cspname, ctx->csptype, CRYPT_VERIFYCONTEXT)) { CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_CRYPTACQUIRECONTEXT_ERROR); capi_addlasterror(); return 0; } if (!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, NULL, &buflen, CRYPT_FIRST)) { CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR); capi_addlasterror(); return 0; } CAPI_trace(ctx, "Got max container len %d\n", buflen); if (buflen == 0) buflen = 1024; cname = OPENSSL_malloc(buflen); if (!cname) { CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, ERR_R_MALLOC_FAILURE); goto err; } for (idx = 0;;idx++) { clen = buflen; cname[0] = 0; if (idx == 0) flags = CRYPT_FIRST; else flags = 0; if(!CryptGetProvParam(hprov, PP_ENUMCONTAINERS, cname, &clen, flags)) { err = GetLastError(); if (err == ERROR_NO_MORE_ITEMS) goto done; CAPIerr(CAPI_F_CAPI_LIST_CONTAINERS, CAPI_R_ENUMCONTAINERS_ERROR); capi_adderror(err); goto err; } CAPI_trace(ctx, "Container name %s, len=%d, index=%d, flags=%d\n", cname, clen, idx, flags); if (!cname[0] && (clen == buflen)) { CAPI_trace(ctx, "Enumerate bug: using workaround\n"); goto done; } BIO_printf(out, "%d. %s\n", idx, cname); } err: ret = 0; done: if (cname) OPENSSL_free(cname); CryptReleaseContext(hprov, 0); return ret; } CRYPT_KEY_PROV_INFO *capi_get_prov_info(CAPI_CTX *ctx, PCCERT_CONTEXT cert) { DWORD len; CRYPT_KEY_PROV_INFO *pinfo; if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, NULL, &len)) return NULL; pinfo = OPENSSL_malloc(len); if (!pinfo) { CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, ERR_R_MALLOC_FAILURE); return NULL; } if(!CertGetCertificateContextProperty(cert, CERT_KEY_PROV_INFO_PROP_ID, pinfo, &len)) { CAPIerr(CAPI_F_CAPI_GET_PROV_INFO, CAPI_R_ERROR_GETTING_KEY_PROVIDER_INFO); capi_addlasterror(); OPENSSL_free(pinfo); return NULL; } return pinfo; } static void capi_dump_prov_info(CAPI_CTX *ctx, BIO *out, CRYPT_KEY_PROV_INFO *pinfo) { char *provname = NULL, *contname = NULL; if (!pinfo) { BIO_printf(out, " No Private Key\n"); return; } provname = wide_to_asc(pinfo->pwszProvName); contname = wide_to_asc(pinfo->pwszContainerName); if (!provname || !contname) goto err; BIO_printf(out, " Private Key Info:\n"); BIO_printf(out, " Provider Name: %s, Provider Type %d\n", provname, pinfo->dwProvType); BIO_printf(out, " Container Name: %s, Key Type %d\n", contname, pinfo->dwKeySpec); err: if (provname) OPENSSL_free(provname); if (contname) OPENSSL_free(contname); } char * capi_cert_get_fname(CAPI_CTX *ctx, PCCERT_CONTEXT cert) { LPWSTR wfname; DWORD dlen; CAPI_trace(ctx, "capi_cert_get_fname\n"); if (!CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, NULL, &dlen)) return NULL; wfname = OPENSSL_malloc(dlen); if (CertGetCertificateContextProperty(cert, CERT_FRIENDLY_NAME_PROP_ID, wfname, &dlen)) { char *fname = wide_to_asc(wfname); OPENSSL_free(wfname); return fname; } CAPIerr(CAPI_F_CAPI_CERT_GET_FNAME, CAPI_R_ERROR_GETTING_FRIENDLY_NAME); capi_addlasterror(); OPENSSL_free(wfname); return NULL; } void capi_dump_cert(CAPI_CTX *ctx, BIO *out, PCCERT_CONTEXT cert) { X509 *x; unsigned char *p; unsigned long flags = ctx->dump_flags; if (flags & CAPI_DMP_FNAME) { char *fname; fname = capi_cert_get_fname(ctx, cert); if (fname) { BIO_printf(out, " Friendly Name \"%s\"\n", fname); OPENSSL_free(fname); } else BIO_printf(out, " <No Friendly Name>\n"); } p = cert->pbCertEncoded; x = d2i_X509(NULL, &p, cert->cbCertEncoded); if (!x) BIO_printf(out, " <Can't parse certificate>\n"); if (flags & CAPI_DMP_SUMMARY) { BIO_printf(out, " Subject: "); X509_NAME_print_ex(out, X509_get_subject_name(x), 0, XN_FLAG_ONELINE); BIO_printf(out, "\n Issuer: "); X509_NAME_print_ex(out, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE); BIO_printf(out, "\n"); } if (flags & CAPI_DMP_FULL) X509_print_ex(out, x, XN_FLAG_ONELINE,0); if (flags & CAPI_DMP_PKEYINFO) { CRYPT_KEY_PROV_INFO *pinfo; pinfo = capi_get_prov_info(ctx, cert); capi_dump_prov_info(ctx, out, pinfo); if (pinfo) OPENSSL_free(pinfo); } if (flags & CAPI_DMP_PEM) PEM_write_bio_X509(out, x); X509_free(x); } HCERTSTORE capi_open_store(CAPI_CTX *ctx, char *storename) { HCERTSTORE hstore; if (!storename) storename = ctx->storename; if (!storename) storename = "MY"; CAPI_trace(ctx, "Opening certificate store %s\n", storename); hstore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0, ctx->store_flags, storename); if (!hstore) { CAPIerr(CAPI_F_CAPI_OPEN_STORE, CAPI_R_ERROR_OPENING_STORE); capi_addlasterror(); } return hstore; } int capi_list_certs(CAPI_CTX *ctx, BIO *out, char *id) { char *storename; int idx; int ret = 1; HCERTSTORE hstore; PCCERT_CONTEXT cert = NULL; storename = ctx->storename; if (!storename) storename = "MY"; CAPI_trace(ctx, "Listing certs for store %s\n", storename); hstore = capi_open_store(ctx, storename); if (!hstore) return 0; if (id) { cert = capi_find_cert(ctx, id, hstore); if (!cert) { ret = 0; goto err; } capi_dump_cert(ctx, out, cert); CertFreeCertificateContext(cert); } else { for(idx = 0;;idx++) { LPWSTR fname = NULL; cert = CertEnumCertificatesInStore(hstore, cert); if (!cert) break; BIO_printf(out, "Certificate %d\n", idx); capi_dump_cert(ctx, out, cert); } } err: CertCloseStore(hstore, 0); return ret; } static PCCERT_CONTEXT capi_find_cert(CAPI_CTX *ctx, const char *id, HCERTSTORE hstore) { PCCERT_CONTEXT cert = NULL; char *fname = NULL; int match; switch(ctx->lookup_method) { case CAPI_LU_SUBSTR: return CertFindCertificateInStore(hstore, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR_A, id, NULL); case CAPI_LU_FNAME: for(;;) { cert = CertEnumCertificatesInStore(hstore, cert); if (!cert) return NULL; fname = capi_cert_get_fname(ctx, cert); if (fname) { if (strcmp(fname, id)) match = 0; else match = 1; OPENSSL_free(fname); if (match) return cert; } } default: return NULL; } } static CAPI_KEY *capi_get_key(CAPI_CTX *ctx, const char *contname, char *provname, DWORD ptype, DWORD keyspec) { CAPI_KEY *key; key = OPENSSL_malloc(sizeof(CAPI_KEY)); CAPI_trace(ctx, "capi_get_key, contname=%s, provname=%s, type=%d\n", contname, provname, ptype); if (!CryptAcquireContextA(&key->hprov, contname, provname, ptype, 0)) { CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_CRYPTACQUIRECONTEXT_ERROR); capi_addlasterror(); goto err; } if (!CryptGetUserKey(key->hprov, keyspec, &key->key)) { CAPIerr(CAPI_F_CAPI_GET_KEY, CAPI_R_GETUSERKEY_ERROR); capi_addlasterror(); CryptReleaseContext(key->hprov, 0); goto err; } key->keyspec = keyspec; key->pcert = NULL; return key; err: OPENSSL_free(key); return NULL; } static CAPI_KEY *capi_get_cert_key(CAPI_CTX *ctx, PCCERT_CONTEXT cert) { CAPI_KEY *key = NULL; CRYPT_KEY_PROV_INFO *pinfo = NULL; char *provname = NULL, *contname = NULL; pinfo = capi_get_prov_info(ctx, cert); if (!pinfo) goto err; provname = wide_to_asc(pinfo->pwszProvName); contname = wide_to_asc(pinfo->pwszContainerName); if (!provname || !contname) goto err; key = capi_get_key(ctx, contname, provname, pinfo->dwProvType, pinfo->dwKeySpec); err: if (pinfo) OPENSSL_free(pinfo); if (provname) OPENSSL_free(provname); if (contname) OPENSSL_free(contname); return key; } CAPI_KEY *capi_find_key(CAPI_CTX *ctx, const char *id) { PCCERT_CONTEXT cert; HCERTSTORE hstore; CAPI_KEY *key = NULL; switch (ctx->lookup_method) { case CAPI_LU_SUBSTR: case CAPI_LU_FNAME: hstore = capi_open_store(ctx, NULL); if (!hstore) return NULL; cert = capi_find_cert(ctx, id, hstore); if (cert) { key = capi_get_cert_key(ctx, cert); CertFreeCertificateContext(cert); } CertCloseStore(hstore, 0); break; case CAPI_LU_CONTNAME: key = capi_get_key(ctx, id, ctx->cspname, ctx->csptype, ctx->keytype); break; } return key; } void capi_free_key(CAPI_KEY *key) { if (!key) return; CryptDestroyKey(key->key); CryptReleaseContext(key->hprov, 0); if (key->pcert) CertFreeCertificateContext(key->pcert); OPENSSL_free(key); } /* Initialize a CAPI_CTX structure */ static CAPI_CTX *capi_ctx_new() { CAPI_CTX *ctx; ctx = OPENSSL_malloc(sizeof(CAPI_CTX)); if (!ctx) { CAPIerr(CAPI_F_CAPI_CTX_NEW, ERR_R_MALLOC_FAILURE); return NULL; } ctx->cspname = NULL; ctx->csptype = PROV_RSA_FULL; ctx->dump_flags = CAPI_DMP_SUMMARY|CAPI_DMP_FNAME; ctx->keytype = AT_KEYEXCHANGE; ctx->storename = NULL; ctx->ssl_client_store = NULL; ctx->store_flags = CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_CURRENT_USER; ctx->lookup_method = CAPI_LU_SUBSTR; ctx->debug_level = 0; ctx->debug_file = NULL; ctx->client_cert_select = cert_select_simple; return ctx; } static void capi_ctx_free(CAPI_CTX *ctx) { CAPI_trace(ctx, "Calling capi_ctx_free with %lx\n", ctx); if (!ctx) return; if (ctx->cspname) OPENSSL_free(ctx->cspname); if (ctx->debug_file) OPENSSL_free(ctx->debug_file); if (ctx->storename) OPENSSL_free(ctx->storename); if (ctx->ssl_client_store) OPENSSL_free(ctx->ssl_client_store); OPENSSL_free(ctx); } static int capi_ctx_set_provname(CAPI_CTX *ctx, LPSTR pname, DWORD type, int check) { CAPI_trace(ctx, "capi_ctx_set_provname, name=%s, type=%d\n", pname, type); if (check) { HCRYPTPROV hprov; if (!CryptAcquireContextA(&hprov, NULL, pname, type, CRYPT_VERIFYCONTEXT)) { CAPIerr(CAPI_F_CAPI_CTX_SET_PROVNAME, CAPI_R_CRYPTACQUIRECONTEXT_ERROR); capi_addlasterror(); return 0; } CryptReleaseContext(hprov, 0); } ctx->cspname = BUF_strdup(pname); ctx->csptype = type; return 1; } static int capi_ctx_set_provname_idx(CAPI_CTX *ctx, int idx) { LPSTR pname; DWORD type; if (capi_get_provname(ctx, &pname, &type, idx) != 1) return 0; return capi_ctx_set_provname(ctx, pname, type, 0); } static int cert_issuer_match(STACK_OF(X509_NAME) *ca_dn, X509 *x) { int i; X509_NAME *nm; /* Special case: empty list: match anything */ if (sk_X509_NAME_num(ca_dn) <= 0) return 1; for (i = 0; i < sk_X509_NAME_num(ca_dn); i++) { nm = sk_X509_NAME_value(ca_dn, i); if (!X509_NAME_cmp(nm, X509_get_issuer_name(x))) return 1; } return 0; } static int capi_load_ssl_client_cert(ENGINE *e, SSL *ssl, STACK_OF(X509_NAME) *ca_dn, X509 **pcert, EVP_PKEY **pkey, STACK_OF(X509) **pother, UI_METHOD *ui_method, void *callback_data) { STACK_OF(X509) *certs = NULL; X509 *x; char *storename; const char *p; int i, client_cert_idx; HCERTSTORE hstore; PCCERT_CONTEXT cert = NULL, excert = NULL; CAPI_CTX *ctx; CAPI_KEY *key; ctx = ENGINE_get_ex_data(e, capi_idx); *pcert = NULL; *pkey = NULL; storename = ctx->ssl_client_store; if (!storename) storename = "MY"; hstore = capi_open_store(ctx, storename); if (!hstore) return 0; /* Enumerate all certificates collect any matches */ for(i = 0;;i++) { cert = CertEnumCertificatesInStore(hstore, cert); if (!cert) break; p = cert->pbCertEncoded; x = d2i_X509(NULL, &p, cert->cbCertEncoded); if (!x) { CAPI_trace(ctx, "Can't Parse Certificate %d\n", i); continue; } if (cert_issuer_match(ca_dn, x) && X509_check_purpose(x, X509_PURPOSE_SSL_CLIENT, 0)) { key = capi_get_cert_key(ctx, cert); if (!key) { X509_free(x); continue; } /* Match found: attach extra data to it so * we can retrieve the key later. */ excert = CertDuplicateCertificateContext(cert); key->pcert = excert; X509_set_ex_data(x, cert_capi_idx, key); if (!certs) certs = sk_X509_new_null(); sk_X509_push(certs, x); } else X509_free(x); } if (cert) CertFreeCertificateContext(cert); if (hstore) CertCloseStore(hstore, 0); if (!certs) return 0; /* Select the appropriate certificate */ client_cert_idx = ctx->client_cert_select(e, ssl, certs); /* Set the selected certificate and free the rest */ for(i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (i == client_cert_idx) *pcert = x; else { key = X509_get_ex_data(x, cert_capi_idx); capi_free_key(key); X509_free(x); } } sk_X509_free(certs); if (!*pcert) return 0; /* Setup key for selected certificate */ key = X509_get_ex_data(*pcert, cert_capi_idx); *pkey = capi_get_pkey(e, key); X509_set_ex_data(*pcert, cert_capi_idx, NULL); return 1; } /* Simple client cert selection function: always select first */ static int cert_select_simple(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs) { return 0; } #ifdef OPENSSL_CAPIENG_DIALOG /* More complex cert selection function, using standard function * CryptUIDlgSelectCertificateFromStore() to produce a dialog box. */ /* Definitions which are in cryptuiapi.h but this is not present in older * versions of headers. */ #ifndef CRYPTUI_SELECT_LOCATION_COLUMN #define CRYPTUI_SELECT_LOCATION_COLUMN 0x000000010 #define CRYPTUI_SELECT_INTENDEDUSE_COLUMN 0x000000004 #endif #define dlg_title L"OpenSSL Application SSL Client Certificate Selection" #define dlg_prompt L"Select a certificate to use for authentication" #define dlg_columns CRYPTUI_SELECT_LOCATION_COLUMN \ |CRYPTUI_SELECT_INTENDEDUSE_COLUMN static int cert_select_dialog(ENGINE *e, SSL *ssl, STACK_OF(X509) *certs) { X509 *x; HCERTSTORE dstore; PCCERT_CONTEXT cert; CAPI_CTX *ctx; CAPI_KEY *key; HWND hwnd; int i, idx = -1; if (sk_X509_num(certs) == 1) return 0; ctx = ENGINE_get_ex_data(e, capi_idx); /* Create an in memory store of certificates */ dstore = CertOpenStore(CERT_STORE_PROV_MEMORY, 0, 0, CERT_STORE_CREATE_NEW_FLAG, NULL); if (!dstore) { CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_CREATING_STORE); capi_addlasterror(); goto err; } /* Add all certificates to store */ for(i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); key = X509_get_ex_data(x, cert_capi_idx); if (!CertAddCertificateContextToStore(dstore, key->pcert, CERT_STORE_ADD_NEW, NULL)) { CAPIerr(CAPI_F_CERT_SELECT_DIALOG, CAPI_R_ERROR_ADDING_CERT); capi_addlasterror(); goto err; } } hwnd = GetForegroundWindow(); if (!hwnd) hwnd = GetActiveWindow(); if (!hwnd && ctx->getconswindow) hwnd = ctx->getconswindow(); /* Call dialog to select one */ cert = ctx->certselectdlg(dstore, hwnd, dlg_title, dlg_prompt, dlg_columns, 0, NULL); /* Find matching cert from list */ if (cert) { for(i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); key = X509_get_ex_data(x, cert_capi_idx); if (CertCompareCertificate( X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert->pCertInfo, key->pcert->pCertInfo)) { idx = i; break; } } } err: if (dstore) CertCloseStore(dstore, 0); return idx; } #endif #else /* !__COMPILE_CAPIENG */ #include <openssl/engine.h> #ifndef OPENSSL_NO_DYNAMIC_ENGINE OPENSSL_EXPORT int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); OPENSSL_EXPORT int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { return 0; } IMPLEMENT_DYNAMIC_CHECK_FN() #else void ENGINE_load_capi(void){} #endif #endif
the_stack_data/130740.c
extern const unsigned char Pods_BCryptVersionString[]; extern const double Pods_BCryptVersionNumber; const unsigned char Pods_BCryptVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:Pods_BCrypt PROJECT:Pods-1" "\n"; const double Pods_BCryptVersionNumber __attribute__ ((used)) = (double)1.;
the_stack_data/40762239.c
#include "stdio.h" unsigned long crc_table[256]; int crc_table_computed = 0; typedef unsigned long DWORD; void make_crc_table(void) { unsigned long c; int n, k; for (n = 0; n < 256; n++) { c = (unsigned long)n; for (k = 0; k < 8; k++) { if (c & 1) c = 0xedb88320L ^ (c >> 1); else c = c >> 1; } crc_table[n] = c; } crc_table_computed = 1; } unsigned long update_crc(unsigned long crc, unsigned char* buf, int len) { unsigned long c = crc; int n; if (!crc_table_computed) make_crc_table(); for (n = 0; n < len; n++) { c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); } return c; } /* Return the CRC of the bytes buf[0..len-1]. */ unsigned long crc(unsigned char* buf, int len) { return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL; } int main() { unsigned char IHDR[] = "\xDE\xAD\xBE\xEF\xDE\xAD\xBE\xEF\xDE\xAD\xBE\xEF\xDE\xAD\xBE\xEF\xDE"; unsigned int w, h, i; unsigned int target_crc = 0x69696969; int max = 100000; for (w = 0; w < max; w++) { for (h = 0; h < max; h++) { *(DWORD*)&IHDR[4] = w; __asm__("bswap %0" : "+r" (*(DWORD*)&IHDR[4])); *(DWORD*)&IHDR[8] = h; __asm__("bswap %0" : "+r" (*(DWORD*)&IHDR[8])); //60 44 4c b6 if (crc(IHDR, 17) == target_crc) { printf("W:%d H:%d\n", w, h); return 0; } } } return 1; }
the_stack_data/150142453.c
/** ****************************************************************************** * @file Templates/Src/stm32f1xx_hal_msp.c * @author MCD Application Team * @version V1.4.0 * @date 29-April-2016 * @brief HAL MSP module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ /** @addtogroup STM32F1xx_HAL_Examples * @{ */ /** @addtogroup Templates * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup HAL_MSP_Private_Functions * @{ */ /** * @brief Initializes the Global MSP. * @param None * @retval None */ void HAL_MspInit(void) { } /** * @brief DeInitializes the Global MSP. * @param None * @retval None */ void HAL_MspDeInit(void) { } /** * @brief Initializes the PPP MSP. * @param None * @retval None */ /*void HAL_PPP_MspInit(void) {*/ /*}*/ /** * @brief DeInitializes the PPP MSP. * @param None * @retval None */ /*void HAL_PPP_MspDeInit(void) {*/ /*}*/ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/212642454.c
/* Autogenerated: 'src/ExtractionOCaml/bedrock2_unsaturated_solinas' --lang bedrock2 --static --no-wide-int --widen-carry --widen-bytes --split-multiret --no-select 25519 64 '(auto)' '2^255 - 19' carry_mul carry_square carry add sub opp selectznz to_bytes from_bytes carry_scmul121666 */ /* curve description: 25519 */ /* machine_wordsize = 64 (from "64") */ /* requested operations: carry_mul, carry_square, carry, add, sub, opp, selectznz, to_bytes, from_bytes, carry_scmul121666 */ /* n = 5 (from "(auto)") */ /* s-c = 2^255 - [(1, 19)] (from "2^255 - 19") */ /* tight_bounds_multiplier = 1 (from "") */ /* */ /* Computed values: */ /* carry_chain = [0, 1, 2, 3, 4, 0, 1] */ /* eval z = z[0] + (z[1] << 51) + (z[2] << 102) + (z[3] << 153) + (z[4] << 204) */ /* bytes_eval z = z[0] + (z[1] << 8) + (z[2] << 16) + (z[3] << 24) + (z[4] << 32) + (z[5] << 40) + (z[6] << 48) + (z[7] << 56) + (z[8] << 64) + (z[9] << 72) + (z[10] << 80) + (z[11] << 88) + (z[12] << 96) + (z[13] << 104) + (z[14] << 112) + (z[15] << 120) + (z[16] << 128) + (z[17] << 136) + (z[18] << 144) + (z[19] << 152) + (z[20] << 160) + (z[21] << 168) + (z[22] << 176) + (z[23] << 184) + (z[24] << 192) + (z[25] << 200) + (z[26] << 208) + (z[27] << 216) + (z[28] << 224) + (z[29] << 232) + (z[30] << 240) + (z[31] << 248) */ /* balance = [0xfffffffffffda, 0xffffffffffffe, 0xffffffffffffe, 0xffffffffffffe, 0xffffffffffffe] */ #include <stdint.h> #include <memory.h> // LITTLE-ENDIAN memory access is REQUIRED // the following two functions are required to work around -fstrict-aliasing static inline uintptr_t _br2_load(uintptr_t a, size_t sz) { uintptr_t r = 0; memcpy(&r, (void*)a, sz); return r; } static inline void _br2_store(uintptr_t a, uintptr_t v, size_t sz) { memcpy((void*)a, &v, sz); } /* * Input Bounds: * in0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] * in1: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] */ static void internal_fiat_25519_carry_mul(uintptr_t out0, uintptr_t in0, uintptr_t in1) { uintptr_t x4, x3, x2, x1, x9, x8, x7, x6, x0, x5, x16, x22, x61, x23, x62, x17, x60, x26, x65, x27, x66, x63, x64, x28, x69, x29, x70, x67, x68, x58, x73, x59, x74, x71, x75, x72, x30, x32, x79, x33, x80, x31, x78, x36, x83, x37, x84, x81, x82, x42, x87, x43, x88, x85, x86, x50, x91, x51, x92, x89, x10, x34, x95, x35, x96, x11, x94, x38, x99, x39, x100, x97, x98, x44, x103, x45, x104, x101, x102, x52, x107, x53, x108, x105, x12, x18, x111, x19, x112, x13, x110, x40, x115, x41, x116, x113, x114, x46, x119, x47, x120, x117, x118, x54, x123, x55, x124, x121, x14, x20, x127, x21, x128, x15, x126, x24, x131, x25, x132, x129, x130, x48, x135, x49, x136, x133, x134, x56, x139, x57, x140, x137, x138, x76, x143, x141, x144, x142, x122, x145, x148, x125, x149, x147, x106, x150, x153, x109, x154, x152, x90, x155, x158, x93, x159, x157, x160, x77, x162, x163, x164, x146, x166, x167, x151, x165, x168, x169, x156, x161, x170, x171, x172, x173, x174; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ x5 = _br2_load((in1)+((uintptr_t)0ULL), sizeof(uintptr_t)); x6 = _br2_load((in1)+((uintptr_t)8ULL), sizeof(uintptr_t)); x7 = _br2_load((in1)+((uintptr_t)16ULL), sizeof(uintptr_t)); x8 = _br2_load((in1)+((uintptr_t)24ULL), sizeof(uintptr_t)); x9 = _br2_load((in1)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x10 = (x4)*((x9)*((uintptr_t)19ULL)); x11 = sizeof(intptr_t) == 4 ? ((uint64_t)(x4)*((x9)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x4)*((x9)*((uintptr_t)19ULL)))>>64; x12 = (x4)*((x8)*((uintptr_t)19ULL)); x13 = sizeof(intptr_t) == 4 ? ((uint64_t)(x4)*((x8)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x4)*((x8)*((uintptr_t)19ULL)))>>64; x14 = (x4)*((x7)*((uintptr_t)19ULL)); x15 = sizeof(intptr_t) == 4 ? ((uint64_t)(x4)*((x7)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x4)*((x7)*((uintptr_t)19ULL)))>>64; x16 = (x4)*((x6)*((uintptr_t)19ULL)); x17 = sizeof(intptr_t) == 4 ? ((uint64_t)(x4)*((x6)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x4)*((x6)*((uintptr_t)19ULL)))>>64; x18 = (x3)*((x9)*((uintptr_t)19ULL)); x19 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*((x9)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x3)*((x9)*((uintptr_t)19ULL)))>>64; x20 = (x3)*((x8)*((uintptr_t)19ULL)); x21 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*((x8)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x3)*((x8)*((uintptr_t)19ULL)))>>64; x22 = (x3)*((x7)*((uintptr_t)19ULL)); x23 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*((x7)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x3)*((x7)*((uintptr_t)19ULL)))>>64; x24 = (x2)*((x9)*((uintptr_t)19ULL)); x25 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*((x9)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x2)*((x9)*((uintptr_t)19ULL)))>>64; x26 = (x2)*((x8)*((uintptr_t)19ULL)); x27 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*((x8)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x2)*((x8)*((uintptr_t)19ULL)))>>64; x28 = (x1)*((x9)*((uintptr_t)19ULL)); x29 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*((x9)*((uintptr_t)19ULL)))>>32 : ((__uint128_t)(x1)*((x9)*((uintptr_t)19ULL)))>>64; x30 = (x4)*(x5); x31 = sizeof(intptr_t) == 4 ? ((uint64_t)(x4)*(x5))>>32 : ((__uint128_t)(x4)*(x5))>>64; x32 = (x3)*(x6); x33 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*(x6))>>32 : ((__uint128_t)(x3)*(x6))>>64; x34 = (x3)*(x5); x35 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*(x5))>>32 : ((__uint128_t)(x3)*(x5))>>64; x36 = (x2)*(x7); x37 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*(x7))>>32 : ((__uint128_t)(x2)*(x7))>>64; x38 = (x2)*(x6); x39 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*(x6))>>32 : ((__uint128_t)(x2)*(x6))>>64; x40 = (x2)*(x5); x41 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*(x5))>>32 : ((__uint128_t)(x2)*(x5))>>64; x42 = (x1)*(x8); x43 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x8))>>32 : ((__uint128_t)(x1)*(x8))>>64; x44 = (x1)*(x7); x45 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x7))>>32 : ((__uint128_t)(x1)*(x7))>>64; x46 = (x1)*(x6); x47 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x6))>>32 : ((__uint128_t)(x1)*(x6))>>64; x48 = (x1)*(x5); x49 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x5))>>32 : ((__uint128_t)(x1)*(x5))>>64; x50 = (x0)*(x9); x51 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x9))>>32 : ((__uint128_t)(x0)*(x9))>>64; x52 = (x0)*(x8); x53 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x8))>>32 : ((__uint128_t)(x0)*(x8))>>64; x54 = (x0)*(x7); x55 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x7))>>32 : ((__uint128_t)(x0)*(x7))>>64; x56 = (x0)*(x6); x57 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x6))>>32 : ((__uint128_t)(x0)*(x6))>>64; x58 = (x0)*(x5); x59 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x5))>>32 : ((__uint128_t)(x0)*(x5))>>64; x60 = (x22)+(x16); x61 = (x60)<(x22); x62 = (x61)+(x23); x63 = (x62)+(x17); x64 = (x26)+(x60); x65 = (x64)<(x26); x66 = (x65)+(x27); x67 = (x66)+(x63); x68 = (x28)+(x64); x69 = (x68)<(x28); x70 = (x69)+(x29); x71 = (x70)+(x67); x72 = (x58)+(x68); x73 = (x72)<(x58); x74 = (x73)+(x59); x75 = (x74)+(x71); x76 = ((x72)>>((uintptr_t)51ULL))|((x75)<<((uintptr_t)13ULL)); x77 = (x72)&((uintptr_t)2251799813685247ULL); x78 = (x32)+(x30); x79 = (x78)<(x32); x80 = (x79)+(x33); x81 = (x80)+(x31); x82 = (x36)+(x78); x83 = (x82)<(x36); x84 = (x83)+(x37); x85 = (x84)+(x81); x86 = (x42)+(x82); x87 = (x86)<(x42); x88 = (x87)+(x43); x89 = (x88)+(x85); x90 = (x50)+(x86); x91 = (x90)<(x50); x92 = (x91)+(x51); x93 = (x92)+(x89); x94 = (x34)+(x10); x95 = (x94)<(x34); x96 = (x95)+(x35); x97 = (x96)+(x11); x98 = (x38)+(x94); x99 = (x98)<(x38); x100 = (x99)+(x39); x101 = (x100)+(x97); x102 = (x44)+(x98); x103 = (x102)<(x44); x104 = (x103)+(x45); x105 = (x104)+(x101); x106 = (x52)+(x102); x107 = (x106)<(x52); x108 = (x107)+(x53); x109 = (x108)+(x105); x110 = (x18)+(x12); x111 = (x110)<(x18); x112 = (x111)+(x19); x113 = (x112)+(x13); x114 = (x40)+(x110); x115 = (x114)<(x40); x116 = (x115)+(x41); x117 = (x116)+(x113); x118 = (x46)+(x114); x119 = (x118)<(x46); x120 = (x119)+(x47); x121 = (x120)+(x117); x122 = (x54)+(x118); x123 = (x122)<(x54); x124 = (x123)+(x55); x125 = (x124)+(x121); x126 = (x20)+(x14); x127 = (x126)<(x20); x128 = (x127)+(x21); x129 = (x128)+(x15); x130 = (x24)+(x126); x131 = (x130)<(x24); x132 = (x131)+(x25); x133 = (x132)+(x129); x134 = (x48)+(x130); x135 = (x134)<(x48); x136 = (x135)+(x49); x137 = (x136)+(x133); x138 = (x56)+(x134); x139 = (x138)<(x56); x140 = (x139)+(x57); x141 = (x140)+(x137); x142 = (x76)+(x138); x143 = (x142)<(x76); x144 = (x143)+(x141); x145 = ((x142)>>((uintptr_t)51ULL))|((x144)<<((uintptr_t)13ULL)); x146 = (x142)&((uintptr_t)2251799813685247ULL); x147 = (x145)+(x122); x148 = (x147)<(x145); x149 = (x148)+(x125); x150 = ((x147)>>((uintptr_t)51ULL))|((x149)<<((uintptr_t)13ULL)); x151 = (x147)&((uintptr_t)2251799813685247ULL); x152 = (x150)+(x106); x153 = (x152)<(x150); x154 = (x153)+(x109); x155 = ((x152)>>((uintptr_t)51ULL))|((x154)<<((uintptr_t)13ULL)); x156 = (x152)&((uintptr_t)2251799813685247ULL); x157 = (x155)+(x90); x158 = (x157)<(x155); x159 = (x158)+(x93); x160 = ((x157)>>((uintptr_t)51ULL))|((x159)<<((uintptr_t)13ULL)); x161 = (x157)&((uintptr_t)2251799813685247ULL); x162 = (x160)*((uintptr_t)19ULL); x163 = (x77)+(x162); x164 = (x163)>>((uintptr_t)51ULL); x165 = (x163)&((uintptr_t)2251799813685247ULL); x166 = (x164)+(x146); x167 = (x166)>>((uintptr_t)51ULL); x168 = (x166)&((uintptr_t)2251799813685247ULL); x169 = (x167)+(x151); x170 = x165; x171 = x168; x172 = x169; x173 = x156; x174 = x161; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x170, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x171, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x172, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x173, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x174, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_carry_mul(uint64_t out1[5], const uint64_t arg1[5], const uint64_t arg2[5]) { internal_fiat_25519_carry_mul((uintptr_t)out1, (uintptr_t)arg1, (uintptr_t)arg2); } /* * Input Bounds: * in0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] */ static void internal_fiat_25519_carry_square(uintptr_t out0, uintptr_t in0) { uintptr_t x4, x5, x3, x8, x9, x2, x6, x1, x7, x10, x11, x12, x0, x21, x25, x44, x26, x45, x22, x43, x41, x48, x42, x49, x46, x50, x47, x23, x27, x54, x28, x55, x24, x53, x33, x58, x34, x59, x56, x13, x29, x62, x30, x63, x14, x61, x35, x66, x36, x67, x64, x15, x31, x70, x32, x71, x16, x69, x37, x74, x38, x75, x72, x17, x19, x78, x20, x79, x18, x77, x39, x82, x40, x83, x80, x81, x51, x86, x84, x87, x85, x73, x88, x91, x76, x92, x90, x65, x93, x96, x68, x97, x95, x57, x98, x101, x60, x102, x100, x103, x52, x105, x106, x107, x89, x109, x110, x94, x108, x111, x112, x99, x104, x113, x114, x115, x116, x117; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x5 = (x4)*((uintptr_t)19ULL); x6 = (x5)*((uintptr_t)2ULL); x7 = (x4)*((uintptr_t)2ULL); x8 = (x3)*((uintptr_t)19ULL); x9 = (x8)*((uintptr_t)2ULL); x10 = (x3)*((uintptr_t)2ULL); x11 = (x2)*((uintptr_t)2ULL); x12 = (x1)*((uintptr_t)2ULL); x13 = (x4)*(x5); x14 = sizeof(intptr_t) == 4 ? ((uint64_t)(x4)*(x5))>>32 : ((__uint128_t)(x4)*(x5))>>64; x15 = (x3)*(x6); x16 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*(x6))>>32 : ((__uint128_t)(x3)*(x6))>>64; x17 = (x3)*(x8); x18 = sizeof(intptr_t) == 4 ? ((uint64_t)(x3)*(x8))>>32 : ((__uint128_t)(x3)*(x8))>>64; x19 = (x2)*(x6); x20 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*(x6))>>32 : ((__uint128_t)(x2)*(x6))>>64; x21 = (x2)*(x9); x22 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*(x9))>>32 : ((__uint128_t)(x2)*(x9))>>64; x23 = (x2)*(x2); x24 = sizeof(intptr_t) == 4 ? ((uint64_t)(x2)*(x2))>>32 : ((__uint128_t)(x2)*(x2))>>64; x25 = (x1)*(x6); x26 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x6))>>32 : ((__uint128_t)(x1)*(x6))>>64; x27 = (x1)*(x10); x28 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x10))>>32 : ((__uint128_t)(x1)*(x10))>>64; x29 = (x1)*(x11); x30 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x11))>>32 : ((__uint128_t)(x1)*(x11))>>64; x31 = (x1)*(x1); x32 = sizeof(intptr_t) == 4 ? ((uint64_t)(x1)*(x1))>>32 : ((__uint128_t)(x1)*(x1))>>64; x33 = (x0)*(x7); x34 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x7))>>32 : ((__uint128_t)(x0)*(x7))>>64; x35 = (x0)*(x10); x36 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x10))>>32 : ((__uint128_t)(x0)*(x10))>>64; x37 = (x0)*(x11); x38 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x11))>>32 : ((__uint128_t)(x0)*(x11))>>64; x39 = (x0)*(x12); x40 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x12))>>32 : ((__uint128_t)(x0)*(x12))>>64; x41 = (x0)*(x0); x42 = sizeof(intptr_t) == 4 ? ((uint64_t)(x0)*(x0))>>32 : ((__uint128_t)(x0)*(x0))>>64; x43 = (x25)+(x21); x44 = (x43)<(x25); x45 = (x44)+(x26); x46 = (x45)+(x22); x47 = (x41)+(x43); x48 = (x47)<(x41); x49 = (x48)+(x42); x50 = (x49)+(x46); x51 = ((x47)>>((uintptr_t)51ULL))|((x50)<<((uintptr_t)13ULL)); x52 = (x47)&((uintptr_t)2251799813685247ULL); x53 = (x27)+(x23); x54 = (x53)<(x27); x55 = (x54)+(x28); x56 = (x55)+(x24); x57 = (x33)+(x53); x58 = (x57)<(x33); x59 = (x58)+(x34); x60 = (x59)+(x56); x61 = (x29)+(x13); x62 = (x61)<(x29); x63 = (x62)+(x30); x64 = (x63)+(x14); x65 = (x35)+(x61); x66 = (x65)<(x35); x67 = (x66)+(x36); x68 = (x67)+(x64); x69 = (x31)+(x15); x70 = (x69)<(x31); x71 = (x70)+(x32); x72 = (x71)+(x16); x73 = (x37)+(x69); x74 = (x73)<(x37); x75 = (x74)+(x38); x76 = (x75)+(x72); x77 = (x19)+(x17); x78 = (x77)<(x19); x79 = (x78)+(x20); x80 = (x79)+(x18); x81 = (x39)+(x77); x82 = (x81)<(x39); x83 = (x82)+(x40); x84 = (x83)+(x80); x85 = (x51)+(x81); x86 = (x85)<(x51); x87 = (x86)+(x84); x88 = ((x85)>>((uintptr_t)51ULL))|((x87)<<((uintptr_t)13ULL)); x89 = (x85)&((uintptr_t)2251799813685247ULL); x90 = (x88)+(x73); x91 = (x90)<(x88); x92 = (x91)+(x76); x93 = ((x90)>>((uintptr_t)51ULL))|((x92)<<((uintptr_t)13ULL)); x94 = (x90)&((uintptr_t)2251799813685247ULL); x95 = (x93)+(x65); x96 = (x95)<(x93); x97 = (x96)+(x68); x98 = ((x95)>>((uintptr_t)51ULL))|((x97)<<((uintptr_t)13ULL)); x99 = (x95)&((uintptr_t)2251799813685247ULL); x100 = (x98)+(x57); x101 = (x100)<(x98); x102 = (x101)+(x60); x103 = ((x100)>>((uintptr_t)51ULL))|((x102)<<((uintptr_t)13ULL)); x104 = (x100)&((uintptr_t)2251799813685247ULL); x105 = (x103)*((uintptr_t)19ULL); x106 = (x52)+(x105); x107 = (x106)>>((uintptr_t)51ULL); x108 = (x106)&((uintptr_t)2251799813685247ULL); x109 = (x107)+(x89); x110 = (x109)>>((uintptr_t)51ULL); x111 = (x109)&((uintptr_t)2251799813685247ULL); x112 = (x110)+(x94); x113 = x108; x114 = x111; x115 = x112; x116 = x99; x117 = x104; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x113, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x114, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x115, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x116, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x117, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_carry_square(uint64_t out1[5], const uint64_t arg1[5]) { internal_fiat_25519_carry_square((uintptr_t)out1, (uintptr_t)arg1); } /* * Input Bounds: * in0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] */ static void internal_fiat_25519_carry(uintptr_t out0, uintptr_t in0) { uintptr_t x0, x1, x2, x3, x4, x5, x6, x10, x11, x7, x8, x9, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x5 = x0; x6 = ((x5)>>((uintptr_t)51ULL))+(x1); x7 = ((x6)>>((uintptr_t)51ULL))+(x2); x8 = ((x7)>>((uintptr_t)51ULL))+(x3); x9 = ((x8)>>((uintptr_t)51ULL))+(x4); x10 = ((x5)&((uintptr_t)2251799813685247ULL))+(((x9)>>((uintptr_t)51ULL))*((uintptr_t)19ULL)); x11 = ((x10)>>((uintptr_t)51ULL))+((x6)&((uintptr_t)2251799813685247ULL)); x12 = (x10)&((uintptr_t)2251799813685247ULL); x13 = (x11)&((uintptr_t)2251799813685247ULL); x14 = ((x11)>>((uintptr_t)51ULL))+((x7)&((uintptr_t)2251799813685247ULL)); x15 = (x8)&((uintptr_t)2251799813685247ULL); x16 = (x9)&((uintptr_t)2251799813685247ULL); x17 = x12; x18 = x13; x19 = x14; x20 = x15; x21 = x16; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x17, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x18, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x19, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x20, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x21, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_carry(uint64_t out1[5], const uint64_t arg1[5]) { internal_fiat_25519_carry((uintptr_t)out1, (uintptr_t)arg1); } /* * Input Bounds: * in0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] * in1: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] */ static void internal_fiat_25519_add(uintptr_t out0, uintptr_t in0, uintptr_t in1) { uintptr_t x0, x5, x1, x6, x2, x7, x3, x8, x4, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ x5 = _br2_load((in1)+((uintptr_t)0ULL), sizeof(uintptr_t)); x6 = _br2_load((in1)+((uintptr_t)8ULL), sizeof(uintptr_t)); x7 = _br2_load((in1)+((uintptr_t)16ULL), sizeof(uintptr_t)); x8 = _br2_load((in1)+((uintptr_t)24ULL), sizeof(uintptr_t)); x9 = _br2_load((in1)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x10 = (x0)+(x5); x11 = (x1)+(x6); x12 = (x2)+(x7); x13 = (x3)+(x8); x14 = (x4)+(x9); x15 = x10; x16 = x11; x17 = x12; x18 = x13; x19 = x14; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x15, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x16, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x17, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x18, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x19, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_add(uint64_t out1[5], const uint64_t arg1[5], const uint64_t arg2[5]) { internal_fiat_25519_add((uintptr_t)out1, (uintptr_t)arg1, (uintptr_t)arg2); } /* * Input Bounds: * in0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] * in1: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] */ static void internal_fiat_25519_sub(uintptr_t out0, uintptr_t in0, uintptr_t in1) { uintptr_t x0, x5, x1, x6, x2, x7, x3, x8, x4, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ x5 = _br2_load((in1)+((uintptr_t)0ULL), sizeof(uintptr_t)); x6 = _br2_load((in1)+((uintptr_t)8ULL), sizeof(uintptr_t)); x7 = _br2_load((in1)+((uintptr_t)16ULL), sizeof(uintptr_t)); x8 = _br2_load((in1)+((uintptr_t)24ULL), sizeof(uintptr_t)); x9 = _br2_load((in1)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x10 = (((uintptr_t)4503599627370458ULL)+(x0))-(x5); x11 = (((uintptr_t)4503599627370494ULL)+(x1))-(x6); x12 = (((uintptr_t)4503599627370494ULL)+(x2))-(x7); x13 = (((uintptr_t)4503599627370494ULL)+(x3))-(x8); x14 = (((uintptr_t)4503599627370494ULL)+(x4))-(x9); x15 = x10; x16 = x11; x17 = x12; x18 = x13; x19 = x14; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x15, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x16, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x17, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x18, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x19, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_sub(uint64_t out1[5], const uint64_t arg1[5], const uint64_t arg2[5]) { internal_fiat_25519_sub((uintptr_t)out1, (uintptr_t)arg1, (uintptr_t)arg2); } /* * Input Bounds: * in0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] */ static void internal_fiat_25519_opp(uintptr_t out0, uintptr_t in0) { uintptr_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x5 = ((uintptr_t)4503599627370458ULL)-(x0); x6 = ((uintptr_t)4503599627370494ULL)-(x1); x7 = ((uintptr_t)4503599627370494ULL)-(x2); x8 = ((uintptr_t)4503599627370494ULL)-(x3); x9 = ((uintptr_t)4503599627370494ULL)-(x4); x10 = x5; x11 = x6; x12 = x7; x13 = x8; x14 = x9; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x10, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x11, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x12, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x13, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x14, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_opp(uint64_t out1[5], const uint64_t arg1[5]) { internal_fiat_25519_opp((uintptr_t)out1, (uintptr_t)arg1); } /* * Input Bounds: * in0: [0x0 ~> 0x1] * in1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * in2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] * Output Bounds: * out0: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] */ static void internal_fiat_25519_selectznz(uintptr_t out0, uintptr_t in0, uintptr_t in1, uintptr_t in2) { uintptr_t x5, x10, x0, x11, x6, x13, x1, x14, x7, x16, x2, x17, x8, x19, x3, x20, x9, x22, x4, x23, x12, x15, x18, x21, x24, x25, x26, x27, x28, x29; /*skip*/ x0 = _br2_load((in1)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in1)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in1)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in1)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in1)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ x5 = _br2_load((in2)+((uintptr_t)0ULL), sizeof(uintptr_t)); x6 = _br2_load((in2)+((uintptr_t)8ULL), sizeof(uintptr_t)); x7 = _br2_load((in2)+((uintptr_t)16ULL), sizeof(uintptr_t)); x8 = _br2_load((in2)+((uintptr_t)24ULL), sizeof(uintptr_t)); x9 = _br2_load((in2)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x10 = ((uintptr_t)-1ULL)+((in0)==((uintptr_t)0ULL)); x11 = (x10)^((uintptr_t)18446744073709551615ULL); x12 = ((x5)&(x10))|((x0)&(x11)); x13 = ((uintptr_t)-1ULL)+((in0)==((uintptr_t)0ULL)); x14 = (x13)^((uintptr_t)18446744073709551615ULL); x15 = ((x6)&(x13))|((x1)&(x14)); x16 = ((uintptr_t)-1ULL)+((in0)==((uintptr_t)0ULL)); x17 = (x16)^((uintptr_t)18446744073709551615ULL); x18 = ((x7)&(x16))|((x2)&(x17)); x19 = ((uintptr_t)-1ULL)+((in0)==((uintptr_t)0ULL)); x20 = (x19)^((uintptr_t)18446744073709551615ULL); x21 = ((x8)&(x19))|((x3)&(x20)); x22 = ((uintptr_t)-1ULL)+((in0)==((uintptr_t)0ULL)); x23 = (x22)^((uintptr_t)18446744073709551615ULL); x24 = ((x9)&(x22))|((x4)&(x23)); x25 = x12; x26 = x15; x27 = x18; x28 = x21; x29 = x24; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x25, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x26, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x27, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x28, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x29, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_selectznz(uint64_t out1[5], uint8_t arg1, const uint64_t arg2[5], const uint64_t arg3[5]) { internal_fiat_25519_selectznz((uintptr_t)out1, (uintptr_t)arg1, (uintptr_t)arg2, (uintptr_t)arg3); } /* * Input Bounds: * in0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] * Output Bounds: * out0: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] */ static void internal_fiat_25519_to_bytes(uintptr_t out0, uintptr_t in0) { uintptr_t x0, x6, x5, x1, x8, x9, x10, x12, x13, x11, x2, x15, x16, x17, x19, x20, x18, x3, x22, x23, x24, x26, x27, x25, x4, x29, x30, x31, x33, x34, x32, x36, x7, x38, x39, x41, x14, x42, x43, x45, x44, x46, x48, x21, x49, x50, x52, x51, x53, x55, x28, x56, x57, x59, x58, x60, x62, x35, x63, x37, x64, x65, x61, x54, x47, x40, x71, x73, x75, x77, x79, x69, x81, x82, x84, x86, x88, x90, x92, x68, x94, x95, x97, x99, x101, x103, x105, x107, x67, x109, x110, x112, x114, x116, x118, x120, x66, x122, x123, x125, x127, x129, x131, x133, x70, x72, x74, x76, x78, x80, x83, x85, x87, x89, x91, x93, x96, x98, x100, x102, x104, x106, x108, x111, x113, x115, x117, x119, x121, x124, x126, x128, x130, x132, x134, x135, x136, x137, x138, x139, x140, x141, x142, x143, x144, x145, x146, x147, x148, x149, x150, x151, x152, x153, x154, x155, x156, x157, x158, x159, x160, x161, x162, x163, x164, x165, x166, x167; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x5 = (x0)-((uintptr_t)2251799813685229ULL); x6 = (x0)<(x5); x7 = (x5)&((uintptr_t)2251799813685247ULL); x8 = ((x6)<<((uintptr_t)13ULL))-((x5)>>((uintptr_t)51ULL)); x9 = (x1)-((uintptr_t)2251799813685247ULL); x10 = (x1)<(x9); x11 = (x9)-(x8); x12 = (x9)<(x11); x13 = (x10)+(x12); x14 = (x11)&((uintptr_t)2251799813685247ULL); x15 = ((x13)<<((uintptr_t)13ULL))-((x11)>>((uintptr_t)51ULL)); x16 = (x2)-((uintptr_t)2251799813685247ULL); x17 = (x2)<(x16); x18 = (x16)-(x15); x19 = (x16)<(x18); x20 = (x17)+(x19); x21 = (x18)&((uintptr_t)2251799813685247ULL); x22 = ((x20)<<((uintptr_t)13ULL))-((x18)>>((uintptr_t)51ULL)); x23 = (x3)-((uintptr_t)2251799813685247ULL); x24 = (x3)<(x23); x25 = (x23)-(x22); x26 = (x23)<(x25); x27 = (x24)+(x26); x28 = (x25)&((uintptr_t)2251799813685247ULL); x29 = ((x27)<<((uintptr_t)13ULL))-((x25)>>((uintptr_t)51ULL)); x30 = (x4)-((uintptr_t)2251799813685247ULL); x31 = (x4)<(x30); x32 = (x30)-(x29); x33 = (x30)<(x32); x34 = (x31)+(x33); x35 = (x32)&((uintptr_t)2251799813685247ULL); x36 = ((x34)<<((uintptr_t)13ULL))-((x32)>>((uintptr_t)51ULL)); x37 = ((uintptr_t)-1ULL)+((x36)==((uintptr_t)0ULL)); x38 = (x7)+((x37)&((uintptr_t)2251799813685229ULL)); x39 = (x38)<(x7); x40 = (x38)&((uintptr_t)2251799813685247ULL); x41 = ((x38)>>((uintptr_t)51ULL))+((x39)<<((uintptr_t)13ULL)); x42 = (x41)+(x14); x43 = (x42)<(x14); x44 = (x42)+((x37)&((uintptr_t)2251799813685247ULL)); x45 = (x44)<((x37)&((uintptr_t)2251799813685247ULL)); x46 = (x43)+(x45); x47 = (x44)&((uintptr_t)2251799813685247ULL); x48 = ((x44)>>((uintptr_t)51ULL))+((x46)<<((uintptr_t)13ULL)); x49 = (x48)+(x21); x50 = (x49)<(x21); x51 = (x49)+((x37)&((uintptr_t)2251799813685247ULL)); x52 = (x51)<((x37)&((uintptr_t)2251799813685247ULL)); x53 = (x50)+(x52); x54 = (x51)&((uintptr_t)2251799813685247ULL); x55 = ((x51)>>((uintptr_t)51ULL))+((x53)<<((uintptr_t)13ULL)); x56 = (x55)+(x28); x57 = (x56)<(x28); x58 = (x56)+((x37)&((uintptr_t)2251799813685247ULL)); x59 = (x58)<((x37)&((uintptr_t)2251799813685247ULL)); x60 = (x57)+(x59); x61 = (x58)&((uintptr_t)2251799813685247ULL); x62 = ((x58)>>((uintptr_t)51ULL))+((x60)<<((uintptr_t)13ULL)); x63 = (x62)+(x35); x64 = (x63)+((x37)&((uintptr_t)2251799813685247ULL)); x65 = (x64)&((uintptr_t)2251799813685247ULL); x66 = (x65)<<((uintptr_t)4ULL); x67 = (x61)*((uintptr_t)2ULL); x68 = (x54)<<((uintptr_t)6ULL); x69 = (x47)<<((uintptr_t)3ULL); x70 = (x40)&((uintptr_t)255ULL); x71 = (x40)>>((uintptr_t)8ULL); x72 = (x71)&((uintptr_t)255ULL); x73 = (x71)>>((uintptr_t)8ULL); x74 = (x73)&((uintptr_t)255ULL); x75 = (x73)>>((uintptr_t)8ULL); x76 = (x75)&((uintptr_t)255ULL); x77 = (x75)>>((uintptr_t)8ULL); x78 = (x77)&((uintptr_t)255ULL); x79 = (x77)>>((uintptr_t)8ULL); x80 = (x79)&((uintptr_t)255ULL); x81 = (x79)>>((uintptr_t)8ULL); x82 = (x69)+(x81); x83 = (x82)&((uintptr_t)255ULL); x84 = (x82)>>((uintptr_t)8ULL); x85 = (x84)&((uintptr_t)255ULL); x86 = (x84)>>((uintptr_t)8ULL); x87 = (x86)&((uintptr_t)255ULL); x88 = (x86)>>((uintptr_t)8ULL); x89 = (x88)&((uintptr_t)255ULL); x90 = (x88)>>((uintptr_t)8ULL); x91 = (x90)&((uintptr_t)255ULL); x92 = (x90)>>((uintptr_t)8ULL); x93 = (x92)&((uintptr_t)255ULL); x94 = (x92)>>((uintptr_t)8ULL); x95 = (x68)+(x94); x96 = (x95)&((uintptr_t)255ULL); x97 = (x95)>>((uintptr_t)8ULL); x98 = (x97)&((uintptr_t)255ULL); x99 = (x97)>>((uintptr_t)8ULL); x100 = (x99)&((uintptr_t)255ULL); x101 = (x99)>>((uintptr_t)8ULL); x102 = (x101)&((uintptr_t)255ULL); x103 = (x101)>>((uintptr_t)8ULL); x104 = (x103)&((uintptr_t)255ULL); x105 = (x103)>>((uintptr_t)8ULL); x106 = (x105)&((uintptr_t)255ULL); x107 = (x105)>>((uintptr_t)8ULL); x108 = (x107)&((uintptr_t)255ULL); x109 = (x107)>>((uintptr_t)8ULL); x110 = (x67)+(x109); x111 = (x110)&((uintptr_t)255ULL); x112 = (x110)>>((uintptr_t)8ULL); x113 = (x112)&((uintptr_t)255ULL); x114 = (x112)>>((uintptr_t)8ULL); x115 = (x114)&((uintptr_t)255ULL); x116 = (x114)>>((uintptr_t)8ULL); x117 = (x116)&((uintptr_t)255ULL); x118 = (x116)>>((uintptr_t)8ULL); x119 = (x118)&((uintptr_t)255ULL); x120 = (x118)>>((uintptr_t)8ULL); x121 = (x120)&((uintptr_t)255ULL); x122 = (x120)>>((uintptr_t)8ULL); x123 = (x66)+(x122); x124 = (x123)&((uintptr_t)255ULL); x125 = (x123)>>((uintptr_t)8ULL); x126 = (x125)&((uintptr_t)255ULL); x127 = (x125)>>((uintptr_t)8ULL); x128 = (x127)&((uintptr_t)255ULL); x129 = (x127)>>((uintptr_t)8ULL); x130 = (x129)&((uintptr_t)255ULL); x131 = (x129)>>((uintptr_t)8ULL); x132 = (x131)&((uintptr_t)255ULL); x133 = (x131)>>((uintptr_t)8ULL); x134 = (x133)&((uintptr_t)255ULL); x135 = (x133)>>((uintptr_t)8ULL); x136 = x70; x137 = x72; x138 = x74; x139 = x76; x140 = x78; x141 = x80; x142 = x83; x143 = x85; x144 = x87; x145 = x89; x146 = x91; x147 = x93; x148 = x96; x149 = x98; x150 = x100; x151 = x102; x152 = x104; x153 = x106; x154 = x108; x155 = x111; x156 = x113; x157 = x115; x158 = x117; x159 = x119; x160 = x121; x161 = x124; x162 = x126; x163 = x128; x164 = x130; x165 = x132; x166 = x134; x167 = x135; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x136, 1); _br2_store((out0)+((uintptr_t)1ULL), x137, 1); _br2_store((out0)+((uintptr_t)2ULL), x138, 1); _br2_store((out0)+((uintptr_t)3ULL), x139, 1); _br2_store((out0)+((uintptr_t)4ULL), x140, 1); _br2_store((out0)+((uintptr_t)5ULL), x141, 1); _br2_store((out0)+((uintptr_t)6ULL), x142, 1); _br2_store((out0)+((uintptr_t)7ULL), x143, 1); _br2_store((out0)+((uintptr_t)8ULL), x144, 1); _br2_store((out0)+((uintptr_t)9ULL), x145, 1); _br2_store((out0)+((uintptr_t)10ULL), x146, 1); _br2_store((out0)+((uintptr_t)11ULL), x147, 1); _br2_store((out0)+((uintptr_t)12ULL), x148, 1); _br2_store((out0)+((uintptr_t)13ULL), x149, 1); _br2_store((out0)+((uintptr_t)14ULL), x150, 1); _br2_store((out0)+((uintptr_t)15ULL), x151, 1); _br2_store((out0)+((uintptr_t)16ULL), x152, 1); _br2_store((out0)+((uintptr_t)17ULL), x153, 1); _br2_store((out0)+((uintptr_t)18ULL), x154, 1); _br2_store((out0)+((uintptr_t)19ULL), x155, 1); _br2_store((out0)+((uintptr_t)20ULL), x156, 1); _br2_store((out0)+((uintptr_t)21ULL), x157, 1); _br2_store((out0)+((uintptr_t)22ULL), x158, 1); _br2_store((out0)+((uintptr_t)23ULL), x159, 1); _br2_store((out0)+((uintptr_t)24ULL), x160, 1); _br2_store((out0)+((uintptr_t)25ULL), x161, 1); _br2_store((out0)+((uintptr_t)26ULL), x162, 1); _br2_store((out0)+((uintptr_t)27ULL), x163, 1); _br2_store((out0)+((uintptr_t)28ULL), x164, 1); _br2_store((out0)+((uintptr_t)29ULL), x165, 1); _br2_store((out0)+((uintptr_t)30ULL), x166, 1); _br2_store((out0)+((uintptr_t)31ULL), x167, 1); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_to_bytes(uint8_t out1[32], const uint64_t arg1[5]) { internal_fiat_25519_to_bytes((uintptr_t)out1, (uintptr_t)arg1); } /* * Input Bounds: * in0: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] * Output Bounds: * out0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] */ static void internal_fiat_25519_from_bytes(uintptr_t out0, uintptr_t in0) { uintptr_t x31, x30, x29, x28, x27, x26, x25, x24, x23, x22, x21, x20, x19, x18, x17, x16, x15, x14, x13, x12, x11, x10, x9, x8, x7, x6, x5, x4, x3, x2, x1, x0, x62, x63, x61, x64, x60, x65, x59, x66, x58, x67, x57, x68, x69, x56, x71, x55, x72, x54, x73, x53, x74, x52, x75, x51, x76, x77, x50, x79, x49, x80, x48, x81, x47, x82, x46, x83, x45, x84, x44, x85, x86, x43, x88, x42, x89, x41, x90, x40, x91, x39, x92, x38, x93, x94, x37, x96, x36, x97, x35, x98, x34, x99, x33, x100, x32, x101, x70, x78, x87, x95, x102, x103, x104, x105, x106, x107; x0 = _br2_load((in0)+((uintptr_t)0ULL), 1); x1 = _br2_load((in0)+((uintptr_t)1ULL), 1); x2 = _br2_load((in0)+((uintptr_t)2ULL), 1); x3 = _br2_load((in0)+((uintptr_t)3ULL), 1); x4 = _br2_load((in0)+((uintptr_t)4ULL), 1); x5 = _br2_load((in0)+((uintptr_t)5ULL), 1); x6 = _br2_load((in0)+((uintptr_t)6ULL), 1); x7 = _br2_load((in0)+((uintptr_t)7ULL), 1); x8 = _br2_load((in0)+((uintptr_t)8ULL), 1); x9 = _br2_load((in0)+((uintptr_t)9ULL), 1); x10 = _br2_load((in0)+((uintptr_t)10ULL), 1); x11 = _br2_load((in0)+((uintptr_t)11ULL), 1); x12 = _br2_load((in0)+((uintptr_t)12ULL), 1); x13 = _br2_load((in0)+((uintptr_t)13ULL), 1); x14 = _br2_load((in0)+((uintptr_t)14ULL), 1); x15 = _br2_load((in0)+((uintptr_t)15ULL), 1); x16 = _br2_load((in0)+((uintptr_t)16ULL), 1); x17 = _br2_load((in0)+((uintptr_t)17ULL), 1); x18 = _br2_load((in0)+((uintptr_t)18ULL), 1); x19 = _br2_load((in0)+((uintptr_t)19ULL), 1); x20 = _br2_load((in0)+((uintptr_t)20ULL), 1); x21 = _br2_load((in0)+((uintptr_t)21ULL), 1); x22 = _br2_load((in0)+((uintptr_t)22ULL), 1); x23 = _br2_load((in0)+((uintptr_t)23ULL), 1); x24 = _br2_load((in0)+((uintptr_t)24ULL), 1); x25 = _br2_load((in0)+((uintptr_t)25ULL), 1); x26 = _br2_load((in0)+((uintptr_t)26ULL), 1); x27 = _br2_load((in0)+((uintptr_t)27ULL), 1); x28 = _br2_load((in0)+((uintptr_t)28ULL), 1); x29 = _br2_load((in0)+((uintptr_t)29ULL), 1); x30 = _br2_load((in0)+((uintptr_t)30ULL), 1); x31 = _br2_load((in0)+((uintptr_t)31ULL), 1); /*skip*/ /*skip*/ x32 = (x31)<<((uintptr_t)44ULL); x33 = (x30)<<((uintptr_t)36ULL); x34 = (x29)<<((uintptr_t)28ULL); x35 = (x28)<<((uintptr_t)20ULL); x36 = (x27)<<((uintptr_t)12ULL); x37 = (x26)<<((uintptr_t)4ULL); x38 = (x25)<<((uintptr_t)47ULL); x39 = (x24)<<((uintptr_t)39ULL); x40 = (x23)<<((uintptr_t)31ULL); x41 = (x22)<<((uintptr_t)23ULL); x42 = (x21)<<((uintptr_t)15ULL); x43 = (x20)<<((uintptr_t)7ULL); x44 = (x19)<<((uintptr_t)50ULL); x45 = (x18)<<((uintptr_t)42ULL); x46 = (x17)<<((uintptr_t)34ULL); x47 = (x16)<<((uintptr_t)26ULL); x48 = (x15)<<((uintptr_t)18ULL); x49 = (x14)<<((uintptr_t)10ULL); x50 = (x13)<<((uintptr_t)2ULL); x51 = (x12)<<((uintptr_t)45ULL); x52 = (x11)<<((uintptr_t)37ULL); x53 = (x10)<<((uintptr_t)29ULL); x54 = (x9)<<((uintptr_t)21ULL); x55 = (x8)<<((uintptr_t)13ULL); x56 = (x7)<<((uintptr_t)5ULL); x57 = (x6)<<((uintptr_t)48ULL); x58 = (x5)<<((uintptr_t)40ULL); x59 = (x4)<<((uintptr_t)32ULL); x60 = (x3)<<((uintptr_t)24ULL); x61 = (x2)<<((uintptr_t)16ULL); x62 = (x1)<<((uintptr_t)8ULL); x63 = x0; x64 = (x62)+(x63); x65 = (x61)+(x64); x66 = (x60)+(x65); x67 = (x59)+(x66); x68 = (x58)+(x67); x69 = (x57)+(x68); x70 = (x69)&((uintptr_t)2251799813685247ULL); x71 = (x69)>>((uintptr_t)51ULL); x72 = (x56)+(x71); x73 = (x55)+(x72); x74 = (x54)+(x73); x75 = (x53)+(x74); x76 = (x52)+(x75); x77 = (x51)+(x76); x78 = (x77)&((uintptr_t)2251799813685247ULL); x79 = (x77)>>((uintptr_t)51ULL); x80 = (x50)+(x79); x81 = (x49)+(x80); x82 = (x48)+(x81); x83 = (x47)+(x82); x84 = (x46)+(x83); x85 = (x45)+(x84); x86 = (x44)+(x85); x87 = (x86)&((uintptr_t)2251799813685247ULL); x88 = (x86)>>((uintptr_t)51ULL); x89 = (x43)+(x88); x90 = (x42)+(x89); x91 = (x41)+(x90); x92 = (x40)+(x91); x93 = (x39)+(x92); x94 = (x38)+(x93); x95 = (x94)&((uintptr_t)2251799813685247ULL); x96 = (x94)>>((uintptr_t)51ULL); x97 = (x37)+(x96); x98 = (x36)+(x97); x99 = (x35)+(x98); x100 = (x34)+(x99); x101 = (x33)+(x100); x102 = (x32)+(x101); x103 = x70; x104 = x78; x105 = x87; x106 = x95; x107 = x102; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x103, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x104, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x105, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x106, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x107, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_from_bytes(uint64_t out1[5], const uint8_t arg1[32]) { internal_fiat_25519_from_bytes((uintptr_t)out1, (uintptr_t)arg1); } /* * Input Bounds: * in0: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] * Output Bounds: * out0: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] */ static void internal_fiat_25519_carry_scmul_121666(uintptr_t out0, uintptr_t in0) { uintptr_t x4, x3, x2, x1, x0, x14, x13, x11, x15, x18, x12, x19, x17, x9, x20, x23, x10, x24, x22, x7, x25, x28, x8, x29, x27, x5, x30, x33, x6, x34, x32, x35, x16, x37, x38, x39, x21, x41, x42, x26, x40, x43, x44, x31, x36, x45, x46, x47, x48, x49; x0 = _br2_load((in0)+((uintptr_t)0ULL), sizeof(uintptr_t)); x1 = _br2_load((in0)+((uintptr_t)8ULL), sizeof(uintptr_t)); x2 = _br2_load((in0)+((uintptr_t)16ULL), sizeof(uintptr_t)); x3 = _br2_load((in0)+((uintptr_t)24ULL), sizeof(uintptr_t)); x4 = _br2_load((in0)+((uintptr_t)32ULL), sizeof(uintptr_t)); /*skip*/ /*skip*/ x5 = ((uintptr_t)121666ULL)*(x4); x6 = sizeof(intptr_t) == 4 ? ((uint64_t)((uintptr_t)121666ULL)*(x4))>>32 : ((__uint128_t)((uintptr_t)121666ULL)*(x4))>>64; x7 = ((uintptr_t)121666ULL)*(x3); x8 = sizeof(intptr_t) == 4 ? ((uint64_t)((uintptr_t)121666ULL)*(x3))>>32 : ((__uint128_t)((uintptr_t)121666ULL)*(x3))>>64; x9 = ((uintptr_t)121666ULL)*(x2); x10 = sizeof(intptr_t) == 4 ? ((uint64_t)((uintptr_t)121666ULL)*(x2))>>32 : ((__uint128_t)((uintptr_t)121666ULL)*(x2))>>64; x11 = ((uintptr_t)121666ULL)*(x1); x12 = sizeof(intptr_t) == 4 ? ((uint64_t)((uintptr_t)121666ULL)*(x1))>>32 : ((__uint128_t)((uintptr_t)121666ULL)*(x1))>>64; x13 = ((uintptr_t)121666ULL)*(x0); x14 = sizeof(intptr_t) == 4 ? ((uint64_t)((uintptr_t)121666ULL)*(x0))>>32 : ((__uint128_t)((uintptr_t)121666ULL)*(x0))>>64; x15 = ((x13)>>((uintptr_t)51ULL))|((x14)<<((uintptr_t)13ULL)); x16 = (x13)&((uintptr_t)2251799813685247ULL); x17 = (x15)+(x11); x18 = (x17)<(x15); x19 = (x18)+(x12); x20 = ((x17)>>((uintptr_t)51ULL))|((x19)<<((uintptr_t)13ULL)); x21 = (x17)&((uintptr_t)2251799813685247ULL); x22 = (x20)+(x9); x23 = (x22)<(x20); x24 = (x23)+(x10); x25 = ((x22)>>((uintptr_t)51ULL))|((x24)<<((uintptr_t)13ULL)); x26 = (x22)&((uintptr_t)2251799813685247ULL); x27 = (x25)+(x7); x28 = (x27)<(x25); x29 = (x28)+(x8); x30 = ((x27)>>((uintptr_t)51ULL))|((x29)<<((uintptr_t)13ULL)); x31 = (x27)&((uintptr_t)2251799813685247ULL); x32 = (x30)+(x5); x33 = (x32)<(x30); x34 = (x33)+(x6); x35 = ((x32)>>((uintptr_t)51ULL))|((x34)<<((uintptr_t)13ULL)); x36 = (x32)&((uintptr_t)2251799813685247ULL); x37 = (x35)*((uintptr_t)19ULL); x38 = (x16)+(x37); x39 = (x38)>>((uintptr_t)51ULL); x40 = (x38)&((uintptr_t)2251799813685247ULL); x41 = (x39)+(x21); x42 = (x41)>>((uintptr_t)51ULL); x43 = (x41)&((uintptr_t)2251799813685247ULL); x44 = (x42)+(x26); x45 = x40; x46 = x43; x47 = x44; x48 = x31; x49 = x36; /*skip*/ _br2_store((out0)+((uintptr_t)0ULL), x45, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)8ULL), x46, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)16ULL), x47, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)24ULL), x48, sizeof(uintptr_t)); _br2_store((out0)+((uintptr_t)32ULL), x49, sizeof(uintptr_t)); /*skip*/ return; } /* NOTE: The following wrapper function is not covered by Coq proofs */ static void fiat_25519_carry_scmul_121666(uint64_t out1[5], const uint64_t arg1[5]) { internal_fiat_25519_carry_scmul_121666((uintptr_t)out1, (uintptr_t)arg1); }
the_stack_data/118010.c
/* PR c/10320 The function temp was not being emitted in a prerelease of 3.4 20030406. Contributed by [email protected] */ static inline void temp(); int main() { temp(); return 0; } static void temp(){}
the_stack_data/358242.c
#include<stdio.h> int main(){ int m; scanf("%i",&m); if(m>2 && m%2==0){ printf("YES"); } else{ printf("NO"); } return 0; }
the_stack_data/119398.c
inline int foo(int x) { return x; } int getfoo2() { return (int)foo; }
the_stack_data/616493.c
// REQUIRES: powerpc-registered-target // RUN: %clang_cc1 -triple powerpc-unknown-unknown -emit-llvm %s -o - | FileCheck %s void test_eh_return_data_regno() { volatile int res; res = __builtin_eh_return_data_regno(0); // CHECK: store volatile i32 3 res = __builtin_eh_return_data_regno(1); // CHECK: store volatile i32 4 } // CHECK-LABEL: define i64 @test_builtin_ppc_get_timebase long long test_builtin_ppc_get_timebase() { // CHECK: call i64 @llvm.readcyclecounter() return __builtin_ppc_get_timebase(); } void test_builtin_ppc_setrnd() { volatile double res; volatile int x = 100; // CHECK: call double @llvm.ppc.setrnd(i32 2) res = __builtin_setrnd(2); // CHECK: call double @llvm.ppc.setrnd(i32 100) res = __builtin_setrnd(100); // CHECK: call double @llvm.ppc.setrnd(i32 %2) res = __builtin_setrnd(x); }
the_stack_data/11629.c
#include <stdio.h> int main(int argc, char const *argv[]) { int mod; int i; for (i = 0; i < 50; i++) { mod=i%2; printf("%d\n",mod); } }
the_stack_data/97013222.c
# include<stdio.h> void knapsack(int n, float weight[], float profit[], float capacity) { float x[20], tp = 0; int i, j, u; u = capacity; for (i = 0; i < n; i++) x[i] = 0.0; for (i = 0; i < n; i++) { if (weight[i] > u) break; else { x[i] = 1.0; tp = tp + profit[i]; u = u - weight[i]; } } if (i < n) x[i] = u / weight[i]; tp = tp + (x[i] * profit[i]); printf("\nThe result vector is:- "); for (i = 0; i < n; i++) printf("%f\t", x[i]); printf("\nMaximum profit is:- %f", tp); } int main() { float weight[20], profit[20], capacity; int num, i, j; float ratio[20], temp; printf("\nEnter the no. of objects:- "); scanf("%d", &num); printf("\nEnter the weights and profits of each object:- "); for (i = 0; i < num; i++) { scanf("%f %f", &weight[i], &profit[i]); } printf("\nEnter the capacity of knapsack:- "); scanf("%f", &capacity); for (i = 0; i < num; i++) { ratio[i] = profit[i] / weight[i]; } for (i = 0; i < num; i++) { for (j = i + 1; j < num; j++) { if (ratio[i] < ratio[j]) { temp = ratio[j]; ratio[j] = ratio[i]; ratio[i] = temp; temp = weight[j]; weight[j] = weight[i]; weight[i] = temp; temp = profit[j]; profit[j] = profit[i]; profit[i] = temp; } } } knapsack(num, weight, profit, capacity); return(0); }
the_stack_data/296037.c
struct MindustryObject {}; // builtin instructions void print(char* s) { asm("print {s}"); } void printd(double s) { asm("print {s}"); } void printflush(struct MindustryObject message) { asm("printflush {message}"); } struct MindustryObject radar(struct MindustryObject obj, char* target1, char* target2, char* target3, char* sort, double order) { asm("radar {target1} {target2} {target3} {sort} {obj} {order} {dest}"); } double sensor(struct MindustryObject obj, char* prop) { asm("sensor {dest} {obj} @{prop}"); } void enable(struct MindustryObject obj, double enabled) { asm("control enabled {obj} {enabled} 0 0 0"); } void configure(struct MindustryObject obj, char* configure) { asm("control configure {obj} {configure} 0 0 0"); } void setcolor(struct MindustryObject obj, double r, double g, double b) { asm("control color {obj} {r} {g} {b} 0"); } void shoot(struct MindustryObject obj, double x, double y, double shoot) { asm("control shoot {obj} {x} {y} {shoot} 0"); } void shootp(struct MindustryObject obj, double unit, double shoot) { asm("control shootp {obj} {unit} {shoot} 0 0"); } struct MindustryObject get_link(double index) { asm("getlink {dest} {index}"); } double read(struct MindustryObject cell, double index) { asm("read {dest} {cell} {index}"); } void write(double val, struct MindustryObject cell, double index) { asm("write {val} {cell} {index}"); } void drawclear(double r, double g, double b) { asm("draw clear {r} {g} {b}"); } void drawcolor(double r, double g, double b, double a) { asm("draw color {r} {g} {b} {a}"); } void drawstroke(double width) { asm("draw stroke {width}"); } void drawline(double x1, double y1, double x2, double y2) { asm("draw line {x1} {y1} {x2} {y2}"); } void drawrect(double x, double y, double w, double h) { asm("draw rect {x} {y} {w} {h}"); } void drawlinerect(double x, double y, double w, double h) { asm("draw lineRect {x} {y} {w} {h}"); } void drawpoly(double x, double y, double sides, double radius, double rotation) { asm("draw poly {x} {y} {sides} {radius} {rotation}"); } void drawlinepoly(double x, double y, double sides, double radius, double rotation) { asm("draw linePoly {x} {y} {sides} {radius} {rotation}"); } void drawtriangle(double x1, double y1, double x2, double y2, double x3, double y3) { asm("draw triangle {x1} {y1} {x2} {y2} {x3} {y3}"); } void drawimage(double x, double y, char* image, double size, double rotation) { asm("draw image {x} {y} {image} {size} {rotation} 0"); } void drawflush(struct MindustryObject display) { asm("drawflush {display}"); } // unit commands (not complete; don't know how to return multiple values) void ubind(char* type) { asm("ubind @{type}"); } void unit_move(double x, double y) { asm("ucontrol move {x} {y} 0 0 0"); } void unit_idle() { asm("ucontrol idle 0 0 0 0 0"); } void unit_stop() { asm("ucontrol stop 0 0 0 0 0"); } void unit_approach(double x, double y, double radius) { asm("ucontrol approach {x} {y} {radius} 0 0"); } void unit_boost(double enable) { asm("ucontrol boost {enable} 0 0 0 0"); } void unit_pathfind() { asm("ucontrol pathfind 0 0 0 0 0"); } void unit_target(double x, double y, double shoot) { asm("ucontrol target {x} {y} {shoot} 0 0"); } void unit_targetp(double unit, double shoot) { asm("ucontrol targetp {unit} {shoot} 0 0 0"); } void unit_item_drop(struct MindustryObject obj, double amount) { asm("ucontrol itemDrop {obj} {amount} 0 0 0"); } void unit_item_take(struct MindustryObject obj, char* item, double amount) { asm("ucontrol itemTake {obj} @{item} {amount} 0 0"); } void unit_pay_drop() { asm("ucontrol payDrop 0 0 0 0 0"); } void unit_pay_take(double takeUnits) { asm("ucontrol payTake {takeUnits} 0 0 0 0"); } void unit_mine(double x, double y) { asm("ucontrol mine {x} {y} 0 0 0"); } void unit_flag(double value) { asm("ucontrol flag {value} 0 0 0 0"); } void unit_build(double x, double y, char* block, double rotation, char* configure) { asm("ucontrol build {x} {y} {block} {rotation} {configure}"); } double unit_within(double x, double y, double radius) { asm("ucontrol within {x} {y} {radius} {dest} 0"); } struct MindustryObject unit_radar(char* target1, char* target2, char* target3, char* sort, double order) { asm("uradar {target1} {target2} {target3} {sort} 0 {order} {dest}"); }
the_stack_data/680953.c
#include <sys/select.h> #include <signal.h> #include <stdint.h> #include <errno.h> #include "syscall.h" #define IS32BIT(x) !((x)+0x80000000ULL>>32) #define CLAMP(x) (int)(IS32BIT(x) ? (x) : 0x7fffffffU+((0ULL+(x))>>63)) int select(int n, fd_set *restrict rfds, fd_set *restrict wfds, fd_set *restrict efds, struct timeval *restrict tv) { time_t s = tv ? tv->tv_sec : 0; suseconds_t us = tv ? tv->tv_usec : 0; long ns; const time_t max_time = (1ULL<<8*sizeof(time_t)-1)-1; if (s<0 || us<0) return __syscall_ret(-EINVAL); if (us/1000000 > max_time - s) { s = max_time; us = 999999; ns = 999999999; } else { s += us/1000000; us %= 1000000; ns = us*1000; } #ifdef SYS_pselect6_time64 int r = -ENOSYS; if (SYS_pselect6 == SYS_pselect6_time64 || !IS32BIT(s)) r = __syscall_cp(SYS_pselect6_time64, n, rfds, wfds, efds, tv ? ((long long[]){s, ns}) : 0, ((syscall_arg_t[]){ 0, _NSIG/8 })); if (SYS_pselect6 == SYS_pselect6_time64 || r!=-ENOSYS) return __syscall_ret(r); #endif #ifdef SYS_select return syscall_cp(SYS_select, n, rfds, wfds, efds, tv ? ((long[]){s, us}) : 0); #else return syscall_cp(SYS_pselect6, n, rfds, wfds, efds, tv ? ((long[]){s, ns}) : 0, ((syscall_arg_t[]){ 0, _NSIG/8 })); #endif }
the_stack_data/184519226.c
#include<stdio.h> #include<limits.h> int main(){ int minimo = INT_MIN, valor, quantidade = 0; while(quantidade<5){ quantidade++; printf("Coloque um numero para comparar: "); scanf("%d",&valor); if(valor>minimo){ minimo = valor; } } printf("O maior numero eh: %d", minimo); }
the_stack_data/31389151.c
#include <stdio.h> #include <stdlib.h> // node of list structure typedef struct tagListNode { struct tagListNode *prev; struct tagListNode *next; int data; } ListNode; int main(void) { ListNode *firstNode, *lastNode, *newNode, *thisNode, *removeNode; firstNode = lastNode = NULL; int buf; do { printf("input integer (0: quit) > "); scanf("%d", &buf); // append node to list if (buf) { // allocate new node newNode = (ListNode*)malloc(sizeof(ListNode)); newNode->data = buf; newNode->next = NULL; if (lastNode != NULL) { lastNode->next = newNode; newNode->prev = lastNode; lastNode = newNode; } else { // first node firstNode = lastNode = newNode; newNode->prev = NULL; } } // while 0 is inputed } while (buf != 0); // print and sum all nodes printf("numbers\n"); int sum = 0; for (thisNode = firstNode; thisNode != NULL; thisNode = thisNode->next) { printf("%d\t", thisNode->data); sum += thisNode->data; } printf("\nsum=%d\n", sum); // remove all nodes for (thisNode = firstNode; thisNode != NULL;) { removeNode = thisNode; thisNode = thisNode->next; free(removeNode); } return 0; }
the_stack_data/95449612.c
/* Copyright (c) 2011 The WebM project authors. All Rights Reserved. */ /* */ /* Use of this source code is governed by a BSD-style license */ /* that can be found in the LICENSE file in the root of the source */ /* tree. An additional intellectual property rights grant can be found */ /* in the file PATENTS. All contributing project authors may */ /* be found in the AUTHORS file in the root of the source tree. */ static const char* const cfg = "--target=armv7-linux-gcc --enable-pic --enable-realtime-only --enable-external-build --enable-postproc --disable-install-srcs --enable-multi-res-encoding --enable-temporal-denoising --disable-unit-tests --disable-install-docs --disable-examples --disable-avx2"; const char *vpx_codec_build_config(void) {return cfg;}
the_stack_data/25138331.c
// find all substrings of digits from a given string that sum to 10 #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> int main(void) { char s[100]; printf("Enter string : " ) ; scanf("%s", s); for (int i = 0; i < strlen(s) - 1; i++)//start position of the substring { for (int j = i + 1; j < strlen(s); j++)//end pointer of substring { int sum =0 ; for(int k =i ; k<=j ; k++) sum+=s[k]-'0' ; if(sum==10){ for(int k =i ; k<=j ; k++) printf("%c" , s[k]) ; printf("\n") ; } } } }
the_stack_data/566336.c
#include<stdio.h> void reverse(int *arr, int n){ int temp; for(int i=0; i<(n/2); i++){ temp = arr[i]; arr[i] = arr[n-i-1]; arr[n-i-1] = temp; } } int main(){ int arr[] = {1,2,3,4,5,6,7}; reverse(arr, 7); for(int i=0; i<7; i++){ printf("The value of %d element is: %d\n", i, arr[i]); } return 0; }
the_stack_data/1216464.c
// RUN: %clang -target aarch64-none-linux-gnu -x c -E -dM %s -o - | FileCheck %s // RUN: %clang -target arm64-none-linux-gnu -x c -E -dM %s -o - | FileCheck %s // CHECK: __AARCH64EL__ 1 // CHECK: __ARM_64BIT_STATE 1 // CHECK-NOT: __ARM_32BIT_STATE // CHECK: __ARM_ACLE 200 // CHECK: __ARM_ALIGN_MAX_STACK_PWR 4 // CHECK: __ARM_ARCH 8 // CHECK: __ARM_ARCH_ISA_A64 1 // CHECK-NOT: __ARM_ARCH_ISA_ARM // CHECK-NOT: __ARM_ARCH_ISA_THUMB // CHECK-NOT: __ARM_FEATURE_QBIT // CHECK-NOT: __ARM_FEATURE_DSP // CHECK-NOT: __ARM_FEATURE_SAT // CHECK-NOT: __ARM_FEATURE_SIMD32 // CHECK: __ARM_ARCH_PROFILE 'A' // CHECK-NOT: __ARM_FEATURE_BIG_ENDIAN // CHECK: __ARM_FEATURE_CLZ 1 // CHECK-NOT: __ARM_FEATURE_CRC32 1 // CHECK-NOT: __ARM_FEATURE_CRYPTO 1 // CHECK: __ARM_FEATURE_DIRECTED_ROUNDING 1 // CHECK: __ARM_FEATURE_DIV 1 // CHECK: __ARM_FEATURE_FMA 1 // CHECK: __ARM_FEATURE_IDIV 1 // CHECK: __ARM_FEATURE_LDREX 0xF // CHECK: __ARM_FEATURE_NUMERIC_MAXMIN 1 // CHECK: __ARM_FEATURE_UNALIGNED 1 // CHECK: __ARM_FP 0xE // CHECK: __ARM_FP16_ARGS 1 // CHECK: __ARM_FP16_FORMAT_IEEE 1 // CHECK-NOT: __ARM_FP_FAST 1 // CHECK: __ARM_NEON 1 // CHECK: __ARM_NEON_FP 0xE // CHECK: __ARM_PCS_AAPCS64 1 // CHECK-NOT: __ARM_PCS 1 // CHECK-NOT: __ARM_PCS_VFP 1 // CHECK-NOT: __ARM_SIZEOF_MINIMAL_ENUM 1 // CHECK-NOT: __ARM_SIZEOF_WCHAR_T 2 // CHECK-NOT: __ARM_FEATURE_SVE // CHECK-NOT: __ARM_FEATURE_DOTPROD // RUN: %clang -target aarch64-none-linux-gnu -march=armv8-a+crypto -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-CRYPTO %s // RUN: %clang -target arm64-none-linux-gnu -march=armv8-a+crypto -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-CRYPTO %s // CHECK-CRYPTO: __ARM_FEATURE_CRYPTO 1 // RUN: %clang -target aarch64-none-linux-gnu -mcrc -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-CRC32 %s // RUN: %clang -target arm64-none-linux-gnu -mcrc -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-CRC32 %s // RUN: %clang -target aarch64-none-linux-gnu -march=armv8-a+crc -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-CRC32 %s // RUN: %clang -target arm64-none-linux-gnu -march=armv8-a+crc -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-CRC32 %s // CHECK-CRC32: __ARM_FEATURE_CRC32 1 // RUN: %clang -target aarch64-none-linux-gnu -fno-math-errno -fno-signed-zeros\ // RUN: -fno-trapping-math -fassociative-math -freciprocal-math\ // RUN: -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-FASTMATH %s // RUN: %clang -target aarch64-none-linux-gnu -ffast-math -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-FASTMATH %s // RUN: %clang -target arm64-none-linux-gnu -ffast-math -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-FASTMATH %s // CHECK-FASTMATH: __ARM_FP_FAST 1 // RUN: %clang -target aarch64-none-linux-gnu -fshort-wchar -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SHORTWCHAR %s // RUN: %clang -target arm64-none-linux-gnu -fshort-wchar -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SHORTWCHAR %s // CHECK-SHORTWCHAR: __ARM_SIZEOF_WCHAR_T 2 // RUN: %clang -target aarch64-none-linux-gnu -fshort-enums -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SHORTENUMS %s // RUN: %clang -target arm64-none-linux-gnu -fshort-enums -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SHORTENUMS %s // CHECK-SHORTENUMS: __ARM_SIZEOF_MINIMAL_ENUM 1 // RUN: %clang -target aarch64-none-linux-gnu -march=armv8-a+simd -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NEON %s // RUN: %clang -target arm64-none-linux-gnu -march=armv8-a+simd -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-NEON %s // CHECK-NEON: __ARM_NEON 1 // CHECK-NEON: __ARM_NEON_FP 0xE // RUN: %clang -target aarch64-none-eabi -march=armv8.1-a -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-QRDMX %s // RUN: %clang -target aarch64-none-eabi -march=armv8.2-a -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-QRDMX %s // CHECK-QRDMX: __ARM_FEATURE_QRDMX 1 // RUN: %clang -target aarch64 -march=arm64 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-ARCH-NOT-ACCEPT %s // RUN: %clang -target aarch64 -march=aarch64 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-ARCH-NOT-ACCEPT %s // CHECK-ARCH-NOT-ACCEPT: error: the clang compiler does not support // RUN: %clang -target aarch64 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-GENERIC %s // RUN: %clang -target aarch64 -march=armv8-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-GENERIC %s // CHECK-GENERIC: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" // RUN: %clang -target aarch64 -mtune=cyclone -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MTUNE-CYCLONE %s // RUN: %clang -target aarch64-none-linux-gnu -march=armv8-a+sve -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-SVE %s // CHECK-SVE-NOT: __ARM_FEATURE_SVE 1 // RUN: %clang -target aarch64-none-linux-gnu -march=armv8.2a+dotprod -x c -E -dM %s -o - | FileCheck --check-prefix=CHECK-DOTPROD %s // CHECK-DOTPROD: __ARM_FEATURE_DOTPROD 1 // On ARMv8.2-A and above, +fp16fml implies +fp16. // On ARMv8.4-A and above, +fp16 implies +fp16fml. // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a+nofp16fml+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a+nofp16+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-FML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a+fp16+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8-a+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-FML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8-a+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+nofp16fml+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-FML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+nofp16+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-FML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+fp16+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+fp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-FML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+fp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-FML --check-prefix=CHECK-FULLFP16-VECTOR-SCALAR %s // CHECK-FULLFP16-FML: #define __ARM_FEATURE_FP16FML 1 // CHECK-FULLFP16-NOFML-NOT: #define __ARM_FEATURE_FP16FML 1 // CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1 // CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC 1 // CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FP 0xE // CHECK-FULLFP16-VECTOR-SCALAR: #define __ARM_FP16_FORMAT_IEEE 1 // +fp16fml+nosimd doesn't make sense as the fp16fml instructions all require SIMD. // However, as +fp16fml implies +fp16 there is a set of defines that we would expect. // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8-a+fp16fml+nosimd -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8-a+fp16+nosimd -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+fp16fml+nosimd -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+fp16+nosimd -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-SCALAR %s // CHECK-FULLFP16-SCALAR-NOT: #define __ARM_FEATURE_FP16FML 1 // CHECK-FULLFP16-SCALAR: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1 // CHECK-FULLFP16-SCALAR-NOT: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC 1 // CHECK-FULLFP16-SCALAR: #define __ARM_FP 0xE // CHECK-FULLFP16-SCALAR: #define __ARM_FP16_FORMAT_IEEE 1 // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.2-a+fp16fml+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+nofp16fml -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // RUN: %clang -target aarch64-none-linux-gnueabi -march=armv8.4-a+fp16fml+nofp16 -x c -E -dM %s -o - | FileCheck -match-full-lines --check-prefix=CHECK-FULLFP16-NOFML-VECTOR-SCALAR %s // CHECK-FULLFP16-NOFML-VECTOR-SCALAR-NOT: #define __ARM_FEATURE_FP16FML 1 // CHECK-FULLFP16-NOFML-VECTOR-SCALAR-NOT: #define __ARM_FEATURE_FP16_SCALAR_ARITHMETIC 1 // CHECK-FULLFP16-NOFML-VECTOR-SCALAR-NOT: #define __ARM_FEATURE_FP16_VECTOR_ARITHMETIC 1 // CHECK-FULLFP16-NOFML-VECTOR-SCALAR: #define __ARM_FP 0xE // CHECK-FULLFP16-NOFML-VECTOR-SCALAR: #define __ARM_FP16_FORMAT_IEEE 1 // ================== Check whether -mtune accepts mixed-case features. // RUN: %clang -target aarch64 -mtune=CYCLONE -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MTUNE-CYCLONE %s // CHECK-MTUNE-CYCLONE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+zcm" "-target-feature" "+zcz" // RUN: %clang -target aarch64 -mcpu=apple-a7 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A7 %s // RUN: %clang -target aarch64 -mcpu=apple-a8 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A7 %s // RUN: %clang -target aarch64 -mcpu=apple-a9 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A7 %s // RUN: %clang -target aarch64 -mcpu=apple-a10 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A10 %s // RUN: %clang -target aarch64 -mcpu=apple-a11 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A11 %s // RUN: %clang -target aarch64 -mcpu=apple-a12 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A12 %s // RUN: %clang -target aarch64 -mcpu=apple-a13 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A13 %s // RUN: %clang -target aarch64 -mcpu=apple-s4 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A12 %s // RUN: %clang -target aarch64 -mcpu=apple-s5 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A12 %s // RUN: %clang -target aarch64 -mcpu=cyclone -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-APPLE-A7 %s // RUN: %clang -target aarch64 -mcpu=cortex-a34 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A34 %s // RUN: %clang -target aarch64 -mcpu=cortex-a35 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A35 %s // RUN: %clang -target aarch64 -mcpu=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A53 %s // RUN: %clang -target aarch64 -mcpu=cortex-a57 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A57 %s // RUN: %clang -target aarch64 -mcpu=cortex-a72 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A72 %s // RUN: %clang -target aarch64 -mcpu=cortex-a73 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-CORTEX-A73 %s // RUN: %clang -target aarch64 -mcpu=exynos-m3 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-M1 %s // RUN: %clang -target aarch64 -mcpu=exynos-m4 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-M4 %s // RUN: %clang -target aarch64 -mcpu=exynos-m5 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-M4 %s // RUN: %clang -target aarch64 -mcpu=kryo -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-KRYO %s // RUN: %clang -target aarch64 -mcpu=thunderx2t99 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-THUNDERX2T99 %s // RUN: %clang -target aarch64 -mcpu=a64fx -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-A64FX %s // CHECK-MCPU-APPLE-A7: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crypto" "-target-feature" "+zcm" "-target-feature" "+zcz" "-target-feature" "+sha2" "-target-feature" "+aes" // CHECK-MCPU-APPLE-A10: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+rdm" "-target-feature" "+zcm" "-target-feature" "+zcz" "-target-feature" "+sha2" "-target-feature" "+aes" // CHECK-MCPU-APPLE-A11: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" "-target-feature" "+zcm" "-target-feature" "+zcz" "-target-feature" "+sha2" "-target-feature" "+aes" // CHECK-MCPU-APPLE-A12: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.3a" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+fullfp16" "-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" "-target-feature" "+rcpc" "-target-feature" "+zcm" "-target-feature" "+zcz" "-target-feature" "+sha2" "-target-feature" "+aes" // CHECK-MCPU-A34: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" // CHECK-MCPU-APPLE-A13: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.4a" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+dotprod" "-target-feature" "+fullfp16" "-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" "-target-feature" "+rcpc" "-target-feature" "+zcm" "-target-feature" "+zcz" "-target-feature" "+fp16fml" "-target-feature" "+sm4" "-target-feature" "+sha3" "-target-feature" "+sha2" "-target-feature" "+aes" // CHECK-MCPU-A35: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-A53: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-A57: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-A72: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-CORTEX-A73: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-M1: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-M4: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+dotprod" "-target-feature" "+fullfp16" // CHECK-MCPU-KRYO: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-THUNDERX2T99: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MCPU-A64FX: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+fullfp16" "-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" "-target-feature" "+sve" "-target-feature" "+sha2" // RUN: %clang -target x86_64-apple-macosx -arch arm64 -### -c %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH-ARM64 %s // CHECK-ARCH-ARM64: "-target-cpu" "apple-a7" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crypto" "-target-feature" "+zcm" "-target-feature" "+zcz" // RUN: %clang -target x86_64-apple-macosx -arch arm64_32 -### -c %s 2>&1 | FileCheck --check-prefix=CHECK-ARCH-ARM64_32 %s // CHECK-ARCH-ARM64_32: "-target-cpu" "apple-s4" "-target-feature" "+v8.3a" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+fullfp16" "-target-feature" "+ras" "-target-feature" "+lse" "-target-feature" "+rdm" "-target-feature" "+rcpc" "-target-feature" "+zcm" "-target-feature" "+zcz" "-target-feature" "+sha2" "-target-feature" "+aes" // RUN: %clang -target aarch64 -march=armv8-a+fp+simd+crc+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MARCH-1 %s // RUN: %clang -target aarch64 -march=armv8-a+nofp+nosimd+nocrc+nocrypto+fp+simd+crc+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MARCH-1 %s // RUN: %clang -target aarch64 -march=armv8-a+nofp+nosimd+nocrc+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MARCH-2 %s // RUN: %clang -target aarch64 -march=armv8-a+fp+simd+crc+crypto+nofp+nosimd+nocrc+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MARCH-2 %s // RUN: %clang -target aarch64 -march=armv8-a+nosimd -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MARCH-3 %s // CHECK-MARCH-1: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+fp-armv8" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" // CHECK-MARCH-2: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "-fp-armv8" "-target-feature" "-neon" "-target-feature" "-crc" "-target-feature" "-crypto" // CHECK-MARCH-3: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "-neon" // Check +sm4: // // RUN: %clang -target aarch64 -march=armv8.2a+sm4 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-SM4 %s // CHECK-SM4: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "+sm4" // // Check +sha3: // // RUN: %clang -target aarch64 -march=armv8.2a+sha3 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-SHA3 %s // CHECK-SHA3: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "+sha3" // // Check +sha2: // // RUN: %clang -target aarch64 -march=armv8.3a+sha2 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-SHA2 %s // CHECK-SHA2: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.{{.}}a" "-target-feature" "+sha2" // // Check +aes: // // RUN: %clang -target aarch64 -march=armv8.3a+aes -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-AES %s // CHECK-AES: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.{{.}}a" "-target-feature" "+aes" // // Check -sm4: // // RUN: %clang -target aarch64 -march=armv8.2a+noSM4 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NO-SM4 %s // CHECK-NO-SM4: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "-sm4" // // Check -sha3: // // RUN: %clang -target aarch64 -march=armv8.2a+noSHA3 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NO-SHA3 %s // CHECK-NO-SHA3: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "-sha3" // // Check -sha2: // // RUN: %clang -target aarch64 -march=armv8.2a+noSHA2 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NO-SHA2 %s // CHECK-NO-SHA2: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "-sha2" // // Check -aes: // // RUN: %clang -target aarch64 -march=armv8.2a+noAES -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NO-AES %s // CHECK-NO-AES: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.2a" "-target-feature" "-aes" // // // Arch <= ARMv8.3: crypto = sha2 + aes // ------------------------------------- // // Check +crypto: // // RUN: %clang -target aarch64 -march=armv8a+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO83 %s // RUN: %clang -target aarch64 -march=armv8.1a+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO83 %s // RUN: %clang -target aarch64 -march=armv8.2a+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO83 %s // RUN: %clang -target aarch64 -march=armv8.3a+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO83 %s // RUN: %clang -target aarch64 -march=armv8a+crypto+nocrypto+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO83 %s // CHECK-CRYPTO83: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+crypto" "-target-feature" "+sha2" "-target-feature" "+aes" // // Check -crypto: // // RUN: %clang -target aarch64 -march=armv8a+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO8A %s // RUN: %clang -target aarch64 -march=armv8.1a+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO81 %s // RUN: %clang -target aarch64 -march=armv8.2a+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO82 %s // RUN: %clang -target aarch64 -march=armv8.3a+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO82 %s // RUN: %clang -target aarch64 -march=armv8.3a+nocrypto+crypto+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO82 %s // CHECK-NOCRYPTO8A: "-target-feature" "+neon" "-target-feature" "-crypto" "-target-feature" "-sha2" "-target-feature" "-aes" "-target-abi" "aapcs" // CHECK-NOCRYPTO81: "-target-feature" "+neon" "-target-feature" "+v8.1a" "-target-feature" "-crypto" "-target-feature" "-sha2" "-target-feature" "-aes" "-target-abi" "aapcs" // CHECK-NOCRYPTO82: "-target-feature" "+neon" "-target-feature" "+v8.{{.}}a" "-target-feature" "-crypto" "-target-feature" "-sha2" "-target-feature" "-aes" "-target-feature" "-sm4" "-target-feature" "-sha3" "-target-abi" "aapcs" // // Check +crypto -sha2 -aes: // // RUN: %clang -target aarch64 -march=armv8.1a+crypto+nosha2+noaes -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO83-NOSHA2-NOAES %s // CHECK-CRYPTO83-NOSHA2-NOAES-NOT: "-target-feature" "+sha2" "-target-feature" "+aes" // // Check -crypto +sha2 +aes: // // RUN: %clang -target aarch64 -march=armv8.1a+nocrypto+sha2+aes -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO83-SHA2-AES %s // CHECK-NOCRYPTO83-SHA2-AES: "-target-feature" "+sha2" "-target-feature" "+aes" // // // Arch >= ARMv8.4: crypto = sm4 + sha3 + sha2 + aes // -------------------------------------------------- // // Check +crypto: // // RUN: %clang -target aarch64 -march=armv8.4a+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO84 %s // CHECK-CRYPTO84: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.4a" "-target-feature" "+crypto" "-target-feature" "+sm4" "-target-feature" "+sha3" "-target-feature" "+sha2" "-target-feature" "+aes" // // Check -crypto: // // RUN: %clang -target aarch64 -march=armv8.4a+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-NOCRYPTO84 %s // CHECK-NOCRYPTO84-NOT: "-target-feature" "+crypto" "-target-feature" "+sm4" "-target-feature" "+sha3" "-target-feature" "+sha2" "-target-feature" "+aes" // // Check +crypto -sm4 -sha3: // // RUN: %clang -target aarch64 -march=armv8.4a+crypto+sm4+nosm4+sha3+nosha3 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-CRYPTO84-NOSMSHA %s // CHECK-CRYPTO84-NOSMSHA: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.4a" "-target-feature" "+crypto" "-target-feature" "-sm4" "-target-feature" "-sha3" "-target-feature" "+sha2" "-target-feature" "+aes" // // // RUN: %clang -target aarch64 -mcpu=cyclone+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-1 %s // RUN: %clang -target aarch64 -mcpu=cyclone+crypto+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-1 %s // RUN: %clang -target aarch64 -mcpu=generic+crc -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-2 %s // RUN: %clang -target aarch64 -mcpu=generic+nocrc+crc -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-2 %s // RUN: %clang -target aarch64 -mcpu=cortex-a53+nosimd -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-3 %s // ================== Check whether -mcpu accepts mixed-case features. // RUN: %clang -target aarch64 -mcpu=cyclone+NOCRYPTO -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-1 %s // RUN: %clang -target aarch64 -mcpu=cyclone+CRYPTO+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-1 %s // RUN: %clang -target aarch64 -mcpu=generic+Crc -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-2 %s // RUN: %clang -target aarch64 -mcpu=GENERIC+nocrc+CRC -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-2 %s // RUN: %clang -target aarch64 -mcpu=cortex-a53+noSIMD -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-3 %s // CHECK-MCPU-1: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "-crypto" "-target-feature" "+zcm" "-target-feature" "+zcz" // CHECK-MCPU-2: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" // CHECK-MCPU-3: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "-neon" // RUN: %clang -target aarch64 -mcpu=cyclone+nocrc+nocrypto -march=armv8-a -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-MARCH %s // RUN: %clang -target aarch64 -march=armv8-a -mcpu=cyclone+nocrc+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-MARCH %s // CHECK-MCPU-MARCH: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+zcm" "-target-feature" "+zcz" // RUN: %clang -target aarch64 -mcpu=cortex-a53 -mtune=cyclone -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-MTUNE %s // RUN: %clang -target aarch64 -mtune=cyclone -mcpu=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-MTUNE %s // ================== Check whether -mtune accepts mixed-case features. // RUN: %clang -target aarch64 -mcpu=cortex-a53 -mtune=CYCLONE -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-MTUNE %s // RUN: %clang -target aarch64 -mtune=CyclonE -mcpu=cortex-a53 -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-MCPU-MTUNE %s // CHECK-MCPU-MTUNE: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+crc" "-target-feature" "+crypto" "-target-feature" "+zcm" "-target-feature" "+zcz" // RUN: %clang -target aarch64 -mcpu=generic+neon -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-ERROR-NEON %s // RUN: %clang -target aarch64 -mcpu=generic+noneon -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-ERROR-NEON %s // RUN: %clang -target aarch64 -march=armv8-a+neon -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-ERROR-NEON %s // RUN: %clang -target aarch64 -march=armv8-a+noneon -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-ERROR-NEON %s // CHECK-ERROR-NEON: error: [no]neon is not accepted as modifier, please use [no]simd instead // RUN: %clang -target aarch64 -march=armv8.1a+crypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A-FEATURE-1 %s // RUN: %clang -target aarch64 -march=armv8.1a+nocrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A-FEATURE-2 %s // RUN: %clang -target aarch64 -march=armv8.1a+nosimd -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A-FEATURE-3 %s // ================== Check whether -march accepts mixed-case features. // RUN: %clang -target aarch64 -march=ARMV8.1A+CRYPTO -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A-FEATURE-1 %s // RUN: %clang -target aarch64 -march=Armv8.1a+NOcrypto -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A-FEATURE-2 %s // RUN: %clang -target aarch64 -march=armv8.1a+noSIMD -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-V81A-FEATURE-3 %s // CHECK-V81A-FEATURE-1: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+v8.1a" "-target-feature" "+crypto" // CHECK-V81A-FEATURE-2: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+neon" "-target-feature" "+v8.1a" "-target-feature" "-crypto" // CHECK-V81A-FEATURE-3: "-cc1"{{.*}} "-triple" "aarch64{{.*}}" "-target-feature" "+v8.1a" "-target-feature" "-neon" // ================== Check Memory Tagging Extensions (MTE). // RUN: %clang -target arm64-none-linux-gnu -march=armv8.5-a+memtag -x c -E -dM %s -o - 2>&1 | FileCheck -check-prefix=CHECK-MEMTAG %s // CHECK-MEMTAG: __ARM_FEATURE_MEMORY_TAGGING 1
the_stack_data/86861.c
/* * Kerberos 5 "PA ENC TIMESTAMP" by magnum & Dhiru * * Pcap file -> input file: * 1. tshark -r capture.pcapng -T pdml > ~/capture.pdml * 2. krbng2john.py ~/capture.pdml > krb5.in * 3. Run john on krb5.in * * http://www.ietf.org/rfc/rfc4757.txt * http://www.securiteam.com/windowsntfocus/5BP0H0A6KM.html * * Input format is 'user:$krb5pa$etype$user$realm$salt$timestamp+checksum' * * NOTE: Checksum implies last 12 bytes of PA_ENC_TIMESTAMP value in AS-REQ * packet. * * Default Salt: realm + user * * AES-256 encryption & decryption of AS-REQ timestamp in Kerberos v5 * See the following RFC for more details about the crypto & algorithms used: * * RFC3961 - Encryption and Checksum Specifications for Kerberos 5 * RFC3962 - Advanced Encryption Standard (AES) Encryption for Kerberos 5 * * march 09 / kevin devine <wyse101 0x40 gmail.com> * * This software is Copyright (c) 2012 magnum, and it is hereby released to the * general public under the following terms: Redistribution and use in source * and binary forms, with or without modification, are permitted. * * This software is Copyright (c) 2012 Dhiru Kholia (dhiru at openwall.com) and * released under same terms as above */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_krb5pa_sha1; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_krb5pa_sha1); #else #include <errno.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include "arch.h" #include "misc.h" #include "formats.h" #include "options.h" #include "common.h" #include "unicode.h" #include "config.h" #include "aes.h" #include "krb5_common.h" #include "common-opencl.h" #define OUTLEN 32 #include "opencl_pbkdf2_hmac_sha1.h" #include "hmac_sha.h" #include "loader.h" #define FORMAT_LABEL "krb5pa-sha1-opencl" #define FORMAT_NAME "Kerberos 5 AS-REQ Pre-Auth etype 17/18" /* aes-cts-hmac-sha1-96 */ #define FORMAT_TAG "$krb5pa$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1001 #define BINARY_SIZE 12 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 1 #define MAX_SALTLEN 52 #define MAX_REALMLEN MAX_SALTLEN #define MAX_USERLEN MAX_SALTLEN #define TIMESTAMP_SIZE 44 #define CHECKSUM_SIZE BINARY_SIZE #define TOTAL_LENGTH (14 + 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) + MAX_REALMLEN + MAX_USERLEN + MAX_SALTLEN) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 /* This handles all sizes */ #define GETPOS(i, index) (((index) % ocl_v_width) * 4 + ((i) & ~3U) * ocl_v_width + (((i) & 3) ^ 3) + ((index) / ocl_v_width) * 64 * ocl_v_width) /* This is faster but can't handle size 3 */ //#define GETPOS(i, index) (((index) & (ocl_v_width - 1)) * 4 + ((i) & ~3U) * ocl_v_width + (((i) & 3) ^ 3) + ((index) / ocl_v_width) * 64 * ocl_v_width) static struct fmt_tests tests[] = { {"$krb5pa$18$user1$EXAMPLE.COM$$2a0e68168d1eac344da458599c3a2b33ff326a061449fcbc242b212504e484d45903c6a16e2d593912f56c93883bf697b325193d62a8be9c", "openwall"}, {"$krb5pa$18$user1$EXAMPLE.COM$$a3918bd0381107feedec8db0022bdf3ac56e534ed54d13c62a7013a47713cfc31ef4e7e572f912fa4164f76b335e588bf29c2d17b11c5caa", "openwall"}, {"$krb5pa$18$l33t$EXAMPLE.COM$$98f732b309a1d7ef2355a974842a32894d911e97150f5d57f248e1c2632fbd3735c5f156532ccae0341e6a2d779ca83a06021fe57dafa464", "openwall"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$64dfeee04be2b2e0423814e0df4d0f960885aca4efffe6cb5694c4d34690406071c4968abd2c153ee42d258c5e09a41269bbcd7799f478d3", "password@123"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, {"$krb5pa$18$aduser$AD.EXAMPLE.COM$AD.EXAMPLE.COMaduser$f94f755a8b4493d925094a4eb1cec630ac40411a14c9733a853516fe426637d9daefdedc0567e2bb5a83d4f89a0ad1a4b178662b6106c0ff", "password@12345678"}, /* etype 17 hash obtained using MiTM etype downgrade attack */ {"$krb5pa$17$user1$EXAMPLE.COM$$c5461873dc13665771b98ba80be53939e906d90ae1ba79cf2e21f0395e50ee56379fbef4d0298cfccfd6cf8f907329120048fd05e8ae5df4", "openwall"}, {NULL}, }; static cl_mem mem_in, mem_out, mem_salt, mem_state, pinned_in, pinned_out; static cl_kernel pbkdf2_init, pbkdf2_loop, pbkdf2_final; static struct fmt_main *self; static struct custom_salt { int type; int etype; unsigned char realm[64]; unsigned char user[64]; unsigned char salt[64]; /* realm + user */ unsigned char ct[TIMESTAMP_SIZE]; } *cur_salt; static unsigned char constant[16]; static unsigned char ke_input[16]; static unsigned char ki_input[16]; static size_t key_buf_size; static unsigned int *inbuffer; static pbkdf2_salt currentsalt; static pbkdf2_out *output; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static int new_keys; #define ITERATIONS (4096 - 1) #define HASH_LOOPS 105 // Must be made from factors 3, 3, 5, 7, 13 #define STEP 0 #define SEED 128 static const char * warn[] = { "P xfer: ", ", init: ", ", loop: ", ", inter: ", ", final: ", ", res xfer: " }; static int split_events[] = { 2, -1, -1 }; //This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl_autotune.h" #include "memdbg.h" /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { size_t s; s = autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_init); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_loop)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_final)); return s; } #if 0 struct fmt_main *me; #endif static void create_clobj(size_t gws, struct fmt_main *self) { gws *= ocl_v_width; key_buf_size = 64 * gws; // Allocate memory pinned_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, key_buf_size, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating pinned in"); mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, key_buf_size, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem in"); inbuffer = clEnqueueMapBuffer(queue[gpu_id], pinned_in, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, key_buf_size, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory"); mem_state = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, sizeof(pbkdf2_state) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem_state"); mem_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(pbkdf2_salt), &currentsalt, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem setting"); pinned_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR, sizeof(pbkdf2_out) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating pinned out"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, sizeof(pbkdf2_out) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem out"); output = clEnqueueMapBuffer(queue[gpu_id], pinned_out, CL_TRUE, CL_MAP_READ, 0, sizeof(pbkdf2_out) * gws, 0, NULL, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error mapping page-locked memory"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 2, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_loop, 0, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 0, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 2, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); crypt_out = mem_alloc(sizeof(*crypt_out) * gws); } static void release_clobj(void) { if (crypt_out) { HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_in, inbuffer, 0, NULL, NULL), "Error Unmapping mem in"); HANDLE_CLERROR(clEnqueueUnmapMemObject(queue[gpu_id], pinned_out, output, 0, NULL, NULL), "Error Unmapping mem in"); HANDLE_CLERROR(clFinish(queue[gpu_id]), "Error releasing memory mappings"); HANDLE_CLERROR(clReleaseMemObject(pinned_in), "Release pinned_in"); HANDLE_CLERROR(clReleaseMemObject(pinned_out), "Release pinned_out"); HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release pinned_in"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem_out"); HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem_salt"); HANDLE_CLERROR(clReleaseMemObject(mem_state), "Release mem state"); MEM_FREE(crypt_out); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(pbkdf2_init), "Release Kernel"); HANDLE_CLERROR(clReleaseKernel(pbkdf2_loop), "Release Kernel"); HANDLE_CLERROR(clReleaseKernel(pbkdf2_final), "Release Kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { unsigned char usage[5]; static char valgo[sizeof(ALGORITHM_NAME) + 8] = ""; self = _self; opencl_prepare_dev(gpu_id); /* VLIW5 does better with just 2x vectors due to GPR pressure */ if (!options.v_width && amd_vliw5(device_info[gpu_id])) ocl_v_width = 2; else ocl_v_width = opencl_get_vector_width(gpu_id, sizeof(cl_int)); if (ocl_v_width > 1) { /* Run vectorized kernel */ snprintf(valgo, sizeof(valgo), ALGORITHM_NAME " %ux", ocl_v_width); self->params.algorithm_name = valgo; } // generate 128 bits from 40 bits of "kerberos" string nfold(8 * 8, (unsigned char*)"kerberos", 128, constant); memset(usage,0,sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0xAA; // used to derive Ke nfold(sizeof(usage) * 8, usage, sizeof(ke_input) * 8, ke_input); memset(usage,0,sizeof(usage)); usage[3] = 0x01; // key number in big-endian format usage[4] = 0x55; // used to derive Ki nfold(sizeof(usage) * 8, usage, sizeof(ki_input) * 8, ki_input); } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[128]; snprintf(build_opts, sizeof(build_opts), "-DHASH_LOOPS=%u -DITERATIONS=%u -DOUTLEN=%u " "-DPLAINTEXT_LENGTH=%u -DV_WIDTH=%u", HASH_LOOPS, ITERATIONS, OUTLEN, PLAINTEXT_LENGTH, ocl_v_width); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_kernel.cl", gpu_id, build_opts); pbkdf2_init = clCreateKernel(program[gpu_id], "pbkdf2_init", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); crypt_kernel = pbkdf2_loop = clCreateKernel(program[gpu_id], "pbkdf2_loop", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); pbkdf2_final = clCreateKernel(program[gpu_id], "pbkdf2_final", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); //Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 2 * HASH_LOOPS, split_events, warn, 2, self, create_clobj, release_clobj, ocl_v_width * sizeof(pbkdf2_state), 0, db); //Auto tune execution from shared/included code. autotune_run(self, 4 * ITERATIONS + 4, 0, (cpu(device_info[gpu_id]) ? 1000000000 : 5000000000ULL)); } } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *data = ciphertext; int type, saltlen = 0; // tag is mandatory if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; data += FORMAT_TAG_LEN; // etype field, 17 or 18 p = strchr(data, '$'); if (!p || p - data != 2) return 0; type = atoi(data); if (type < 17 || type > 18) return 0; data = p + 1; // user field p = strchr(data, '$'); if (!p || p - data > MAX_USERLEN) return 0; saltlen += p - data; data = p + 1; // realm field p = strchr(data, '$'); if (!p || p - data > MAX_REALMLEN) return 0; saltlen += p - data; data = p + 1; // salt field p = strchr(data, '$'); if (!p) return 0; // if salt is empty, realm.user is used instead if (p - data) saltlen = p - data; data = p + 1; // We support a max. total salt length of 52. // We could opt to emit a warning if rejected here. if (saltlen > MAX_SALTLEN) { static int warned = 0; if (!ldr_in_pot) if (!warned++) fprintf(stderr, "%s: One or more hashes rejected due to salt length limitation\n", FORMAT_LABEL); return 0; } // 56 bytes (112 hex chars) encrypted timestamp + checksum if (strlen(data) != 2 * (TIMESTAMP_SIZE + CHECKSUM_SIZE) || strspn(data, HEXCHARS_all) != strlen(data)) return 0; return 1; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; char *p; int i; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += FORMAT_TAG_LEN; p = strtokm(ctcopy, "$"); cs.etype = atoi(p); p = strtokm(NULL, "$"); if (p[-1] == '$') cs.user[0] = 0; else { strcpy((char*)cs.user, p); p = strtokm(NULL, "$"); } if (p[-1] == '$') cs.realm[0] = 0; else { strcpy((char*)cs.realm, p); p = strtokm(NULL, "$"); } if (p[-1] == '$') { strcpy((char*)cs.salt, (char*)cs.realm); strcat((char*)cs.salt, (char*)cs.user); } else { strcpy((char*)cs.salt, p); p = strtokm(NULL, "$"); } for (i = 0; i < TIMESTAMP_SIZE; i++) cs.ct[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void clear_keys(void) { memset(inbuffer, 0, key_buf_size); } static void set_key(char *key, int index) { int i; int length = strlen(key); for (i = 0; i < length; i++) ((char*)inbuffer)[GETPOS(i, index)] = key[i]; new_keys = 1; } static char* get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; int i = 0; while (i < PLAINTEXT_LENGTH && (ret[i] = ((char*)inbuffer)[GETPOS(i, index)])) i++; ret[i] = 0; return ret; } static char *split(char *ciphertext, int index, struct fmt_main *pFmt) { static char out[TOTAL_LENGTH + 1]; char in[TOTAL_LENGTH + 1]; char salt[MAX_SALTLEN + 1]; char *data; char *e, *u, *r, *s, *tc; strnzcpy(in, ciphertext, sizeof(in)); tc = strrchr(in, '$'); *tc++ = 0; s = strrchr(in, '$'); *s++ = 0; r = strrchr(in, '$'); *r++ = 0; u = strrchr(in, '$'); *u++ = 0; e = in + 8; /* Default salt is user.realm */ if (!*s) { snprintf(salt, sizeof(salt), "%s%s", r, u); s = salt; } snprintf(out, sizeof(out), "%s%s$%s$%s$%s$%s", FORMAT_TAG, e, u, r, s, tc); data = out + strlen(out) - 2 * (CHECKSUM_SIZE + TIMESTAMP_SIZE) - 1; strlwr(data); return out; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '$') + 1 + TIMESTAMP_SIZE * 2; /* skip to checksum field */ for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; currentsalt.length = strlen((char*)cur_salt->salt); currentsalt.iterations = ITERATIONS; memcpy(currentsalt.salt, cur_salt->salt, currentsalt.length); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, sizeof(pbkdf2_salt), &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int i; int key_size; size_t scalar_gws; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER_VW(count, local_work_size); scalar_gws = global_work_size * ocl_v_width; if (cur_salt->etype == 17) key_size = 16; else key_size = 32; // Copy data to gpu if (ocl_autotune_running || new_keys) { BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, key_buf_size, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); new_keys = 0; } // Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_init, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run initial kernel"); for (i = 0; i < (ocl_autotune_running ? 1 : ITERATIONS / HASH_LOOPS); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_loop, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[2]), "Run loop kernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[3]), "Run intermediate kernel"); for (i = 0; i < (ocl_autotune_running ? 1 : ITERATIONS / HASH_LOOPS); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_loop, 1, NULL, &global_work_size, lws, 0, NULL, NULL), "Run loop kernel (2nd pass)"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[4]), "Run final kernel (SHA1)"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Failed running final kernel"); // Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, sizeof(pbkdf2_out) * scalar_gws, output, 0, NULL, multi_profilingEvent[5]), "Copy result back"); if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < count; i++) { unsigned char base_key[32]; unsigned char Ke[32]; unsigned char plaintext[TIMESTAMP_SIZE]; // pbkdf2((const unsigned char*)saved_key[i], len, (unsigned char *)cur_salt->salt,strlen((char*)cur_salt->salt), 4096, (unsigned int*)tkey); dk(base_key, (unsigned char*)output[i].dk, key_size, constant, 32); dk(Ke, base_key, key_size, ke_input, 32); // Decrypt the AS-REQ timestamp encrypted with 256-bit AES. krb_decrypt(cur_salt->ct, TIMESTAMP_SIZE, plaintext, Ke, key_size); // Check a couple bytes from known plain (YYYYMMDDHHMMSSZ) and // bail out if we are out of luck. if (plaintext[22] == '2' && plaintext[23] == '0' && plaintext[36] == 'Z') { unsigned char Ki[32]; unsigned char checksum[20]; dk(Ki, base_key, key_size, ki_input, 32); // derive checksum of plaintext (only 96 bits used out of 160) hmac_sha1(Ki, key_size, plaintext, TIMESTAMP_SIZE, checksum, 20); memcpy(crypt_out[i], checksum, BINARY_SIZE); } else { memset(crypt_out[i], 0, BINARY_SIZE); } } } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_opencl_krb5pa_sha1 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, { NULL }, { FORMAT_TAG }, tests }, { init, done, reset, fmt_default_prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
the_stack_data/29023.c
#include <stdio.h> #include <string.h> #include <stdlib.h> void parse_response(const char *data, int* time1, int* time2, int* time3); int main() { int a = 0; int b = 0; int c = 0; const char *data = "123/456/789"; parse_response(data, &a, &b, &c); printf("%d\t%d\t%d",a,b, c); } void parse_response(const char *data, int* time1, int* time2, int* time3){ char *str2, *saveptr2; char *del = "/"; char *data2 = strdup(data); int i = 0; for (str2 = data2; ; str2 = NULL) { char *subtoken = strtok_r(str2, del, &saveptr2); if (subtoken == NULL) break; int n=atoi(subtoken); switch (i) { case 1 : *time2 = n; break; case 0 : *time1 = n; break; case 2: *time3 = n; break; } i++; } }
the_stack_data/121592.c
/* ********************* TEXTO SIN ACENTOS *********************/ // Recuerda documentar tus codigos /* Ejemplo de una constante simbolica #define NOMBRE texto */ #include <stdio.h> #define RADIO 2.0; int main() { float r; r= RADIO; printf("RADIO = %f", r); printf("\n"); return 0; }
the_stack_data/226939.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle_() continue; #define myceiling_(w) ceil(w) #define myhuge_(w) HUGE_VAL //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc_(w,s,e,n) dmaxloc_(w,*(s),*(e),n) /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* > \brief \b SLATM7 */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* Definition: */ /* =========== */ /* SUBROUTINE SLATM7( MODE, COND, IRSIGN, IDIST, ISEED, D, N, */ /* RANK, INFO ) */ /* REAL COND */ /* INTEGER IDIST, INFO, IRSIGN, MODE, N, RANK */ /* REAL D( * ) */ /* INTEGER ISEED( 4 ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > SLATM7 computes the entries of D as specified by MODE */ /* > COND and IRSIGN. IDIST and ISEED determine the generation */ /* > of random numbers. SLATM7 is called by SLATMT to generate */ /* > random test matrices. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \verbatim */ /* > MODE - INTEGER */ /* > On entry describes how D is to be computed: */ /* > MODE = 0 means do not change D. */ /* > */ /* > MODE = 1 sets D(1)=1 and D(2:RANK)=1.0/COND */ /* > MODE = 2 sets D(1:RANK-1)=1 and D(RANK)=1.0/COND */ /* > MODE = 3 sets D(I)=COND**(-(I-1)/(RANK-1)) I=1:RANK */ /* > */ /* > MODE = 4 sets D(i)=1 - (i-1)/(N-1)*(1 - 1/COND) */ /* > MODE = 5 sets D to random numbers in the range */ /* > ( 1/COND , 1 ) such that their logarithms */ /* > are uniformly distributed. */ /* > MODE = 6 set D to random numbers from same distribution */ /* > as the rest of the matrix. */ /* > MODE < 0 has the same meaning as ABS(MODE), except that */ /* > the order of the elements of D is reversed. */ /* > Thus if MODE is positive, D has entries ranging from */ /* > 1 to 1/COND, if negative, from 1/COND to 1, */ /* > Not modified. */ /* > */ /* > COND - REAL */ /* > On entry, used as described under MODE above. */ /* > If used, it must be >= 1. Not modified. */ /* > */ /* > IRSIGN - INTEGER */ /* > On entry, if MODE neither -6, 0 nor 6, determines sign of */ /* > entries of D */ /* > 0 => leave entries of D unchanged */ /* > 1 => multiply each entry of D by 1 or -1 with probability .5 */ /* > */ /* > IDIST - CHARACTER*1 */ /* > On entry, IDIST specifies the type of distribution to be */ /* > used to generate a random matrix . */ /* > 1 => UNIFORM( 0, 1 ) */ /* > 2 => UNIFORM( -1, 1 ) */ /* > 3 => NORMAL( 0, 1 ) */ /* > Not modified. */ /* > */ /* > ISEED - INTEGER array, dimension ( 4 ) */ /* > On entry ISEED specifies the seed of the random number */ /* > generator. The random number generator uses a */ /* > linear congruential sequence limited to small */ /* > integers, and so should produce machine independent */ /* > random numbers. The values of ISEED are changed on */ /* > exit, and can be used in the next call to SLATM7 */ /* > to continue the same random number sequence. */ /* > Changed on exit. */ /* > */ /* > D - REAL array, dimension ( MIN( M , N ) ) */ /* > Array to be computed according to MODE, COND and IRSIGN. */ /* > May be changed on exit if MODE is nonzero. */ /* > */ /* > N - INTEGER */ /* > Number of entries of D. Not modified. */ /* > */ /* > RANK - INTEGER */ /* > The rank of matrix to be generated for modes 1,2,3 only. */ /* > D( RANK+1:N ) = 0. */ /* > Not modified. */ /* > */ /* > INFO - INTEGER */ /* > 0 => normal termination */ /* > -1 => if MODE not in range -6 to 6 */ /* > -2 => if MODE neither -6, 0 nor 6, and */ /* > IRSIGN neither 0 nor 1 */ /* > -3 => if MODE neither -6, 0 nor 6 and COND less than 1 */ /* > -4 => if MODE equals 6 or -6 and IDIST not in range 1 to 3 */ /* > -7 => if N negative */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup real_matgen */ /* ===================================================================== */ /* Subroutine */ int slatm7_(integer *mode, real *cond, integer *irsign, integer *idist, integer *iseed, real *d__, integer *n, integer *rank, integer *info) { /* System generated locals */ integer i__1, i__2; doublereal d__1, d__2; /* Local variables */ real temp; integer i__; real alpha; extern /* Subroutine */ int xerbla_(char *, integer *); extern real slaran_(integer *); extern /* Subroutine */ int slarnv_(integer *, integer *, integer *, real *); /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Decode and Test the input parameters. Initialize flags & seed. */ /* Parameter adjustments */ --d__; --iseed; /* Function Body */ *info = 0; /* Quick return if possible */ if (*n == 0) { return 0; } /* Set INFO if an error */ if (*mode < -6 || *mode > 6) { *info = -1; } else if (*mode != -6 && *mode != 0 && *mode != 6 && (*irsign != 0 && * irsign != 1)) { *info = -2; } else if (*mode != -6 && *mode != 0 && *mode != 6 && *cond < 1.f) { *info = -3; } else if ((*mode == 6 || *mode == -6) && (*idist < 1 || *idist > 3)) { *info = -4; } else if (*n < 0) { *info = -7; } if (*info != 0) { i__1 = -(*info); xerbla_("SLATM7", &i__1); return 0; } /* Compute D according to COND and MODE */ if (*mode != 0) { switch (abs(*mode)) { case 1: goto L100; case 2: goto L130; case 3: goto L160; case 4: goto L190; case 5: goto L210; case 6: goto L230; } /* One large D value: */ L100: i__1 = *rank; for (i__ = 2; i__ <= i__1; ++i__) { d__[i__] = 1.f / *cond; /* L110: */ } i__1 = *n; for (i__ = *rank + 1; i__ <= i__1; ++i__) { d__[i__] = 0.f; /* L120: */ } d__[1] = 1.f; goto L240; /* One small D value: */ L130: i__1 = *rank - 1; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = 1.f; /* L140: */ } i__1 = *n; for (i__ = *rank + 1; i__ <= i__1; ++i__) { d__[i__] = 0.f; /* L150: */ } d__[*rank] = 1.f / *cond; goto L240; /* Exponentially distributed D values: */ L160: d__[1] = 1.f; if (*n > 1 && *rank > 1) { d__1 = (doublereal) (*cond); d__2 = (doublereal) (-1.f / (real) (*rank - 1)); alpha = pow_dd(&d__1, &d__2); i__1 = *rank; for (i__ = 2; i__ <= i__1; ++i__) { i__2 = i__ - 1; d__[i__] = pow_ri(&alpha, &i__2); /* L170: */ } i__1 = *n; for (i__ = *rank + 1; i__ <= i__1; ++i__) { d__[i__] = 0.f; /* L180: */ } } goto L240; /* Arithmetically distributed D values: */ L190: d__[1] = 1.f; if (*n > 1) { temp = 1.f / *cond; alpha = (1.f - temp) / (real) (*n - 1); i__1 = *n; for (i__ = 2; i__ <= i__1; ++i__) { d__[i__] = (real) (*n - i__) * alpha + temp; /* L200: */ } } goto L240; /* Randomly distributed D values on ( 1/COND , 1): */ L210: alpha = log(1.f / *cond); i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { d__[i__] = exp(alpha * slaran_(&iseed[1])); /* L220: */ } goto L240; /* Randomly distributed D values from IDIST */ L230: slarnv_(idist, &iseed[1], n, &d__[1]); L240: /* If MODE neither -6 nor 0 nor 6, and IRSIGN = 1, assign */ /* random signs to D */ if (*mode != -6 && *mode != 0 && *mode != 6 && *irsign == 1) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { temp = slaran_(&iseed[1]); if (temp > .5f) { d__[i__] = -d__[i__]; } /* L250: */ } } /* Reverse if MODE < 0 */ if (*mode < 0) { i__1 = *n / 2; for (i__ = 1; i__ <= i__1; ++i__) { temp = d__[i__]; d__[i__] = d__[*n + 1 - i__]; d__[*n + 1 - i__] = temp; /* L260: */ } } } return 0; /* End of SLATM7 */ } /* slatm7_ */
the_stack_data/150139190.c
#include <sched.h> #include <stdlib.h> void __sched_cpufree (cpu_set_t *set) { free (set); } cpu_set_t * __sched_cpualloc (size_t count) { return malloc (__CPU_ALLOC_SIZE (count)); }
the_stack_data/165766159.c
/* Getopt for GNU. NOTE: getopt is now part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to [email protected] before changing it! Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000 Free Software Foundation, Inc. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. Ditto for AIX 3.2 and <stdlib.h>. */ #ifndef _NO_PROTO # define _NO_PROTO #endif #ifdef HAVE_CONFIG_H # include <config.h> #endif #if !defined __STDC__ || !__STDC__ /* This is a separate conditional since some stdc systems reject `defined (const)'. */ # ifndef const # define const # endif #endif #ifdef _MSC_VER #pragma warning (disable: 4131) /* old-style function declaration */ #pragma warning (disable: 4100) /* unreferenced formal parameter */ #endif #include <stdio.h> /* Comment out all this code if we are using the GNU C Library, and are not actually compiling the library itself. This code is part of the GNU C Library, but also included in many other GNU distributions. Compiling and linking in this code is a waste when using the GNU C library (especially if it is a shared library). Rather than having every GNU program understand `configure --with-gnu-libc' and omit the object files, it is simpler to just do this in the source for each such file. */ #define GETOPT_INTERFACE_VERSION 2 #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 # include <gnu-versions.h> # if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION # define ELIDE_CODE # endif #endif #ifndef ELIDE_CODE /* This needs to come after some library #include to get __GNU_LIBRARY__ defined. */ #ifdef __GNU_LIBRARY__ /* Don't include stdlib.h for non-GNU C libraries because some of them contain conflicting prototypes for getopt. */ # include <stdlib.h> # include <unistd.h> #endif /* GNU C library. */ #ifdef VMS # include <unixlib.h> # if HAVE_STRING_H - 0 # include <string.h> # endif #endif #ifndef _ /* This is for other GNU distributions with internationalized messages. When compiling libc, the _ macro is predefined. */ # ifdef HAVE_LIBINTL_H # include <libintl.h> # define _(msgid) gettext (msgid) # else # define _(msgid) (msgid) # endif #endif /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ #include "getopt.h" /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns -1, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* 1003.2 says this must be 1 before any call. */ int optind = 1; /* Formerly, initialization of getopt depended on optind==0, which causes problems with re-calling getopt as programs generally don't know that. */ int __getopt_initialized; /* The next char to be scanned in the option-element in which the last option character we returned was found. This allows us to pick up the scan where we left off. If this is zero, or a null string, it means resume the scan by advancing to the next ARGV-element. */ static char *nextchar; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; /* Describe how to deal with options that follow non-option ARGV-elements. If the caller did not specify anything, the default is REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise. REQUIRE_ORDER means don't recognize them as options; stop option processing when the first non-option is seen. This is what Unix does. This mode of operation is selected by either setting the environment variable POSIXLY_CORRECT, or using `+' as the first character of the list of option characters. PERMUTE is the default. We permute the contents of ARGV as we scan, so that eventually all the non-options are at the end. This allows options to be given in any order, even with programs that were not written to expect this. RETURN_IN_ORDER is an option available to programs that were written to expect options and other ARGV-elements in any order and that care about the ordering of the two. We describe each non-option ARGV-element as if it were the argument of an option with character code 1. Using `-' as the first character of the list of option characters selects this mode of operation. The special argument `--' forces an end of option-scanning regardless of the value of `ordering'. In the case of RETURN_IN_ORDER, only `--' can cause `getopt' to return -1 with `optind' != ARGC. */ static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; /* Value of POSIXLY_CORRECT environment variable. */ static char *posixly_correct; #ifdef __GNU_LIBRARY__ /* We want to avoid inclusion of string.h with non-GNU libraries because there are many ways it can cause trouble. On some systems, it contains special magic macros that don't work in GCC. */ # include <string.h> # define my_index strchr #else # if HAVE_STRING_H # include <string.h> # else # include <strings.h> # endif /* Avoid depending on library functions or files whose names are inconsistent. */ #ifndef getenv extern char *getenv (); #endif static char * my_index (str, chr) const char *str; int chr; { while (*str) { if (*str == chr) return (char *) str; str++; } return 0; } /* If using GCC, we can safely declare strlen this way. If not using GCC, it is ok not to declare it. */ #ifdef __GNUC__ /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. That was relevant to code that was here before. */ # if (!defined __STDC__ || !__STDC__) && !defined strlen /* gcc with -traditional declares the built-in strlen to return int, and has done so at least since version 2.4.5. -- rms. */ extern int strlen (const char *); # endif /* not __STDC__ */ #endif /* __GNUC__ */ #endif /* not __GNU_LIBRARY__ */ /* Handle permutation of arguments. */ /* Describe the part of ARGV that contains non-options that have been skipped. `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is the index after the last of them. */ static int first_nonopt; static int last_nonopt; #ifdef _LIBC /* Bash 2.0 gives us an environment variable containing flags indicating ARGV elements that should not be considered arguments. */ /* Defined in getopt_init.c */ extern char *__getopt_nonoption_flags; static int nonoption_flags_max_len; static int nonoption_flags_len; static int original_argc; static char *const *original_argv; /* Make sure the environment variable bash 2.0 puts in the environment is valid for the getopt call we must make sure that the ARGV passed to getopt is that one passed to the process. */ static void __attribute__ ((unused)) store_args_and_env (int argc, char *const *argv) { /* XXX This is no good solution. We should rather copy the args so that we can compare them later. But we must not use malloc(3). */ original_argc = argc; original_argv = argv; } # ifdef text_set_element text_set_element (__libc_subinit, store_args_and_env); # endif /* text_set_element */ # define SWAP_FLAGS(ch1, ch2) \ if (nonoption_flags_len > 0) \ { \ char __tmp = __getopt_nonoption_flags[ch1]; \ __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ __getopt_nonoption_flags[ch2] = __tmp; \ } #else /* !_LIBC */ # define SWAP_FLAGS(ch1, ch2) #endif /* _LIBC */ /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ #if defined __STDC__ && __STDC__ static void exchange (char **); #endif static void exchange (argv) char **argv; { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ #ifdef _LIBC /* First make sure the handling of the `__getopt_nonoption_flags' string can work normally. Our top argument must be in the range of the string. */ if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) { /* We must extend the array. The user plays games with us and presents new arguments. */ char *new_str = malloc (top + 1); if (new_str == NULL) nonoption_flags_len = nonoption_flags_max_len = 0; else { memset (__mempcpy (new_str, __getopt_nonoption_flags, nonoption_flags_max_len), '\0', top + 1 - nonoption_flags_max_len); nonoption_flags_max_len = top + 1; __getopt_nonoption_flags = new_str; } } #endif while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; register int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; register int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; SWAP_FLAGS (bottom + i, middle + i); } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Initialize the internal data when the first call is made. */ #if defined __STDC__ && __STDC__ static const char *_getopt_initialize (int, char *const *, const char *); #endif static const char * _getopt_initialize (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind; nextchar = NULL; posixly_correct = getenv ("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { ordering = REQUIRE_ORDER; ++optstring; } else if (posixly_correct != NULL) ordering = REQUIRE_ORDER; else ordering = PERMUTE; #ifdef _LIBC if (posixly_correct == NULL && argc == original_argc && argv == original_argv) { if (nonoption_flags_max_len == 0) { if (__getopt_nonoption_flags == NULL || __getopt_nonoption_flags[0] == '\0') nonoption_flags_max_len = -1; else { const char *orig_str = __getopt_nonoption_flags; int len = nonoption_flags_max_len = strlen (orig_str); if (nonoption_flags_max_len < argc) nonoption_flags_max_len = argc; __getopt_nonoption_flags = (char *) malloc (nonoption_flags_max_len); if (__getopt_nonoption_flags == NULL) nonoption_flags_max_len = -1; else memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), '\0', nonoption_flags_max_len - len); } } nonoption_flags_len = nonoption_flags_max_len; } else nonoption_flags_len = 0; #endif return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns -1. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int _getopt_internal (argc, argv, optstring, longopts, longind, long_only) int argc; char *const *argv; const char *optstring; const struct option *longopts; int *longind; int long_only; { int print_errors = opterr; if (optstring[0] == ':') print_errors = 0; optarg = NULL; if (optind == 0 || !__getopt_initialized) { if (optind == 0) optind = 1; /* Don't scan ARGV[0], the program name. */ optstring = _getopt_initialize (argc, argv, optstring); __getopt_initialized = 1; } /* Test whether ARGV[optind] points to a non-option argument. Either it does not have option syntax, or there is an environment flag from the shell indicating it is not an option. The later information is only used when the used in the GNU libc. */ #ifdef _LIBC # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ || (optind < nonoption_flags_len \ && __getopt_nonoption_flags[optind] == '1')) #else # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') #endif if (nextchar == NULL || *nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (last_nonopt > optind) last_nonopt = optind; if (first_nonopt > optind) first_nonopt = optind; if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (last_nonopt != optind) first_nonopt = optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < argc && NONOPTION_P) optind++; last_nonopt = optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != argc && !strcmp (argv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = argc; optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return -1; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (ordering == REQUIRE_ORDER) return -1; optarg = argv[optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[optind][1] == '-' || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = -1; int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if ((unsigned int) (nameend - nextchar) == (unsigned int) strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) fprintf (stderr, _("%s: option `%s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; optopt = 0; return '?'; } if (pfound != NULL) { option_index = indfound; optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) { if (argv[optind - 1][1] == '-') /* --option */ fprintf (stderr, _("%s: option `--%s' doesn't allow an argument\n"), argv[0], pfound->name); else /* +option or -option */ fprintf (stderr, _("%s: option `%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); } nextchar += strlen (nextchar); optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[optind][1] == '-' || my_index (optstring, *nextchar) == NULL) { if (print_errors) { if (argv[optind][1] == '-') /* --option */ fprintf (stderr, _("%s: unrecognized option `--%s'\n"), argv[0], nextchar); else /* +option or -option */ fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), argv[0], argv[optind][0], nextchar); } nextchar = (char *) ""; optind++; optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *nextchar++; char *temp = my_index (optstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == '\0') ++optind; if (temp == NULL || c == ':') { if (print_errors) { if (posixly_correct) /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); else fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); } optopt = c; return '?'; } /* Convenience. Treat POSIX -W foo same as long option --foo */ if (temp[0] == 'W' && temp[1] == ';') { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound = 0; int option_index; /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; return c; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; /* optarg is now the argument, see if it's in the table of longopts. */ for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if ((unsigned int) (nameend - nextchar) == strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (print_errors) fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; return '?'; } if (pfound != NULL) { option_index = indfound; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (print_errors) fprintf (stderr, _("\ %s: option `-W %s' doesn't allow an argument\n"), argv[0], pfound->name); nextchar += strlen (nextchar); return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (print_errors) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } nextchar = NULL; return 'W'; /* Let the application handle it. */ } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != '\0') { optarg = nextchar; optind++; } else optarg = NULL; nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (print_errors) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; nextchar = NULL; } } return c; } } int getopt (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { return _getopt_internal (argc, argv, optstring, (const struct option *) 0, (int *) 0, 0); } #endif /* Not ELIDE_CODE. */ #ifdef TEST /* Compile with -DTEST to make an executable for use in testing the above definition of `getopt'. */ int main (argc, argv) int argc; char **argv; { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; c = getopt (argc, argv, "abc:d:0123456789"); if (c == -1) break; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value `%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); } #endif /* TEST */
the_stack_data/64074.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <stdbool.h> #include <pthread.h> #include <sys/time.h> #include <limits.h> // Global variables for matrices' dimensions int a_row, a_col, b_row, b_col; struct element_data { int **a, **b, **c; int i, j; }; // Read each matrix from file and put elements in 2d array of integers // b_input boolean to switch between 1st matrix file and 2nd matrix file, also helps in confirming dimensions int **read_file(char *file_path, bool b_input) { FILE *fptr = fopen(file_path, "r"); // Open file in read mode if (fptr == NULL) { // Check if file doesn't exist fprintf(stderr, "Cannot open one of the files\n"); exit(1); } // Take row and column of matrix int row, col; // If the returned number of inputs taken is not 2 (row & column) exits and print error // Or if row and column numbers are not integers if (fscanf(fptr, "row=%d col=%d\n", &row, &col) != 2) { fprintf(stderr, "Cannot get row or column number\n"); exit(1); } // Switch between taking input of a matrix or b matrix if (!b_input) { a_row = row, a_col = col; } else { b_row = row, b_col = col; // Check for dimensions can multiply after taking dimensions of 2nd matrix if (a_col != b_row) { fprintf(stderr, "1st matrix column size doesn't match 2nd matrix row size\n"); exit(1); } } // Allocate 2d array storing matrix elements int **arr = (int **) malloc(row * sizeof(int *)); for (int i = 0; i < row; ++i) { arr[i] = (int *) malloc(col * sizeof(int)); } // Taking input line by line from file, then split it according to delimiters, // then check each token is made of numbers only and smaller than INT_MAX char *line = NULL, *delim = " \n\t"; size_t len = 0; char *split; for (int i = 0; i < row; ++i) { if (getline(&line, &len, fptr) != -1) { // Taking line from file split = strtok(line, delim); // Split line according to delimiters for (int j = 0; j < col; ++j) { if (split == NULL) { // Check if there is missing element fprintf(stderr, "Wrong number of elements in row %d\n", i + 1); exit(1); } // Check if number is negative and not a sign only bool neg = (split[0] == '-'); if (neg && strlen(split) == 1) { fprintf(stderr, "Element at row %d column %d is not numeric only\n", i + 1, j + 1); exit(1); } // Check string if there is non digit int k = neg; for (; k < strlen(split); ++k) { if (!isdigit(split[k])) { fprintf(stderr, "Element at row %d column %d is not numeric only\n", i + 1, j + 1); exit(1); } } // Check if string has digits greater than that of int int max_digits_int = 10; if (k > max_digits_int) { fprintf(stderr, "Element size is greater than int at row %d column %d\n", i + 1, j + 1); exit(1); } arr[i][j] = atoi(split); // Convert string to int and put in array split = strtok(NULL, delim); // Continue looping through tokens } } else { fprintf(stderr, "Cannot read matrix elements\n"); exit(1); } } fclose(fptr); // Close file pointer and return array return arr; } // Check for multiplication overflow int mult_overflow(int x, int y, int i, int j) { int z = x * y; if (x != 0 && z / x != y) { fprintf(stderr, "Overflow will occur while computing element at row %d column %d\n", i + 1, j + 1); exit(1); } return z; } // Check for addition overflow int add_overflow(int x, int y, int i, int j) { if (x >= 0) { if (INT_MAX - x < y) { // Overflow will occur fprintf(stderr, "Overflow will occur while computing element at row %d column %d\n", i + 1, j + 1); exit(1); } } else { if (y < INT_MIN - x) { fprintf(stderr, "Overflow will occur while computing element at row %d column %d\n", i + 1, j + 1); exit(1); } } return x + y; } // Non threaded matrix multiplication used for testing void compute(int **a, int **b, int **c) { for (int i = 0; i < a_row; ++i) { for (int j = 0; j < b_col; ++j) { c[i][j] = 0; for (int k = 0; k < a_col; ++k) { c[i][j] += a[i][k] * b[k][j]; } } } } // Compute each row of output in a separate thread void *compute_for_row(void *tdata) { // Retrieve thread data struct element_data *row_data; row_data = (struct element_data *) tdata; int i = row_data->i; int **a = row_data->a, **b = row_data->b, **c = row_data->c; for (; i < a_row; ++i) { for (int j = 0; j < b_col; ++j) { c[i][j] = 0; for (int k = 0; k < a_col; ++k) { // Check for overflow while adding or multiplying int tmp = mult_overflow(a[i][k], b[k][j], i, j); c[i][j] = add_overflow(c[i][j], tmp, i, j); } } } pthread_exit(NULL); } // Compute each element of output in a separate thread void *compute_for_element(void *tdata) { // Retrieve thread data struct element_data *e_data; e_data = (struct element_data *) tdata; int i = e_data->i, j = e_data->j; int **a = e_data->a, **b = e_data->b, **c = e_data->c; c[i][j] = 0; for (int k = 0; k < a_col; ++k) { // Check for overflow while adding or multiplying int tmp = mult_overflow(a[i][k], b[k][j], i, j); c[i][j] = add_overflow(c[i][j], tmp, i, j); } pthread_exit(NULL); } // Create thread for each row to be computed void thread_for_row(int **a, int **b, int **c) { pthread_t threads[a_row]; int rc; for (int i = 0; i < a_row; ++i) { struct element_data *tdata = malloc(sizeof(struct element_data)); tdata->a = a, tdata->b = b, tdata->c = c; tdata->i = i; rc = pthread_create(&threads[i], NULL, compute_for_row, (void *) tdata); if (rc) { // Check if thread is not created fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } // Join threads for (int i = 0; i < a_row; ++i) { pthread_join(threads[i], NULL); if (rc) { // Check if thread is not joined fprintf(stderr, "ERROR; return code from pthread_join() is %d\n", rc); exit(-1); } } printf("Thread for each row method: \nNumber of threads: %d\n", a_row); } // Create thread for each element to be computed void thread_for_element(int **a, int **b, int **c) { pthread_t threads[a_row * b_col]; int rc; for (int i = 0; i < a_row; ++i) { for (int j = 0; j < b_col; ++j) { struct element_data *tdata = malloc(sizeof(struct element_data)); tdata->a = a, tdata->b = b, tdata->c = c; tdata->i = i, tdata->j = j; rc = pthread_create(&threads[i * b_col + j], NULL, compute_for_element, (void *) tdata); if (rc) { // Check if thread is not created fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } } // Join threads for (int i = 0; i < a_row; ++i) { for (int j = 0; j < b_col; ++j) { pthread_join(threads[i * b_col + j], NULL); if (rc) { // Check if thread is not joined fprintf(stderr, "ERROR; return code from pthread_join() is %d\n", rc); exit(-1); } } } printf("Thread for each element method: \nNumber of threads: %d\n", a_row * b_col); } // Writes output array to a file specified by user void write_output(int **c, char *file_path) { FILE *fptr = fopen(file_path, "w"); fprintf(fptr, "row=%d col=%d\n", a_row, b_col); for (int i = 0; i < a_row; ++i) { for (int j = 0; j < b_col; ++j) { if (j != b_col - 1) { fprintf(fptr, "%d\t", c[i][j]); } else { fprintf(fptr, "%d\n", c[i][j]); } } } fclose(fptr); } // Prints output array to terminal, used in testing void show(int **c) { for (int i = 0; i < a_row; ++i) { for (int j = 0; j < b_col; ++j) { printf("%d ", c[i][j]); } printf("\n"); } } int main(int argc, char *argv[]) { // Default files' names char *mat_a_path = "a.txt", *mat_b_path = "b.txt", *mat_c_path = "c.out"; // Taking arguments if exist if (argc == 2) { mat_a_path = argv[1]; } else if (argc == 3) { mat_a_path = argv[1]; mat_b_path = argv[2]; } else if (argc == 4) { mat_a_path = argv[1]; mat_b_path = argv[2]; mat_c_path = argv[3]; } else if (argc > 4) { // Print error if too many arguments fprintf(stderr, "Too many arguments\n"); exit(1); } // Read each matrix from file and put elements in 2d array of integers int **a = read_file(mat_a_path, 0); int **b = read_file(mat_b_path, 1); // Allocate memory for output matrix int **c = (int **) malloc(a_row * sizeof(int *)); for (int i = 0; i < a_row; ++i) { c[i] = (int *) malloc(b_col * sizeof(int)); } // // Non threaded matrix multiplication for testing // compute(a, b, c); // show(c); // Calculating time taken for running 1st method (thread for row) struct timeval start, stop; gettimeofday(&start, NULL); thread_for_row(a, b, c); gettimeofday(&stop, NULL); printf("Seconds taken %lu\n", stop.tv_sec - start.tv_sec); printf("Microseconds taken: %lu\n", stop.tv_usec - start.tv_usec); // show(c); // Calculating time taken for running 2nd method (thread for element) gettimeofday(&start, NULL); thread_for_element(a, b, c); gettimeofday(&stop, NULL); printf("Seconds taken %lu\n", stop.tv_sec - start.tv_sec); printf("Microseconds taken: %lu\n", stop.tv_usec - start.tv_usec); // show(c); write_output(c, mat_c_path); // Write output matrix to file // Free allocated memory free(a); free(b); free(c); return 0; }
the_stack_data/43732.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_rot42.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: drosa-ta <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/20 14:52:25 by drosa-ta #+# #+# */ /* Updated: 2017/01/20 16:20:32 by drosa-ta ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_rot42(char *str) { int new_val; int limit; char c; int i; i = 0; while (str[i]) { c = str[i]; if (c >= 'a' && c <= 'z') limit = 'z'; else if (c >= 'A' && c <= 'Z') limit = 'Z'; if (str[i] + 42 > limit) { c = (limit - 25); str[i] += 42 - (limit - c); } else c = 42; str[i] += c; i++; } return (str); }
the_stack_data/84532.c
// KASAN: use-after-free Read in tipc_mcast_xmit // https://syzkaller.appspot.com/bug?id=faf19370eca3f1fd1531 // status:0 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static int inject_fault(int nth) { int fd; fd = open("/proc/thread-self/fail-nth", O_RDWR); if (fd == -1) exit(1); char buf[16]; sprintf(buf, "%d", nth + 1); if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf)) exit(1); return fd; } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); for (int i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } static void setup_fault() { static struct { const char* file; const char* val; bool fatal; } files[] = { {"/sys/kernel/debug/failslab/ignore-gfp-wait", "N", true}, {"/sys/kernel/debug/fail_futex/ignore-private", "N", false}, {"/sys/kernel/debug/fail_page_alloc/ignore-gfp-highmem", "N", false}, {"/sys/kernel/debug/fail_page_alloc/ignore-gfp-wait", "N", false}, {"/sys/kernel/debug/fail_page_alloc/min-order", "0", false}, }; unsigned i; for (i = 0; i < sizeof(files) / sizeof(files[0]); i++) { if (!write_file(files[i].file, files[i].val)) { if (files[i].fatal) exit(1); } } } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter = 0; for (;; iter++) { int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } } } uint64_t r[1] = {0xffffffffffffffff}; void execute_one(void) { intptr_t res = 0; res = syscall(__NR_socket, 0x1eul, 2ul, 0); if (res != -1) r[0] = res; *(uint64_t*)0x20000380 = 0x20000080; *(uint16_t*)0x20000080 = 0x1e; *(uint8_t*)0x20000082 = 1; *(uint8_t*)0x20000083 = 0; *(uint32_t*)0x20000084 = 1; *(uint32_t*)0x20000088 = 0; *(uint32_t*)0x2000008c = 1; *(uint32_t*)0x20000388 = 0x10; *(uint64_t*)0x20000390 = 0x20000240; *(uint64_t*)0x20000240 = 0x20000b80; memcpy( (void*)0x20000b80, "\xe9\x3f\x39\x95\xae\x1b\x38\x85\xf0\xf3\x1d\xd9\xc4\x5b\x08\x79\x80\x7b" "\x0b\x3b\x01\xbd\x11\xa5\xd6\xa1\x12\x16\x9d\x78\xf2\x00\xc0\xa8\x5d\xe5" "\xd5\xb3\x7c\x25\x21\x5d\x1c\x56\x13\xe2\x6d\x8e\x9c\x87\x48\xd5\x79\xa6" "\x5f\x4d\x1a\x19\xcf\x6f\x4c\x1e\x18\xe8\x88\xf2\x5d\xb6\x39\x18\xa3\x62" "\x74\x39\x58\x78\xbf\xa3\xcf\xd4\x9f\x80\xf2\xc3\x25\xa8\x54\x55\xc0\x1e" "\x41\xd0\xcc\xaa\xf8\x39\x74\xf4\xca\x43\xf0\xd1\xaf\xe8\xd1\x01\xbb\x24" "\x86\x56\xc6\x2d\x51\x0d\x97\x3e\x83\x5b\x20\x6a\x22\xb6\xcb\x85\x7b\x33" "\x9d\x18\x86\x5d\x03\x25\xfd\xf9\xf1\x51\xc6\xf4\xb0\x45\xf5\x1f\x58\xe2" "\x6f\xaa\x9e\x15\xea\xab\xa1\xc2\x1c\xf7\xb3\xb7\x05\x00\x96\xd9\x0b\x9c" "\x42\x86\xfb\x51\x58\x6f\x35\x5c\x40\xbd\xb3\x28\xc3\x28\xfa\x03\xc5\x20" "\x8f\xe3\xea\x9b\x50\x03\x94\xa4\x12\x55\x3c\x71\xbd\x3a\xd6\x74\x16\x9f" "\x57\x15\x29\x0e\x18\x4a\x92\x97\xf8\xe3\xb1\x20\xab\x16\x70\x57\x8a\x3b" "\x7d\xa6\x3b\xb5\x90\x1f\x33\x77\x9b\x11\xff\x65\x1d\x63\x2d\xa7\x52\x15" "\x4e\xa6\x53\xef\xfd\x6c\x92\x69\x61\x5b\xde\xb1\xc0\x42\xc4\xad\x24\x32" "\xb9\x15\x35\xfb\x9e\xeb\xf9\x20\x19\x46\x21\xe2\x25\x0c\x9b\xed\x25\x33" "\x67\xf7\x6e\x18\x5d\x65\xe3\x17\xe9\x1b\xbb\x6d\x76\x14\x11\x37\x93\xb0" "\x60\xe0\x79\xe7\x85\x2b\x7f\x37\xc1\x4e\x0f\x0a\x8f\x73\xe1\x8c\x4a\x2b" "\x5b\x54\x75\xc0\xbd\xec\xfd\x9e\xe6\x18\xbe\x20\xe8\x4b\x74\x0d\x0a\x15" "\xa1\xd9\x95\x9e\x90\x17\x4d\x8c\x2e\xf5\xf6\x39\x25\x8e\x2f\xbf\x43\x2d" "\x7c\x59\x87\xee\xdc\x15\x13\x22\x0d\xf4\x37\x4c\x6d\xaf\xe0\x6f\x7c\x56" "\x27\x67\x95\x6e\x0f\xa7\x59\x3f\x67\xd2\x7e\x7a\xbc\xe5\xe3\xed\x64\xb0" "\x92\x8f\x3f\x2d\x85\x12\x06\xaf\x0d\x33\x97\xcc\x36\x86\xf0\xf2\xa5\xf8" "\x77\xdb\x29\x5a\x4f\x86\xf6\x7d\x34\x48\xbc\xfa\x60\x60\x07\x01\x3d\x23" "\x17\x96\x35\x3f\x65\xab\x81\x4d\x8c\xc4\xe7\x47\xdc\x2d\x5f\x4a\x1c\xad" "\xe8\x71\x92\x9e\xe0\x2e\xc8\x7a\x7e\xef\xac\x71\xfd\x84\x95\xf3\xa5\x66" "\x51\x66\xd2\x7b\x7f\x1d\x58\x99\x24\xfb\xc5\xc7\xc2\xc9\xa4\x42\xf4\xb0" "\xa6\x65\xe6\xa8\xc6\x5f\x45\x02\xb5\x77\x62\x82\x96\x24\x48\xb8\xc8\x41" "\xff\xc6\x55\xeb\x32\xfb\x00\xd0\xde\x81\x8c\x6f\x73\xdb\x19\x24\x95\x6c" "\xe3\x1b\x9c\x61\x13\x56\xaa\x9c\x62\xb3\x0f\x04\x40\xe5\xb7\xaa\x7c\xb7" "\x12\xe3\xa2\x5b\xfb\x85\x63\x15\xb7\xb7\x51\x38\xce\xbc\x35\xc5\xf6\x3a" "\xb6\x39\x83\xa1\xbf\x28\x5a\x25\x0e\x90\x3d\x3c\xe9\xa0\x58\x40\x38\xea" "\x37\xd3\xfc\x52\xde\x74\xe1\xf9\xbb\x43\x64\x1a\x7a\xb7\x28\x8f\x93\x90" "\xb6\x06\x24\xf6\xfb\xf8\xd7\xf1\x6d\x6a\x02\xc9\xa9\x43\xfa\x10\xfa\xcf" "\x80\xa3\x45\xac\xbf\xfe\xa7\x2b\x2b\xd7\x16\x13\x8d\xe0\x78\x5f\x23\xdd" "\xda\x7c\xb2\x6c\x4d\xa4\xc8\xa0\x70\x1b\x9c\x8d\x6f\x43\x87\x6f\x6d\xf2" "\x14\x53\xf8\x39\x7d\x32\xe7\x01\xa7\x19\xe8\xc4\xb8\x54\x2e\x39\x0b\x05" "\x4b\x80\x07\xa6\x72\xad\xbc\x22\x99\x4e\x85\x87\xd9\xf7\x19\x50\x9f\xbf" "\x61\xf2\x16\x8f\xc3\xb2\x4c\xad\x3d\x30\x96\xd7\xab\x31\x34\xb8\xd9\xc6" "\xa4\x0d\xf8\xb6\x16\x27\x02\x8a\x54\xd5\xa3\x4d\xe2\x28\x17\xa9\xd7\x58" "\x83\x91\xa1\xb3\xb4\x82\x70\x90\x16\x99\x7b\x3a\x13\x32\xc7\xc3\xb2\xe6" "\x01\x3c\xa5\xd5\xc1\xf3\xe5\xa1\xd3\x23\x1e\x9f\x2f\x63\xdf\x48\x26\xa8" "\x67\xf1\xa9\x97\xb6\xac\x9c\x77\xa5\x3a\x21\x0e\x59\xd1\x2c\x34\x3a\x32" "\x64\x69\x04\x1b\xbd\x09\xa3\x38\xfb\x97\xa9\xea\x1e\xcf\xf6\x6e\x2c\x72" "\x93\xca\xc8\x24\xd8\x4f\x89\xd6\x7e\xa4\xa0\x27\xd3\x9e\xe7\x2a\x81\x07" "\xad\x11\x5b\x25\x39\xde\xcc\xb8\xbf\x3a\x8a\xce\x57\xa9\x4d\xf8\xca\x4e" "\x10\x88\xd1\xaf\x1d\x35\xc1\x6a\x3e\xca\x7c\x98\xcc\xbb\xe3\x25\x56\xe8" "\x60\x6b\x62\xd3\xe4\xfb\xb7\xfb\xd7\x0f\xa0\x0d\x58\xb2\xc1\xcd\xa6\x26" "\xfb\x26\xf9\x17\x62\x03\xa8\xbb\x3b\x9b\x9e\x91\x9d\xbb\xde\xde\x3e\x99" "\xfb\xf3\xf0\x99\xea\x67\x8f\xe4\x0a\x42\x19\x50\x0a\x7d\x0a\xfb\xf8\xd5" "\xc5\x07\xf5\xc3\x97\x6d\xda\xc3\xb9\xd9\xd7\x03\xcc\xfc\x6e\xe9\x2a\x0d" "\x9a\xec\x2a\xd6\xa2\x08\x43\x0d\xa6\xc8\x8e\xf2\x44\x44\x19\x2d\x14\xec" "\x26\x08\xa4\x31\x99\xc5\xc6\x5a\xf8\x31\x2f\xa4\x64\x26\x60\x6f\x95\xaa" "\x68\xed\x4c\x90\xe7\x0c\xc8\xe9\x40\x7b\x6d\x80\x5d\x12\x31\x32\x20\x10" "\xcd\xec\xe9\xb2\x02\x2f\x02\x84\xd7\xe3\xf9\xd1\x2c\xca\xb5\x78\x97\x26" "\x51\x31\x98\xeb\x63\x20\x2d\x71\x68\x54\x7d\x7a\x4a\x0e\xca\x53\x60\x4d" "\xd6\xb9\x96\x0e\x70\x3d\xa1\xf8\x79\xd6\x93\x78\x1c\x95\x7b\x58\xbd\x2f" "\xcf\x1d\x25\x9b\x3a\x66\x92\x16\x0d\xa3\x78\xe3\x5e\x38\xa4\x8f\x11\x91" "\xe0\xbb\x80\xf1\x2e\xeb\x62\x9a\x37\x02\x82\x18\x44\x91\x5b\xb1\x6e\xd6" "\x9d\xf5\xec\x12\xb9\x74\x95\xd5\xd4\x1f\xca\x24\x0b\xf1\x8e\xa6\x1a\x67" "\x48\xd9\xa1\xd1\x0c\x21\xed\xfc\xa8\x71\xfa\xb3\xea\x30\x33\x3e\x51\x13" "\x58\x0f\x50\xc6\x00\x34\x31\xb3\x59\x0a\x23\x06\x0c\x7c\x5f\x22\xa6\x15" "\x21\x56\xb8\x3f\xed\xef\x43\x58\xd6\xd1\x1f\x6d\x7b\x84\x28\xf5\x14\xd4" "\x23\x51\xc3\x5d\xda\x08\x1c\xa2\xe9\x5f\x66\xb7\x53\xb1\x75\x3f\x16\xda" "\x63\xa2\xae\xb3\xab\x42\xd2\xb9\x23\xc4\xaa\x01\x7d\xd0\x8a\x8e\x1f\xc9" "\x24\x52\xfb\xd3\x98\x32\x00\x81\x0d\x32\x04\xf1\xc4\x0f\xd7\xc9\x4e\x4c" "\x5d\x0b\x06\x55\x30\x8e\xf1\x1c\xbf\x6c\x9c\x3a\x58\x45\xf9\x69\x3b\x14" "\x25\xeb\xdd\x93\x73\xa7\xfb\x42\x08\xc1\x6a\xf3\x01\xb0\x48\xaa\xd2\x1f" "\x6e\x3d\xd6\x93\xc4\x63\xa3\x75\xed\x40\x48\x64\x58\x47\xfd\x10\x7f\x7e" "\xd6\xe8\xb1\x3d\x08\x85\x40\x71\x72\x8a\xf3\x45\xd6\x0e\x24\x24\x03\x32" "\xab\x7e\x27\xf8\x4b\x81\xb0\x1c\x75\x5c\xab\x73\x59\xc8\xfb\x51\xb4\x3c" "\x01\x1c\x70\x70\x08\x1b\x95\x4a\x34\xba\x48\x18\x95\xf5\x6a\x32\x24\x3e" "\x0b\x09\xdd\x0c\x4d\xbb\x73\xe6\x98\xc7\xce\xe6\x6a\x1d\xf0\x57\xee\xbb" "\xb7\x13\x1c\x35\x91\x23\x3f\x10\x13\x79\x44\x0f\x5a\x05\xaa\xe5\x44\x10" "\x34\xdf\x66\xb3\x8f\x68\x4d\xcd\xa7\x5d\x99\x87\x06\xcb\x61\xb0\xc6\x50" "\x99\x00\x08\x1b\xfd\xbf\x71\x3c\x85\xcc\x45\xcf\x19\x62\xa5\x94\xc7\xea" "\xeb\xee\x8a\xfd\x4a\x71\xd4\x5a\x06\x5e\xe7\x94\x3d\x87\x70\x10\x97\x1d" "\x2c\x49\x4d\x1d\xee\x62\x29\x0c\xbf\x39\xc7\x03\x43\xb3\x38\x43\xa8\x01" "\x45\x9e\xab\xa2\xf6\x63\x85\xad\xa7\x04\xcd\x6a\x67\x14\xc8\xae\xd7\xaf" "\x1e\xe3\x92\x23\xdc\x39\x81\x03\xeb\x20\xb1\xed\x13\xba\x8a\x4e\x7f\xa7" "\xc3\xe1\x34\x63\x1d\x78\x6c\x64\xee\xe3\xa7\x63\x1b\x64\x5d\x26\xe3\xbc" "\xc4\x06\x48\x35\x1b\xa7\x63\x89\x41\xb2\xe9\x66\x92\x98\x61\x52\x5d\x5b" "\x6c\xe3\xd0\x61\x87\x7c\x25\x10\x62\xda\x21\x47\x5a\x66\xe7\xf1\x4a\x32" "\x11\x62\x04\x78\x7f\xef\xe4\xce\xe1\xae\x70\xe5\x16\x0d\x6c\x4d\x0b\x95" "\x7d\x59\x42\x8f\xc2\x89\x41\xd5\x82\xae\x5b\x9d\x97\x8e\x32\x00\xe5\xc6" "\x2d\x47\x40\x51\x47\xb6\xeb\x90\xc5\xc9\x49\x89\x49\xd1\x7c\xfe\xfa\x95" "\x17\x7b\x97\xfa\x4e\xa0\x15\x6c\x41\xf6\xba\xca\x65\xb1\x05\xe2\x85\x52" "\x3f\xed\x27\x4c\x84\x4a\x8d\xab\xce\xa4\x18\xb8\xd7\x9c\xd3\x53\xcf\xf2" "\x86\xf1\x3f\x8f\xf7\x15\x06\xbe\xee\xf4\x89\xaa\xa0\x95\x40\xf2\xf1\x0d" "\x06\x72\x81\x9c\x33\xe4\x2e\xda\x76\x17\x21\x07\xab\x6f\x40\x9c\xda\xd2" "\xed\x67\x48\x13\xd6\x9c\x94\x19\x55\xed\x95\x42\xfc\x14\xed\x3f\xfe\xe0" "\xfb\x5a\x01\xf8\x91\x03\xe0\xa9\xaa\x78\xe9\x17\xf0\xc8\x50\xbd\x78\x9e" "\xfc\xfa\xb8\x63\x4c\xcf\x36\x32\xf3\x85\xbd\x2d\x0f\x64\xf9\x30\xc6\xf2" "\xb8\x3e\xd7\x1a\xbd\x75\xc7\x01\x55\x13\x54\xc1\x6b\x15\x43\x08\xe6\xd5" "\xd0\xc4\xab\xc7\x55\x8d\xd7\xc7\x69\xb4\x41\x3d\x33\x0a\xfd\x63\x80\x8a" "\x83\xb0\x5a\x1d\xeb\x58\x6a\x29\xf4\xcc\x87\x94\xf8\xc9\xba\xd4\xa3\x4b" "\x16\x26\x14\x9b\xd8\x68\xa2\x96\x2c\x8b\x7e\x55\x86\x0d\xb7\x56\xf6\x3b" "\x5b\x79\xfe\x55\x43\x36\x18\xda\x2e\x9b\x50\x79\xb4\x85\xea\x09\x19\x93" "\x33\x1d\xeb\x35\x26\xae\x79\xfc\xc0\x6e\x5d\x00\x77\x95\x38\x11\xe1\x04" "\x80\x0b\x16\x8b\x8c\x46\x81\x87\x99\x18\x9e\xd1\xfb\xb9\xa9\x9e\xe3\x62" "\x8f\xd6\xe3\xec\xb3\xdc\x8c\xa0\xfb\xe5\xf9\x00\xdd\x6f\x75\x26\x65\xf0" "\xa5\xf5\xd8\x1f\x3c\x01\xed\x4f\x51\x5d\x16\x14\x16\x28\x08\x3b\x45\xca" "\x45\x29\xc7\x2c\x2d\x6f\xb1\xdd\x92\x8a\xbb\x4d\x22\xef\xa1\x89\xd9\xdc" "\xd9\x0f\x64\xf9\x7c\x33\xd4\xcd\x23\x2b\xe3\xf1\x27\x35\x29\xc7\x8e\x8c" "\x73\xa1\x2a\x7b\xcf\x2c\x10\x8d\xac\x29\x2c\x2b\x54\x22\x23\x1b\xdf\x49" "\xb8\x70\x1c\x22\x22\x91\x2b\x6c\x91\xff\x4c\x7a\x2b\xa0\x4c\xd9\x20\x3b" "\xfa\x71\xc6\x93\x21\xcf\xde\xfc\x20\xd0\x00\x99\x34\xa1\x2b\x0c\xfd\xe1" "\xe1\xb7\xaf\x10\x74\xfc\x72\xa7\xd5\xe0\x18\x38\x95\xf2\x0c\x76\x18\x88" "\x98\x13\xbf\x5f\x9b\x70\xa1\xc4\x41\x28\xb1\x1b\x64\xee\xc2\x74\x31\x40" "\xc8\x57\x11\x55\x91\xf0\x97\x6e\xef\x7d\x5b\x31\x9f\x2d\x2b\xbe\x07\x48" "\xd5\x54\xe4\x89\x0e\x42\xb1\x29\xdf\xdb\x3a\x8c\xe9\xb3\xde\x46\xe6\xa8" "\x36\xcd\x57\xd5\x5f\xdc\x9f\x1c\x1c\xda\xda\xd5\x8d\xc4\xf4\x31\xaf\xad" "\xb9\x7b\xe9\x02\x7e\xcb\xbf\xab\x4b\xe1\x89\x05\x4a\x6f\x5d\x46\xa9\xc7" "\x42\x9a\x96\x1f\x3d\x9d\x22\x3a\x69\x03\x4b\x3f\x15\x20\xe2\xac\xf8\x55" "\x89\x4e\x69\x6e\xef\xbe\xef\xa8\xaa\xdf\xae\x7c\xd4\x63\xd8\x44\xee\xc4" "\x45\x46\xeb\xd0\x88\xcd\x52\x46\x75\xed\xf2\x58\x40\x66\xe4\xae\xd0\xfd" "\xa3\x8a\x01\x08\xcf\xf9\x67\x96\x67\xd5\x40\x9c\x8f\x28\x76\x1a\xa0\x88" "\x2b\x29\x99\x26\xd7\x38\x12\x44\x7d\x1d\x2a\x9d\x20\x39\xa7\x65\x7f\x64" "\x12\x1b\xb1\x5b\xbe\xc0\x96\x14\xc2\x07\xce\x08\xf2\x10\x39\x67\x87\x70" "\x7e\x7a\x1c\x39\x6a\x74\x05\x18\xfe\x8d\x8b\xa7\xbf\x43\xa6\xeb\x1c\x72" "\xbc\xf5\xb5\xfa\x66\xd6\xec\x88\x43\x31\x4e\x17\x52\x8c\x67\x53\xed\xd0" "\x23\xad\xe7\xc8\x15\xdf\x4c\xf9\x6b\xb2\x4f\xf0\xc3\x87\x8a\x74\x30\x22" "\x21\x04\xa0\xcf\xac\x39\xba\x14\x92\xb3\x9a\xc6\xee\x1e\xab\x17\x8f\x40" "\x5a\x47\x63\x0f\x2b\xe0\x67\x47\xe0\xe2\x60\x1b\xfa\x9f\x83\xac\x01\x98" "\x11\xc6\x59\x1d\x45\xa7\x98\x8d\x04\x85\xae\xed\x5d\x57\x8b\xa0\x25\xbd" "\xc2\xe7\xf1\x7f\xcd\xcd\xa1\xfe\x0b\x01\xe6\x58\x79\x36\x87\xa1\x16\x2a" "\x16\x1c\xdb\x2a\x52\x15\x02\x6e\x41\x98\x4c\xe2\xcc\x92\x13\x64\xde\xb2" "\xa7\x76\xaf\x0e\x8f\x3d\xc4\xea\xe0\x02\xb3\x31\xb7\x59\xc9\xf6\x37\xb2" "\xd4\x80\x8e\xab\x4f\xd8\x5c\x71\xa7\x20\x9d\xe9\x8e\xcf\xf0\x70\x3d\xce" "\x04\x62\x7f\x7e\x1a\xf0\x03\xe8\x87\xaa\x7c\x4e\x2b\xc4\xa2\xe9\xfe\xb0" "\xad\x90\x5a\x71\xd2\x6a\x26\x0f\xda\x09\x9c\x6b\x29\x4d\xd2\x3f\xbc\x27" "\xe5\xe9\xd7\xd1\x26\x52\x82\x84\x7f\x51\xa0\x80\x68\x74\xb9\x7b\x5d\x9d" "\xc9\x1a\x84\xeb\x98\xf6\x27\x4f\xcd\x4a\x55\x5e\x22\xab\xa9\x37\xc4\x33" "\xab\x01\xeb\xab\x33\x50\x2d\xba\x79\x40\xb2\xa5\x69\x5d\xde\xd5\xfc\xec" "\x44\x13\x10\x79\x5f\x16\x39\x48\xe3\x7a\x3f\x63\x7d\x31\x9c\x97\x63\xe3" "\xed\x0a\xc1\x0d\x52\xcc\x0e\x7c\xff\xf4\xc3\x88\xfb\x93\x41\x19\xb8\x95" "\xc3\x9e\xad\xb5\x38\xa2\x16\x38\xce\xee\x82\x45\x8e\x29\xff\x28\x80\x07" "\xa7\x05\xef\x44\x2f\x83\xc1\xd3\x6e\xe4\xdc\x21\x3f\x0e\x67\x18\x9a\x7a" "\x44\x9f\xcd\x07\x71\x8f\x3b\x80\x03\x8b\x63\xc0\x2b\x19\x8b\x17\xc1\xa6" "\x3e\x2d\x04\xa3\xc5\xa5\x98\x70\x47\xe4\x67\x25\xc0\xa8\x5f\x24\xea\xac" "\x70\x03\xb9\xe2\xb8\xf2\x19\x01\x6f\xcc\x0b\x08\xe3\xc8\x10\x29\x46\xfb" "\x9e\x89\xd1\xeb\xfd\xf3\x63\xe8\x08\x0f\xe5\x5a\x21\xe5\xf5\x8c\xf2\xaf" "\xd5\x80\x76\xe8\x9f\x60\x2a\xf3\x2b\x86\x5e\x11\x43\x7b\x88\xc9\xaf\x5a" "\xe6\xcf\x21\xc3\xfd\xea\xdd\xee\x05\x88\x30\xae\x68\x73\x3e\x72\x58\xff" "\xb2\xee\xf7\xe4\x3d\xb9\x0a\x03\xa3\xe1\x2e\x6e\x52\xb3\x1b\x83\x99\x01" "\xc6\x9e\xcd\xc9\x6b\x34\x47\x60\x2e\x1b\x40\x89\xb7\x56\xe7\x12\x4f\x50" "\x0a\x7b\xd3\x30\xcb\x60\xd7\x70\xc1\xdf\xca\x28\x18\xe2\x1b\xff\x94\xf6" "\x18\x80\xd7\x32\x1e\xd0\x2a\xae\x16\x09\xfb\xc6\xa0\xdf\xac\x8b\x19\x98" "\xf5\xb4\xdb\x56\xe0\x99\x27\x08\xb3\x05\xff\x68\x04\xf8\xec\x55\x2e\x67" "\xa2\x4f\x33\xb9\x01\x03\xd2\xa0\x7c\x1e\xf6\xb4\x77\xe3\xee\x7e\x3a\x6c" "\x90\xca\x7a\x55\xdf\x02\xaa\xe1\xf4\x85\x97\x9f\x7c\xee\xb2\x95\xba\x18" "\x52\xcb\xd9\x40\xbc\xd8\x53\x58\xdc\xbe\x9d\x4d\x52\x95\x61\x40\x84\xbe" "\xe8\x17\x1b\x69\x0c\xbd\x4d\x21\x93\xfa\x3b\xf5\x54\x5a\x9c\x5c\x47\xd2" "\x8c\x9f\x93\x42\x2c\x59\xaf\x30\xd2\xe2\x6c\x1f\xfd\x1f\xb5\xe1\x13\xf2" "\xee\xae\x2e\x81\x5f\x53\xbb\x17\x31\xff\xc4\x34\xb4\x8a\xd3\xa7\x71\x74" "\x03\x37\xa5\xdc\xb6\x09\xd3\x7c\x79\xa3\x75\x9f\xef\x2c\x0c\x83\x97\xbc" "\x63\x01\x0f\x31\x3d\x6b\xb2\xeb\x12\x0e\x00\x97\x4f\x40\xa1\x84\xf5\x21" "\x6c\x59\xf6\xb5\x63\xd6\x03\x9a\x00\xae\xa0\x2c\x1f\x70\xd7\x9c\x99\xcd" "\x70\x47\xe8\xeb\x54\xcf\xb1\x5b\x41\x68\x8f\x2a\x45\xf2\x95\x5a\xf3\x0c" "\x40\xfa\xfe\xbe\xef\xde\x3c\xb7\xef\x91\xa5\xba\x0b\x45\x8a\x2e\xde\x6e" "\x98\x9c\x70\x07\x36\x1a\xab\x37\xc7\x5a\xc4\x0d\xcd\xe8\xff\x66\x65\x76" "\x4f\x14\x3a\xea\x7e\x86\x61\x83\xba\xa1\x67\xf9\x92\x9f\xa9\xa7\x8e\x6a" "\xd7\xf0\x68\xbf\xa0\x75\x1c\xad\x9f\x1b\x1e\x54\xd8\x00\x28\x1f\x5e\xc6" "\x7c\x1c\x81\x7c\x5e\x58\xa4\x0c\x5e\xc9\xf2\xb2\xb6\xac\xf8\x5f\x6a\xbf" "\xbf\x54\x76\x7c\x59\xd0\x25\x2a\x50\xa5\xdf\x38\x46\xdc\x9e\x4f\xb4\x14" "\xd0\xbc\xf0\x10\x1b\x1a\xd5\x47\x76\x63\x5c\x52\x22\x61\xba\x01\xd9\x4a" "\x8b\xe1\x68\x1f\x16\x2f\x9e\xde\x83\xfc\x8f\xa1\xf2\x49\x4e\x3d\x40\x94" "\x90\xb1\x78\x62\x57\xce\x0f\x75\x1b\x2c\xf6\x90\xe7\x7f\x09\x65\xd4\xfc" "\x72\x81\x1a\x70\x19\xd2\xa6\xaa\x8a\x4b\xc7\x35\xc5\x59\x2a\xbe\x2d\x07" "\xae\x22\x6f\xed\xa3\xf1\x0a\x5a\xe6\xfc\x31\xea\x95\x88\xd3\x62\x40\x0b" "\x4a\x88\xad\xd1\x25\x28\x22\x44\x32\xd2\xa4\xfa\xab\x1d\xa4\xde\x71\x3b" "\x07\x59\x90\xd2\xe5\xec\x52\x7d\x79\x1a\x03\xac\x89\x44\x37\x1d\x47\x12" "\x13\x30\xa1\x70\xe5\x59\x75\x8f\xf0\x8f\xb1\xc2\x54\xdf\x5a\x23\x13\x9d" "\x42\x31\x3e\xb8\x2b\x4f\x11\x15\x78\x10\x7f\x2c\x15\xff\x2e\xff\xd4\x4e" "\x4c\x0c\x0d\xaf\xc6\x09\xc6\xd2\xa6\x4d\xe1\x36\x8d\x44\x44\xdd\x30\x88" "\x22\x41\x56\xa0\xab\x55\x61\x57\xff\xa1\xc3\xba\x09\x99\x8e\x43\xd0\x9e" "\xc7\x8f\x6a\x7b\x9a\x99\xfc\xc2\x02\xea\x4c\x6a\xfc\x4e\xc8\xb4\x63\xa7" "\x91\x6b\x59\xdd\x79\x98\x6e\x09\xe8\x5b\x1f\xf8\x1a\xd1\x42\xcf\xe5\x66" "\xd8\x69\xca\x20\xfe\xaf\xea\xb1\x0b\xbf\x8f\xf7\xcb\xb8\x50\x83\x75\x64" "\x93\xb1\x1f\xee\x6f\xb7\x05\x11\x26\x0c\x3c\xa0\xf5\xea\xb4\x19\x0c\x69" "\xb0\x8c\x85\x92\x9c\xbb\x39\x34\xfd\xf1\x47\x0a\x5a\x75\xd2\xfa\x93\xd9" "\xd2\x04\xf8\xa2\xeb\x64\xe6\xb6\x0f\x4b\x6a\x9d\x95\x85\x55\xce\x9f\x2f" "\xd7\x68\x9d\x44\xb7\x77\xca\x5c\xc7\xfc\xca\x49\x93\x99\xe0\x1a\x39\x0a" "\x68\xa6\x9c\xee\x9f\x11\x24\x91\xb5\x95\x28\xc4\xb8\x58\x00\x40\xae\x09" "\xc0\xd7\xe9\xa3\xa7\x07\x8d\x20\xe0\xbc\xf0\xa0\x15\x84\xb6\x6f\xc8\x8f" "\x3b\x94\x64\x26\x46\x4a\x1f\x77\xbd\x83\x84\xb7\x91\x8d\x12\xc7\x87\xb0" "\x9c\xbf\x5d\x9a\x53\xcb\xc7\x3a\x46\xef\xd9\xc1\xec\x8f\x4b\x1c\x87\x64" "\x76\xf6\x42\xe6\x12\x0d\x8f\xe2\x79\x2a\x71\x03\x82\xa0\x70\x82\x60\xb9" "\x76\xce\xb5\x74\x31\x03\xed\xe0\xda\xe4\xbd\xea\x85\x82\x63\xbb\xdb\xe4" "\x08\xa7\xca\xc6\xb0\x83\x4f\xb5\x35\xd3\x56\x3e\x09\x44\x37\x9d\x75\x81" "\x49\xe3\x73\x34\x50\x57\x38\xfb\x95\x02\xdc\xf4\xc2\x30\x14\x00\x4e\xf2" "\x1a\xd4\x38\xc8\x3d\x0b\xa7\xb9\x09\xd4\x5f\x9c\xb8\xbd\xb1\xe4\x39\x1d" "\x83\x14\x02\xd3\xd4\xe8\x08\xbf\x8a\x04\x64\xdc\x67\x60\xf2\x18\x8f\x32" "\xad\x21\x1e\xc8\xfa\x70\xda\x09\xf5\x75\xdf\xe9\x2e\x27\x94\x3b\xbf\x87" "\x9d\x21\x9b\x5b\x0c\xe4\xfc\x3d\x9f\x05\x77\x8c\x83\x8c\xb4\x30\xd4\x33" "\xa0\x6e\xec\x6a\x2d\xec\x8b\x2e\x5a\xe2\xdb\x8b\x5b\x1f\xfb\xc2\x35\x72" "\x6f\xb0\x86\x72\x20\x17\xf6\xc3\x65\x0f\xd5\x6d\x12\xe6\xba\x16\x01\xb3" "\x26\x43\x3b\x36\x32\x8f\xf7\x6d\x24\xc3\xbb\x32\xbb\x8a\x9e\x0a\x15\x3a" "\xea\x5e\x34\xb9\x4c\x7c\x27\xe6\xed\xc2\xe0\x6a\xaa\xf9\x81\xa9\x68\x1c" "\x5a\x84\x51\x37\x3a\x46\xf5\xca\x68\x48\x22\xb9\x06\x7b\x82\x7d\xa3\xcc" "\x9f\x67\x6d\xbf\x90\xf4\xc7\x38\x93\x6e\xb5\xfd\x18\x15\x69\x0a\xef\x6a" "\x95\x96\x26\xb7\xeb\x53\x2b\x3a\x4a\xd0\xa0\x1b\xeb\x4b\x42\x07\x00\x65" "\xef\x2d\x0e\x01\x42\x09\x1c\xd8\x66\xb9\xa0\xa6\x32\x1f\x26\xf2\x8d\x14" "\x74\x6a\x14\x5d\xcb\xe7\x5f\xc7\x8b\xc0\x43\x1b\xf0\x07\x72\x32\x54\x88" "\xe3\xfd\x29\x3b\x7a\x6f\xc1", 3661); *(uint64_t*)0x20000248 = 0xe4d; *(uint64_t*)0x20000398 = 1; *(uint64_t*)0x200003a0 = 0; *(uint64_t*)0x200003a8 = 0; *(uint32_t*)0x200003b0 = 0; inject_fault(5); syscall(__NR_sendmsg, r[0], 0x20000380ul, 0ul); } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); inject_fault(5); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); setup_fault(); loop(); return 0; }
the_stack_data/43889157.c
// Copyright (C) 2015-2020 Virgil Security, Inc. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // (1) Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // // (3) Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Lead Maintainer: Virgil Security Inc. <[email protected]> #if FLDT_CLIENT #include <virgil/iot/protocols/snap/fldt/fldt-private.h> #include <virgil/iot/protocols/snap/fldt/fldt-client.h> #include <virgil/iot/protocols/snap/generated/snap_cvt.h> #include <virgil/iot/status_code/status_code.h> #include <virgil/iot/logger/logger.h> #include <virgil/iot/macros/macros.h> #include <virgil/iot/update/update.h> #include <stdlib-config.h> #include <global-hal.h> #include <virgil/iot/trust_list/trust_list.h> static vs_snap_service_t _fldt_client = {0}; #define VS_FLDT_RETRY_MAX (5) #define VS_FLDT_WAIT_MAX (10) // Seconds #define VS_FLDT_REQUEST_SZ_MAX (150) // TODO : This setting might be moved to some config #define CLIENT_FILE_TYPE_ARRAY_SIZE (10) typedef struct { bool in_progress; int retry_used; int tick_cnt; uint32_t expected_offset; vs_mac_addr_t gateway_mac; uint32_t command; uint8_t data[VS_FLDT_REQUEST_SZ_MAX]; uint16_t data_sz; } vs_fldt_client_retry_ctx_t; typedef struct { vs_update_file_type_t type; vs_file_version_t prev_file_version; vs_file_version_t cur_file_version; vs_update_interface_t *update_interface; void *file_header; uint32_t file_size; vs_mac_addr_t gateway_mac; vs_fldt_client_retry_ctx_t retry_ctx; } vs_fldt_client_file_type_mapping_t; static uint32_t _file_type_mapping_array_size = 0; static vs_fldt_client_file_type_mapping_t _client_file_type_mapping[CLIENT_FILE_TYPE_ARRAY_SIZE]; static vs_fldt_got_file _got_file_callback = NULL; static vs_status_e _ask_file_type_info(const char *file_type_descr, vs_fldt_gnfh_header_request_t *gnfh_request, vs_fldt_client_file_type_mapping_t *file_type_info); /******************************************************************/ static void _update_process_reset(vs_fldt_client_file_type_mapping_t *object_info) { CHECK_NOT_ZERO(object_info); vs_fldt_client_retry_ctx_t *retry_ctx = &object_info->retry_ctx; if (object_info->retry_ctx.in_progress) { switch (object_info->retry_ctx.command) { case VS_FLDT_GNFH: case VS_FLDT_GNFD: case VS_FLDT_GNFF: object_info->update_interface->delete_object(object_info->update_interface->storage_context, &object_info->type); object_info->cur_file_version = object_info->prev_file_version; break; default: break; } } VS_FLDT_PRINT_DEBUG(object_info->type.type, retry_ctx->command, "_update_process_reset"); VS_IOT_MEMSET(retry_ctx, 0, sizeof(*retry_ctx)); terminate:; } /******************************************************************/ static void _delete_mapping_element(vs_fldt_client_file_type_mapping_t *file_element_to_delete) { vs_fldt_client_file_type_mapping_t *file_type_info = _client_file_type_mapping; uint32_t id; bool found = false; if (0 == _file_type_mapping_array_size) { return; } for (id = 0; id < _file_type_mapping_array_size; ++id, ++file_type_info) { if (!found) { if (file_element_to_delete == file_type_info) { if (file_element_to_delete->update_interface && file_element_to_delete->update_interface->free_item) { file_element_to_delete->update_interface->free_item( file_element_to_delete->update_interface->storage_context, &file_element_to_delete->type); } if (file_element_to_delete->file_header) { VS_IOT_FREE(file_element_to_delete->file_header); file_element_to_delete->file_header = NULL; } found = true; } } else { _client_file_type_mapping[id - 1] = *file_type_info; VS_IOT_MEMSET(file_type_info, 0, sizeof(vs_fldt_client_file_type_mapping_t)); } } if (found) { _file_type_mapping_array_size--; } } /******************************************************************/ static vs_status_e _update_process_set(vs_fldt_client_file_type_mapping_t *object_info, uint32_t command, uint32_t expected_offset, const uint8_t *request_data, uint32_t request_data_sz) { CHECK_NOT_ZERO_RET(object_info, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_RET( request_data_sz <= VS_FLDT_REQUEST_SZ_MAX, VS_CODE_ERR_TOO_SMALL_BUFFER, "Small buffer for Retry command"); vs_fldt_client_retry_ctx_t *retry_ctx = &object_info->retry_ctx; if (retry_ctx->command != command) { VS_FLDT_PRINT_DEBUG(object_info->type.type, command, "_update_process_set"); } retry_ctx->in_progress = true; retry_ctx->tick_cnt = 0; retry_ctx->retry_used = 0; retry_ctx->command = command; retry_ctx->gateway_mac = object_info->gateway_mac; retry_ctx->expected_offset = expected_offset; VS_IOT_MEMCPY(retry_ctx->data, request_data, request_data_sz); retry_ctx->data_sz = request_data_sz; return VS_CODE_OK; } /******************************************************************/ static vs_status_e _update_process_retry(vs_fldt_client_file_type_mapping_t *object_info) { CHECK_NOT_ZERO_RET(object_info, VS_CODE_ERR_INCORRECT_ARGUMENT); vs_fldt_client_retry_ctx_t *retry_ctx = &object_info->retry_ctx; retry_ctx->retry_used++; if (retry_ctx->retry_used > VS_FLDT_RETRY_MAX) { VS_FLDT_PRINT_DEBUG( object_info->type.type, retry_ctx->command, "Update process has been stopped, because of retry limit"); _update_process_reset(object_info); return VS_CODE_OK; } VS_FLDT_PRINT_DEBUG(object_info->type.type, retry_ctx->command, "_update_process_retry"); CHECK_RET(!vs_snap_send_request(vs_snap_netif_routing(), &retry_ctx->gateway_mac, VS_FLDT_SERVICE_ID, retry_ctx->command, retry_ctx->data, retry_ctx->data_sz), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Unable to re-send FLDT request"); return VS_CODE_OK; } /******************************************************************/ static vs_fldt_client_file_type_mapping_t * _get_mapping_elem(const vs_update_file_type_t *file_type) { vs_fldt_client_file_type_mapping_t *file_type_info = _client_file_type_mapping; uint32_t id; for (id = 0; id < _file_type_mapping_array_size; ++id, ++file_type_info) { if (vs_update_equal_file_type(&file_type_info->type, file_type)) { return file_type_info; } } VS_LOG_WARNING("[FLDT] Unable to find file type specified"); return NULL; } /*************************************************************************/ static bool _file_is_newer(const vs_file_version_t *available_file, const vs_file_version_t *new_file) { return (VS_CODE_OK == vs_update_compare_version(new_file, available_file)); } /******************************************************************/ static bool _check_download_need(const char *opcode, vs_file_version_t *current_file_ver, const vs_file_version_t *new_file_ver) { bool download; VS_IOT_ASSERT(opcode); VS_IOT_ASSERT(current_file_ver); VS_IOT_ASSERT(new_file_ver); VS_LOG_DEBUG("[FLDT:%s] Current file version : %s", opcode, VS_UPDATE_FILE_VERSION_STR_STATIC(current_file_ver)); VS_LOG_DEBUG("[FLDT:%s] New file version : %s", opcode, VS_UPDATE_FILE_VERSION_STR_STATIC(new_file_ver)); download = _file_is_newer(current_file_ver, new_file_ver); if (download) { VS_LOG_DEBUG("[FLDT:%s] Need to download new version", opcode); } else { VS_LOG_DEBUG("[FLDT:%s] No need to download new version", opcode); } return download; } /******************************************************************/ static int vs_fldt_INFV_request_processor(const uint8_t *request, const uint16_t request_sz, uint8_t *response, const uint16_t response_buf_sz, uint16_t *response_sz) { vs_fldt_infv_new_file_request_t *new_file = (vs_fldt_infv_new_file_request_t *)request; const vs_file_version_t *new_file_ver = NULL; const vs_update_file_type_t *file_type = NULL; vs_fldt_gnfh_header_request_t header_request; vs_fldt_client_file_type_mapping_t *file_type_info = NULL; (void)response; (void)response_buf_sz; (void)response_sz; CHECK_NOT_ZERO_RET(request, VS_CODE_ERR_NULLPTR_ARGUMENT); CHECK_NOT_ZERO_RET(request_sz, VS_CODE_ERR_ZERO_ARGUMENT); CHECK_RET(request_sz == sizeof(*new_file), VS_CODE_ERR_INCORRECT_ARGUMENT, "Unsupported request structure, vs_fldt_infv_new_file_request_t has been waited"); VS_LOG_DEBUG("[FLDT:INFV] Received from " FLDT_MAC_PRINT_TEMPLATE, FLDT_MAC_PRINT_ARG(new_file->gateway_mac)); // Normalize byte order vs_fldt_file_info_t_decode(new_file); new_file_ver = &new_file->type.info.version; file_type = &new_file->type; CHECK_RET(file_type_info = _get_mapping_elem(file_type), VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "Unregistered file type"); VS_LOG_DEBUG("[FLDT:INFV] Gateway " FLDT_MAC_PRINT_TEMPLATE ", file %s : %s", FLDT_MAC_PRINT_ARG(new_file->gateway_mac), VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), VS_UPDATE_FILE_VERSION_STR_STATIC(new_file_ver)); file_type_info->gateway_mac = new_file->gateway_mac; if (_check_download_need("INFV", &file_type_info->cur_file_version, new_file_ver)) { header_request.type = *file_type; header_request.type.info.version = new_file->type.info.version; VS_LOG_DEBUG("[FLDT] Ask header of %s : %s", VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), VS_UPDATE_FILE_VERSION_STR_STATIC(new_file_ver)); // Normalize byte order vs_fldt_gnfh_header_request_t_encode(&header_request); CHECK_RET(VS_CODE_OK == _update_process_set(file_type_info, VS_FLDT_GNFH, 0, (const uint8_t *)&header_request, sizeof(header_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Can't set up retry process"); CHECK_RET(!vs_snap_send_request(vs_snap_netif_routing(), &file_type_info->gateway_mac, VS_FLDT_SERVICE_ID, VS_FLDT_GNFH, (const uint8_t *)&header_request, sizeof(header_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Unable to send FLDT \"GNFH\" server request"); } return VS_CODE_OK; } /******************************************************************/ static int vs_fldt_GNFH_response_processor(bool is_ack, const uint8_t *response, const uint16_t response_sz) { vs_fldt_gnfh_header_response_t *file_header = (vs_fldt_gnfh_header_response_t *)response; vs_file_version_t *file_ver = NULL; vs_update_file_type_t *file_type = NULL; vs_fldt_gnfd_data_request_t data_request; vs_fldt_client_file_type_mapping_t *file_type_info = NULL; vs_status_e ret_code; CHECK_RET(is_ack, VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "wrong GNFH response"); CHECK_NOT_ZERO_RET(response, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_NOT_ZERO_RET(response_sz, VS_CODE_ERR_INCORRECT_ARGUMENT); // Normalize byte order vs_fldt_gnfh_header_response_t_decode(file_header); CHECK_NOT_ZERO_RET(file_header->file_size, VS_CODE_ERR_INCORRECT_ARGUMENT); file_ver = &file_header->fldt_info.type.info.version; file_type = &file_header->fldt_info.type; CHECK_RET(file_type_info = _get_mapping_elem(file_type), VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "Unregistered file type"); if (!_check_download_need("GNFH", &file_type_info->cur_file_version, file_ver)) { file_type_info->retry_ctx.in_progress = false; VS_LOG_WARNING("[FLDT:GNFH] File [type %d] header contains an old version", file_type->type); return VS_CODE_OLD_VERSION; } file_type_info->prev_file_version = file_type_info->cur_file_version; file_type_info->cur_file_version = file_type->info.version; VS_LOG_DEBUG("[FLDT:GNFH] Response file size %d bytes, file %s : %s", file_header->file_size, VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), VS_UPDATE_FILE_VERSION_STR_STATIC(&file_type->info.version)); file_type_info->gateway_mac = file_header->fldt_info.gateway_mac; CHECK_RET(response_sz >= sizeof(*file_header), VS_CODE_ERR_INCORRECT_ARGUMENT, "Response must be of vs_fldt_gnfh_header_response_t type"); STATUS_CHECK_RET(file_type_info->update_interface->set_header(file_type_info->update_interface->storage_context, file_type, file_header->header_data, file_header->header_size, &file_type_info->file_size), "Unable to set header for %s", VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type)); VS_IOT_FREE(file_type_info->file_header); file_type_info->file_header = VS_IOT_MALLOC(file_header->header_size); CHECK_RET(file_type_info->file_header, VS_CODE_ERR_NO_MEMORY, "No memory to allocate %lu bytes for file header", file_header->header_size); VS_IOT_MEMCPY(file_type_info->file_header, file_header->header_data, file_header->header_size); VS_IOT_MEMSET(&data_request, 0, sizeof(data_request)); data_request.offset = 0; data_request.type = *file_type; data_request.type.info.version = file_header->fldt_info.type.info.version; VS_LOG_DEBUG("[FLDT] Ask file data offset %d of %s:%s", data_request.offset, VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), VS_UPDATE_FILE_VERSION_STR_STATIC(&file_type->info.version)); // Normalize byte order vs_fldt_gnfd_data_request_t_encode(&data_request); CHECK_RET(VS_CODE_OK == _update_process_set(file_type_info, VS_FLDT_GNFD, data_request.offset, (const uint8_t *)&data_request, sizeof(data_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Can't set up retry process"); CHECK_RET(!vs_snap_send_request(vs_snap_netif_routing(), &file_type_info->gateway_mac, VS_FLDT_SERVICE_ID, VS_FLDT_GNFD, (const uint8_t *)&data_request, sizeof(data_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Unable to send FLDT \"GNFD\" server request"); return VS_CODE_OK; } /******************************************************************/ static int vs_fldt_GNFD_response_processor(bool is_ack, const uint8_t *response, const uint16_t response_sz) { vs_fldt_gnfd_data_response_t *file_data = (vs_fldt_gnfd_data_response_t *)response; vs_file_version_t *file_ver = NULL; vs_update_file_type_t *file_type = NULL; vs_fldt_client_file_type_mapping_t *file_type_info = NULL; vs_fldt_gnfd_data_request_t data_request; vs_fldt_gnff_footer_request_t footer_request; vs_status_e ret_code; CHECK_RET(is_ack, VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "wrong GNFD response"); // Normalize byte order vs_fldt_gnfd_data_response_t_decode(file_data); file_ver = &file_data->type.info.version; file_type = &file_data->type; CHECK_RET(file_type_info = _get_mapping_elem(file_type), VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "Unregistered file type"); CHECK_NOT_ZERO_RET(response, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_NOT_ZERO_RET(response_sz, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_NOT_ZERO_RET(file_data->data_size, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_RET(response_sz >= sizeof(*file_data) && (response_sz == sizeof(*file_data) + file_data->data_size), VS_CODE_ERR_INCORRECT_ARGUMENT, "Response must be of vs_fldt_gnfd_data_response_t type"); if (0 != VS_IOT_MEMCMP(&file_type_info->cur_file_version, file_ver, sizeof(file_type_info->cur_file_version))) { VS_LOG_WARNING("[FLDT:GNFD] File [type %d] data contains an old version", file_type->type); vs_fldt_gnfh_header_request_t header_request; header_request.type = file_type_info->type; _ask_file_type_info(VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), &header_request, file_type_info); return VS_CODE_OLD_VERSION; } STATUS_CHECK_RET(file_type_info->update_interface->set_data(file_type_info->update_interface->storage_context, file_type, file_type_info->file_header, file_data->data, file_data->data_size, file_data->offset), "Unable to set header for %s", VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type)); if (file_data->next_offset < file_type_info->file_size) { // Load next data data_request.offset = file_data->next_offset; data_request.type = *file_type; data_request.type.info.version = file_data->type.info.version; // Normalize byte order vs_fldt_gnfd_data_request_t_encode(&data_request); CHECK_RET(VS_CODE_OK == _update_process_set(file_type_info, VS_FLDT_GNFD, data_request.offset, (const uint8_t *)&data_request, sizeof(data_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Can't set up retry process"); CHECK_RET(!vs_snap_send_request(vs_snap_netif_routing(), &file_type_info->gateway_mac, VS_FLDT_SERVICE_ID, VS_FLDT_GNFD, (const uint8_t *)&data_request, sizeof(data_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Unable to send FLDT \"GNFD\" server request"); } else { // Load footer footer_request.type = *file_type; footer_request.type.info.version = file_data->type.info.version; // Normalize byte order vs_fldt_gnff_footer_request_t_encode(&footer_request); CHECK_RET(VS_CODE_OK == _update_process_set(file_type_info, VS_FLDT_GNFF, 0, (const uint8_t *)&footer_request, sizeof(footer_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Can't set up retry process"); CHECK_RET(!vs_snap_send_request(vs_snap_netif_routing(), &file_type_info->gateway_mac, VS_FLDT_SERVICE_ID, VS_FLDT_GNFF, (const uint8_t *)&footer_request, sizeof(footer_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Unable to send [FLDT:GNFF] request"); } return VS_CODE_OK; } /******************************************************************/ static vs_status_e _ask_file_type_info(const char *file_type_descr, vs_fldt_gnfh_header_request_t *gnfh_request, vs_fldt_client_file_type_mapping_t *file_type_info) { CHECK_NOT_ZERO_RET(gnfh_request, VS_CODE_ERR_INCORRECT_ARGUMENT); VS_LOG_DEBUG("[FLDT] Ask file type information for file type %s", file_type_descr); vs_fldt_gnfh_header_request_t_encode(gnfh_request); file_type_info->gateway_mac = *vs_snap_broadcast_mac(); _update_process_reset(file_type_info); CHECK_RET(VS_CODE_OK == _update_process_set( file_type_info, VS_FLDT_GNFH, 0, (const uint8_t *)gnfh_request, sizeof(*gnfh_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Can't set up retry process"); CHECK_RET(!vs_snap_send_request(vs_snap_netif_routing(), &file_type_info->gateway_mac, VS_FLDT_SERVICE_ID, VS_FLDT_GNFH, (const uint8_t *)gnfh_request, sizeof(*gnfh_request)), VS_CODE_ERR_INCORRECT_SEND_REQUEST, "Unable to send [FLDT:GNFH] request"); return VS_CODE_OK; } /******************************************************************/ static int vs_fldt_GNFF_response_processor(bool is_ack, const uint8_t *response, const uint16_t response_sz) { vs_fldt_gnff_footer_response_t *file_footer = (vs_fldt_gnff_footer_response_t *)response; vs_file_version_t *file_ver = NULL; vs_update_file_type_t *file_type = NULL; vs_fldt_client_file_type_mapping_t *file_type_info = NULL; bool successfully_updated; vs_status_e ret_code; CHECK_RET(is_ack, VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "wrong GNFF response"); // Normalize byte order vs_fldt_gnff_footer_response_t_decode(file_footer); file_ver = &file_footer->type.info.version; file_type = &file_footer->type; CHECK_RET(file_type_info = _get_mapping_elem(file_type), VS_CODE_ERR_UNREGISTERED_MAPPING_TYPE, "Unregistered file type"); VS_LOG_DEBUG("[FLDT:GNFF] Response for %s : %s. Footer size %d bytes", VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), VS_UPDATE_FILE_VERSION_STR_STATIC(file_ver), file_footer->footer_size); CHECK_NOT_ZERO_RET(response, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_NOT_ZERO_RET(response_sz, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_RET(response_sz >= sizeof(*file_footer) && (response_sz == sizeof(*file_footer) + file_footer->footer_size), VS_CODE_ERR_INCORRECT_ARGUMENT, "Response must be of vs_fldt_gnff_footer_response_t type"); if (0 != VS_IOT_MEMCMP(&file_type_info->cur_file_version, file_ver, sizeof(file_type_info->cur_file_version))) { VS_LOG_WARNING("[FLDT:GNFF] File %s footer contains an old version", VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type)); vs_fldt_gnfh_header_request_t header_request; header_request.type = file_type_info->type; _ask_file_type_info(VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type), &header_request, file_type_info); return VS_CODE_OLD_VERSION; } ret_code = file_type_info->update_interface->set_footer(file_type_info->update_interface->storage_context, file_type, file_type_info->file_header, file_footer->footer_data, file_footer->footer_size); successfully_updated = (ret_code == VS_CODE_OK); // Stop retries file_type_info->retry_ctx.in_progress = !successfully_updated; _got_file_callback(file_type, &file_type_info->prev_file_version, file_ver, file_type_info->update_interface, &file_type_info->gateway_mac, successfully_updated); if (!successfully_updated) { VS_LOG_ERROR("Error while processing footer for %s", VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type)); file_type_info->cur_file_version = file_type_info->prev_file_version; } return VS_CODE_OK; } /******************************************************************/ static vs_status_e _new_mapping_element(vs_fldt_client_file_type_mapping_t **file_element_to_add) { VS_IOT_ASSERT(_file_type_mapping_array_size < (CLIENT_FILE_TYPE_ARRAY_SIZE - 1)); CHECK_RET(_file_type_mapping_array_size < (CLIENT_FILE_TYPE_ARRAY_SIZE - 1), VS_CODE_ERR_NO_MEMORY, "[FLDT] Can't add new file type. Array is full"); *file_element_to_add = &_client_file_type_mapping[_file_type_mapping_array_size++]; VS_LOG_DEBUG("[FLDT] File type was not initialized, add new entry. Array size = %d", _file_type_mapping_array_size); VS_IOT_MEMSET(*file_element_to_add, 0, sizeof(vs_fldt_client_file_type_mapping_t)); return VS_CODE_OK; } /******************************************************************/ vs_status_e vs_fldt_client_add_file_type(const vs_update_file_type_t *file_type, vs_update_interface_t *update_interface) { vs_fldt_client_file_type_mapping_t *existing_file_element = NULL; vs_fldt_client_file_type_mapping_t file_element_to_add; vs_fldt_gnfh_header_request_t gnfh_request; char type_str[VS_UPDATE_DEFAULT_DESC_BUF_SZ]; char version_str[VS_UPDATE_DEFAULT_DESC_BUF_SZ]; vs_status_e ret_code; uint32_t header_size; CHECK_NOT_ZERO_RET(file_type, VS_CODE_ERR_INCORRECT_ARGUMENT); CHECK_NOT_ZERO_RET(update_interface, VS_CODE_ERR_INCORRECT_ARGUMENT); VS_IOT_MEMSET(&file_element_to_add, 0, sizeof(file_element_to_add)); file_element_to_add.type = *file_type; file_element_to_add.update_interface = update_interface; VS_LOG_DEBUG("[FLDT] Add file type %s", vs_update_file_type_str(&file_element_to_add.type, type_str, sizeof(type_str))); ret_code = update_interface->get_header_size( update_interface->storage_context, &file_element_to_add.type, &header_size); if (VS_CODE_OK != ret_code || !header_size) { VS_LOG_ERROR("Unable to get header size for file type %s", type_str); return (VS_CODE_OK == ret_code) ? VS_CODE_ERR_VERIFY : ret_code; } file_element_to_add.file_header = VS_IOT_MALLOC(header_size); file_element_to_add.file_size = 0; ret_code = update_interface->get_header(update_interface->storage_context, &file_element_to_add.type, file_element_to_add.file_header, // Version is here header_size, &header_size); if (VS_CODE_OK == ret_code) { VS_LOG_INFO( "[FLDT] Current file version : %s", vs_update_file_version_str(&file_element_to_add.type.info.version, version_str, sizeof(version_str))); file_element_to_add.cur_file_version = file_element_to_add.type.info.version; file_element_to_add.prev_file_version = file_element_to_add.cur_file_version; } else { VS_LOG_WARNING("[FLDT] File type was not found by Update library"); VS_IOT_FREE(file_element_to_add.file_header); file_element_to_add.file_header = NULL; } existing_file_element = _get_mapping_elem(file_type); if (existing_file_element) { _update_process_reset(existing_file_element); _delete_mapping_element(existing_file_element); VS_LOG_DEBUG("[FLDT] File type is initialized present, update it"); } STATUS_CHECK_RET(_new_mapping_element(&existing_file_element), "[FLDT] Error to create new mapping element"); *existing_file_element = file_element_to_add; gnfh_request.type = *file_type; STATUS_CHECK_RET(_ask_file_type_info(type_str, &gnfh_request, existing_file_element), "Unable to ask current file information"); return VS_CODE_OK; } /******************************************************************/ static vs_status_e _fldt_destroy_client(void) { uint32_t id; vs_fldt_client_file_type_mapping_t *file_type_mapping = _client_file_type_mapping; for (id = 0; id < _file_type_mapping_array_size; ++id, ++file_type_mapping) { file_type_mapping->update_interface->free_item(file_type_mapping->update_interface->storage_context, &file_type_mapping->type); VS_IOT_FREE(file_type_mapping->file_header); } _file_type_mapping_array_size = 0; return VS_CODE_OK; } /******************************************************************************/ static int _fldt_client_request_processor(const struct vs_netif_t *netif, const vs_ethernet_header_t *eth_header, vs_snap_element_t element_id, const uint8_t *request, const uint16_t request_sz, uint8_t *response, const uint16_t response_buf_sz, uint16_t *response_sz) { (void)netif; *response_sz = 0; switch (element_id) { case VS_FLDT_INFV: return vs_fldt_INFV_request_processor(request, request_sz, response, response_buf_sz, response_sz); case VS_FLDT_GNFH: case VS_FLDT_GNFD: case VS_FLDT_GNFF: return VS_CODE_COMMAND_NO_RESPONSE; default: VS_LOG_ERROR("Unsupported FLDT command"); VS_IOT_ASSERT(false); return VS_CODE_COMMAND_NO_RESPONSE; } } /******************************************************************************/ static int _fldt_client_response_processor(const struct vs_netif_t *netif, const vs_ethernet_header_t *eth_header, vs_snap_element_t element_id, bool is_ack, const uint8_t *response, const uint16_t response_sz) { (void)netif; switch (element_id) { case VS_FLDT_INFV: if (!is_ack) { VS_LOG_WARNING("GINF Received response packet with is_ack == false"); } return VS_CODE_COMMAND_NO_RESPONSE; case VS_FLDT_GNFH: return vs_fldt_GNFH_response_processor(is_ack, response, response_sz); case VS_FLDT_GNFD: return vs_fldt_GNFD_response_processor(is_ack, response, response_sz); case VS_FLDT_GNFF: return vs_fldt_GNFF_response_processor(is_ack, response, response_sz); default: VS_LOG_ERROR("Unsupported FLDT command"); VS_IOT_ASSERT(false); return VS_CODE_COMMAND_NO_RESPONSE; } } /******************************************************************************/ static int _fldt_client_periodical_processor(void) { vs_fldt_client_file_type_mapping_t *file_type_info = _client_file_type_mapping; vs_fldt_client_retry_ctx_t *_retry_ctx; uint32_t id; for (id = 0; id < _file_type_mapping_array_size; ++id, ++file_type_info) { _retry_ctx = &file_type_info->retry_ctx; if (_retry_ctx->in_progress) { _retry_ctx->tick_cnt++; if (_retry_ctx->tick_cnt > VS_FLDT_WAIT_MAX) { _update_process_retry(file_type_info); } } } return VS_CODE_OK; } /******************************************************************************/ const vs_snap_service_t * vs_snap_fldt_client(vs_fldt_got_file got_file_callback) { VS_IOT_ASSERT(got_file_callback); VS_IOT_ASSERT(CLIENT_FILE_TYPE_ARRAY_SIZE); _fldt_client.user_data = 0; _fldt_client.id = VS_FLDT_SERVICE_ID; _fldt_client.request_process = _fldt_client_request_processor; _fldt_client.response_process = _fldt_client_response_processor; _fldt_client.periodical_process = _fldt_client_periodical_processor; _fldt_client.deinit = _fldt_destroy_client; _got_file_callback = got_file_callback; return &_fldt_client; } /******************************************************************************/ vs_status_e vs_fldt_client_request_all_files(void) { size_t id; vs_fldt_gnfh_header_request_t gnfh_request; vs_fldt_client_file_type_mapping_t *file_type_info = NULL; vs_status_e ret_code; const char *type_desc_buf; VS_LOG_DEBUG("[FLDT] Request info for all registered file types"); if (!_file_type_mapping_array_size) { VS_LOG_WARNING("[FLDT] No registered file types"); return VS_CODE_OK; } for (id = 0; id < _file_type_mapping_array_size; ++id) { file_type_info = &_client_file_type_mapping[id]; VS_LOG_DEBUG("[FLDT] Request file type %s", type_desc_buf = VS_UPDATE_FILE_TYPE_STR_STATIC(&file_type_info->type)); gnfh_request.type = file_type_info->type; STATUS_CHECK_RET(_ask_file_type_info(type_desc_buf, &gnfh_request, file_type_info), "Unable to ask current file information"); } return VS_CODE_OK; } #endif // FLDT_CLIENT
the_stack_data/948366.c
#include <assert.h> #include <stdlib.h> extern int nondet_int(); int main() { int arraylen=nondet_int(); if(arraylen==3) { int** array_init = malloc(sizeof(int *)*arraylen); int a0, a1, a2; array_init[0] = &a0; array_init[1] = &a1; array_init[2] = &a2; void **local_array=(void**)array_init; int *address=(int *)local_array[0]; assert(address==&a0); } }
the_stack_data/4779.c
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ char* mutable_string = "a string"; const char* immutable_string = "a string"; int mutable_int = 0; const int immutable_int = 0; int main() { int mi = mutable_int; int imi = immutable_int; char* c = mutable_string; char a_char = *mutable_string; char b_char = *immutable_string; return 0; }
the_stack_data/193894072.c
/* Copyright (c) 1979 Regents of the University of California */ #ifdef TRACE #include <stdio.h> #undef putchar #endif printf(fmt, args) { _doprnt(fmt, &args, 0); } _strout(count, string, adjust, flail, fillch) register char *string; register count; register int adjust; #ifdef TRACE register struct _iobuf *flail; #else register struct {int i; } *flail; #endif { if (adjust < 0) { if (*string=='-' && fillch=='0') { #ifdef TRACE if (flail) putc(*string++, flail); else #endif putchar(*string++); count--; } adjust= -adjust; while (--adjust>=0) #ifdef TRACE if (flail) putc(fillch, flail); else #endif putchar(fillch); } while (--count>=0) #ifdef TRACE if (flail) putc(*string++, flail); else #endif putchar(*string++); while (--adjust>=0) #ifdef TRACE if (flail) putc(fillch, flail); else #endif putchar(fillch); }
the_stack_data/920924.c
//PARAM: --enable ana.int.congruence --enable ana.int.congruence_no_overflow --disable ana.int.def_exc --disable ana.int.enums // Examples taken from P. Granger "Static analysis of arithmetical congruences" (1989, International Journal of Computer Mathematics) // https://doi.org/10.1080/00207168908803778 int main() { int a = 1; int b = 2; int c = 3; int d = 4; int e = 0; while (d < 9) { b = 2 * a; d = d + 4; e = e - 4 * a; a = b - a; c = e + d; } a = d / 2; b = d % 2; // c is unknown assert (c == 4); // UNKNOWN // d should be 12 in the concrete domain and 4Z in the congr. domain assert (d != 1); assert (d != 2); assert (d != 3); assert (d == 12); // UNKNOWN // a should be 6 in the concrete domain and 2Z in the congr. domain assert (a == 6); // UNKNOWN // e should be -8 in the concrete domain and 4Z in the congr. domain assert (e == -8); // UNKNOWN assert (b == 0); return 0; }
the_stack_data/155047.c
/* vi: set sw=4 ts=4: */ /* strxfrm for uClibc * * Copyright (C) 2002 by Erik Andersen <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Library General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License * for more details. * * You should have received a copy of the GNU Library General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <string.h> size_t strxfrm(char *dst, const char *src, size_t len) { size_t length; register char *ptr1, *ptr2; length = len; ptr1 = (char *) dst; ptr2 = (char *) src; while (length--) { if (*ptr2) *ptr1++ = *ptr2++; else *ptr1++ = '\0'; } /* The first while loop should have done much of the heavy * lifting for us. This second look will finish the job if * that is necessary */ while (*ptr2) ptr2++; length = (ptr2 - src); if (length<len) return(length); return(len); }
the_stack_data/140765226.c
/***************************************************************** * Unipro UGENE - Integrated Bioinformatics Suite * * This source code is distributed under the terms of the * GNU General Public License. See the files COPYING and LICENSE * for details. * * Author: Kursad Albayraktaroglu, Jizhu Li, Ivan Efremov *****************************************************************/ //Protection from automatically generated .pro files. //This variable is set in local, 'spu' makefile #ifdef UGENE_CELL_SPU #include <stdio.h> #include <assert.h> #include <spu_intrinsics.h> #include <spu_mfcio.h> #include <stdlib.h> #include <libmisc.h> #include <libsync.h> #include "hmmer_spu.h" #define SEQ_BUFFER_SIZE 10000 #define HMM_BUFFER_SIZE 150000 #define MAX_HMM 650 #define ARR_SIZE (MAX_HMM*4+12) atomic_ea_t lastConsumed __attribute__ ((aligned (128))); atomic_ea_t nomoreSeqs __attribute__ ((aligned (128))); atomic_ea_t bufferEntries __attribute__ ((aligned (128))); mutex_ea_t bufferMutex __attribute__ ((aligned (128))); cond_ea_t bufferEmptyCond __attribute__ ((aligned (128))); int mySPEID; struct dma_list_elem { union { unsigned int all32; struct { unsigned nbytes: 31; unsigned stall: 1; } bits; }size; unsigned int ea_low; }; struct dma_list_elem list[16] __attribute__((aligned (16))); void get_large_region(void* dst, unsigned int ea_low, unsigned int nbytes){ unsigned int i = 0; unsigned int tagid = 0; unsigned int listsize; if (!nbytes) return; while (nbytes > 0){ unsigned int sz; sz = (nbytes < 16384) ? nbytes : 16384; list[i].size.all32 = sz; list[i].ea_low = ea_low; nbytes -= sz; ea_low += sz; i++; } listsize = i*sizeof(struct dma_list_elem); spu_mfcdma32(dst,(unsigned int) &list[0], listsize, tagid, MFC_GETL_CMD); spu_writech(MFC_WrTagMask, 1 << tagid); (void) spu_mfcstat(2); } int main(addr64 spe_id, addr64 param) { unsigned int tag_id=0; /* DMA tag id */ int j,k; /* General purpose counters */ void* hmmAddr; /* Address for PPE HMM data buffer */ void* jobQueueBase; /* Address for the sequence job queue */ int hmmDMALength; /* Length of PPE HMM data */ volatile spe_initContext ctx __attribute__ ((aligned (128))); volatile unsigned char seqBuffer[2][SEQ_BUFFER_SIZE] __attribute__ ((aligned (128))); volatile unsigned char hmmBuffer[HMM_BUFFER_SIZE] __attribute__ ((aligned (128))) = {0}; volatile spe_jobEntity jobInfos[2] __attribute__ ((aligned (128))); /* These arrays assume a maximum HMM size of 512 states. (2060 = (512*4)+12) */ char mscCurMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char iscCurMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char dscCurMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char mscPrevMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char iscPrevMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; char dscPrevMem[ARR_SIZE] __attribute__ ((aligned (128))) = {0}; int* mscCur = (int*) (mscCurMem + 0xC); int* iscCur = (int*) (iscCurMem + 0xC); int* dscCur = (int*) (dscCurMem + 0xC); int* mscPrev = (int*) (mscPrevMem + 0xC); int* iscPrev = (int*) (iscPrevMem + 0xC); int* dscPrev = (int*) (dscPrevMem + 0xC); spe_hmm hmmD; hmm_offsets offsetsD; spe_hmm* hmm; hmm_offsets* offsets; float viterbiScore; int entityDMAtag = 6; int entityDMAtag_back = 4; int next_idx, buf_idx = 0; unsigned int seqLength[2]; unsigned int seqAddress[2]; unsigned int entityAddress[2]; unsigned int seqDMALength[2]; memset( &hmmD, 0, sizeof(spe_hmm) ); memset( mscCurMem, 0, ARR_SIZE ); memset( iscCurMem, 0, ARR_SIZE ); memset( dscCurMem, 0, ARR_SIZE ); memset( mscPrevMem, 0, ARR_SIZE ); memset( iscPrevMem, 0, ARR_SIZE ); memset( dscPrevMem, 0, ARR_SIZE ); memset( &ctx, 0, sizeof(spe_initContext) ); memset( seqBuffer, 0, 2 * SEQ_BUFFER_SIZE ); memset( hmmBuffer, 0, HMM_BUFFER_SIZE ); memset( jobInfos, 0, 2 * sizeof(spe_jobEntity) ); /* Allocate SPE HMM and offset data structure buffers */ offsets = &offsetsD; hmm = &hmmD; /* The first thing an SPE thread does is DMA its job context information in. This data is a single 128-byte cache line and contains information about the first job, the HMM to be processed and so on. */ mySPEID = (int) spe_id.ui[1]; /* Initiate DMA for context */ spu_mfcdma32((void *)(&ctx),(unsigned int) param.ull,sizeof(spe_initContext),tag_id,MFC_GET_CMD); spu_writech(MFC_WrTagMask, 1<<tag_id); (void) spu_mfcstat(2); // Decode the context and populate local variables. lastConsumed = (atomic_ea_t) ctx.lastConsumed_addr; nomoreSeqs = (atomic_ea_t) ctx.nomoreSeqs_addr; bufferEntries = (atomic_ea_t) ctx.bufferEntries_addr; bufferEmptyCond = (cond_ea_t) ctx.bufferEmptyCond_addr; bufferMutex = (mutex_ea_t) ctx.bufferMutex_addr; jobQueueBase = (void*) ctx.jobqueue_begin_addr; hmmAddr = (void*) ctx.hmm_buf_begin; hmmDMALength = ctx.hmm_buf_length; //Check the length of the HMM if (hmmDMALength > HMM_BUFFER_SIZE){ printf("Error: The size of this HMM(%d) exceeds the maximum buffer size(%d).\n", hmmDMALength, HMM_BUFFER_SIZE); return 0; }else{ // Transfer the HMM from the main memory to SPE LS. get_large_region((void*)hmmBuffer, (unsigned int)hmmAddr, (unsigned int)hmmDMALength); } // Set up the offsets to create SPE LS HMM profile data structure offsets->M = ctx.hmm_M; offsets->escmem_offset = ctx.offsets.escmem_offset; offsets->bscmem_offset = ctx.offsets.bscmem_offset; offsets->tscmem_offset = ctx.offsets.tscmem_offset; offsets->iscmem_offset = ctx.offsets.iscmem_offset; offsets->mscmem_offset = ctx.offsets.mscmem_offset; offsets->xscmem_offset = ctx.offsets.xscmem_offset; offsets->tsc_TMM_mem_offset = ctx.offsets.tsc_TMM_mem_offset; offsets->tsc_TMI_mem_offset = ctx.offsets.tsc_TMI_mem_offset; offsets->tsc_TMD_mem_offset = ctx.offsets.tsc_TMD_mem_offset; offsets->tsc_TIM_mem_offset = ctx.offsets.tsc_TIM_mem_offset; offsets->tsc_TII_mem_offset = ctx.offsets.tsc_TII_mem_offset; offsets->tsc_TDM_mem_offset = ctx.offsets.tsc_TDM_mem_offset; offsets->tsc_TDD_mem_offset = ctx.offsets.tsc_TDD_mem_offset; /* Allocate and populate the SPE HMM data structure*/ allocateSpeHMM (hmm,(unsigned long int)hmmBuffer,offsets); //Initiate the first sequence DMA k = getSequence(); if (k < 0) exit(0); entityAddress[buf_idx] = (unsigned int) jobQueueBase + (128 * k); spu_mfcdma32((void *)(&(jobInfos[buf_idx])),entityAddress[buf_idx], sizeof(spe_jobEntity),entityDMAtag,MFC_GET_CMD); spu_writech(MFC_WrTagMask, 1 << entityDMAtag); (void) spu_mfcstat(2); seqLength[buf_idx] = jobInfos[buf_idx].seqLength; seqAddress[buf_idx] = jobInfos[buf_idx].seqAddr; seqDMALength[buf_idx] = jobInfos[buf_idx].seqDMALength; spu_mfcdma32((void *)(seqBuffer[buf_idx]),seqAddress[buf_idx], seqDMALength[buf_idx], buf_idx, MFC_GET_CMD); // MAIN PROCESSING LOOP // Retrieve sequences into the buffer and process one by one. j=0; while(1){ // Read and increment the currently available sequence index. k = getSequence(); if (k < 0) { if (k == WAIT_FOR_MORE_SEQUENCES){ continue; } else { break; } } if (k > 0) { //DOUBLE-BUFFERED DMA OPERATION SEQUENCE // 1. Initiate and complete entity DMA transfer for the next iteration. next_idx = buf_idx ^ 1; entityAddress[next_idx] = (unsigned int) jobQueueBase + (128 * k); spu_mfcdma32((void *)(&(jobInfos[next_idx])),entityAddress[next_idx], sizeof(spe_jobEntity), entityDMAtag, MFC_GET_CMD); spu_writech(MFC_WrTagMask, 1 << entityDMAtag); (void) spu_mfcstat(2); seqLength[next_idx] = jobInfos[next_idx].seqLength; seqAddress[next_idx] = jobInfos[next_idx].seqAddr; seqDMALength[next_idx] = jobInfos[next_idx].seqDMALength; // 2. Initiate sequence DMA transfer for the next iteration. spu_mfcdma32((void *)(seqBuffer[next_idx]),seqAddress[next_idx], seqDMALength[next_idx],next_idx,MFC_GET_CMD); // 3. Wait for the last transfer to complete. spu_writech(MFC_WrTagMask, 1 << buf_idx); (void)spu_mfcstat(2); // 4. Use the data from the previous transfer viterbiScore = SPEViterbiSIMD(hmm,seqBuffer[buf_idx],seqLength[buf_idx],mscCur,mscPrev,iscCur,iscPrev,dscCur,dscPrev); j++; //DMA the result back to the PPE jobInfos[buf_idx].seqProcessed = 1; jobInfos[buf_idx].seqViterbiResult = viterbiScore; spu_mfcdma32((void *)(&(jobInfos[buf_idx])),entityAddress[buf_idx], sizeof(spe_jobEntity), entityDMAtag_back, MFC_PUT_CMD); //DMA it back... buf_idx = next_idx; } //if( k > 0 ) } //Process the final DMA spu_writech(MFC_WrTagMask, 1 << buf_idx); (void)spu_mfcstat(2); viterbiScore = SPEViterbiSIMD(hmm,seqBuffer[buf_idx],seqLength[buf_idx],mscCur,mscPrev,iscCur,iscPrev,dscCur,dscPrev); j++; //DMA the result back to the PPE jobInfos[buf_idx].seqProcessed = 1; jobInfos[buf_idx].seqViterbiResult = viterbiScore; spu_mfcdma32((void *)(&(jobInfos[buf_idx])),entityAddress[buf_idx], sizeof(spe_jobEntity), entityDMAtag_back, MFC_PUT_CMD); (void) spu_mfcstat(2); return 0; } int getSequence(){ int k; mutex_lock(bufferMutex); if (atomic_read(bufferEntries)){ //If we're here, we can fetch a sequence from the buffer. k = atomic_inc_return(lastConsumed); atomic_dec(bufferEntries); }else{ // There are no ready entries in the PPE buffer. This could happen in two situations: // 1) The SPEs have overtaken the PPE sequence file reading process. // 2) There are no sequences left to read. if (atomic_read(nomoreSeqs)==1){ //No more sequences to read. Exit. k = NO_MORE_SEQUENCES; } else { k = WAIT_FOR_MORE_SEQUENCES; //Wait until the PPE replenishes the buffer. cond_wait(bufferEmptyCond, bufferMutex); } } mutex_unlock(bufferMutex); return k; } #endif //UGENE_CELL_SPU
the_stack_data/242331405.c
#include<stdio.h> int main(){ int i,n; scanf("%d",&n); if(n<1||n>99){ printf("Number is out of range"); }else{ for(i=1;i<=12;i++){ if(n*12/1000){ printf("%d x %2d = %4d\n",n,i,n*i); }else if(n*12/100){ printf("%d x %2d = %3d\n",n,i,n*i); }else if(n*12/10){ printf("%d x %2d = %2d\n",n,i,n*i); }else{ printf("%d x %2d = %1d\n",n,i,n*i); } } } return 0; }
the_stack_data/11762.c
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers, The Plenteum developers // // This file is part of Bytecoin. // // Bytecoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Bytecoin is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with Bytecoin. If not, see <http://www.gnu.org/licenses/>. #include <assert.h> static_assert(1, "Test static assert c"); int main(int argc, char *argv[]) { return 0; }
the_stack_data/97013369.c
// // BST.c // cTree2 // // Created by Kate KyuWon on 5/31/15. // Copyright (c) 2015 Kate KyuWon. All rights reserved. // #include <stdio.h> #include <stdlib.h> typedef struct node{ int data; struct node *rightChild; struct node *leftChild; struct node *parent; }node_t; typedef struct tree{ node_t *root; }tree_t; tree_t* makeSampleBST(void); void printBSTWithInorder(node_t*); node_t* bstSearch(node_t* node, int key); node_t* bstMinimumBelow(node_t* node); node_t* bstMaximumBelow(node_t* node); node_t* bstSuccessorOf(node_t* node); node_t* bstProcessorOf(node_t* node); void test_minimum(node_t* root); void test_maximun(node_t* root); void test_successor(node_t* node); void bstInsertNode(tree_t* tree, node_t* givenNode); void bstTransplant(tree_t* tree, node_t* rmNode, node_t*mvNode); void bstDeleteNode(tree_t* tree, node_t* node); int main(void){ tree_t *tree = makeSampleBST(); puts("\ntest1: make Sample BST"); printBSTWithInorder(tree->root); puts(" "); puts("\ntest2-1: search node whose key is 12"); printf("The node whose key is %d is at %p. \n", 12 ,bstSearch(tree->root, 12)); puts("\ntest2-2: search node whose key is 2"); printf("The node whose key is %d is at %p. \n", 2 ,bstSearch(tree->root, 2)); puts("\ntest2-2: search node whose key is 7"); printf("The node whose key is %d is at %p. \n", 7 ,bstSearch(tree->root, 7)); puts("\ntest3-1: minimum node of tree"); test_minimum(tree->root); puts("\ntest3-2: maximum node of tree"); test_maximun(tree->root); puts("\ntest4-1: successor node of 2"); test_successor(bstSearch(tree->root, 2)); puts("\ntest4-2: successor node of 9"); test_successor(bstSearch(tree->root, 9)); puts("\ntest4-3: successor node of 12"); test_successor(bstSearch(tree->root, 12)); puts("\ntest4-4: successor node of 15"); test_successor(bstSearch(tree->root, 15)); puts("\ntest4-5: successor node of 19"); test_successor(bstSearch(tree->root, 19)); puts("\n\ntest4-6: successor node of 15"); printf("the precessor of 15 is %d\n", bstProcessorOf(bstSearch(tree->root, 15))->data); puts("\n\ntest4-7: successor node of 12"); printf("the precessor of 12 is %d\n", bstProcessorOf(bstSearch(tree->root, 12))->data); puts("\n\ntest5-1: BST insertion 1"); tree_t *insertTree = (tree_t*)malloc(sizeof(tree_t)); insertTree->root =NULL; node_t *insert1 = (node_t*)malloc(sizeof(node_t)); insert1->data = 1; bstInsertNode(insertTree, insert1); node_t *insert2 = (node_t*)malloc(sizeof(node_t)); insert2->data = 2; bstInsertNode(insertTree, insert2); node_t *insert3 = (node_t*)malloc(sizeof(node_t)); insert3->data = 3; bstInsertNode(insertTree, insert3); node_t *insert4 = (node_t*)malloc(sizeof(node_t)); insert4->data = 4; bstInsertNode(insertTree, insert4); node_t *insert5 = (node_t*)malloc(sizeof(node_t)); insert5->data = 5; bstInsertNode(insertTree, insert5); node_t *insert6 = (node_t*)malloc(sizeof(node_t)); insert6->data = 6; bstInsertNode(insertTree,insert6); printBSTWithInorder(insertTree->root); puts("\ntest5-2: BST insertion 2"); insertTree->root = NULL; insert1->data = 6; bstInsertNode(insertTree, insert1); insert2->data = 5; bstInsertNode(insertTree, insert2); insert3->data = 4; bstInsertNode(insertTree, insert3); insert4->data = 3; bstInsertNode(insertTree, insert4); insert5->data = 2; bstInsertNode(insertTree, insert5); insert6->data = 1; bstInsertNode(insertTree, insert6); printBSTWithInorder(insertTree->root); puts("\ntest5-3: BST insertion 3"); insertTree->root = NULL; insert1->data = 8; bstInsertNode(insertTree, insert1); insert2->data = 4; bstInsertNode(insertTree, insert2); insert3->data = 2; bstInsertNode(insertTree, insert3); insert4->data = 1; bstInsertNode(insertTree, insert4); insert5->data = 3; bstInsertNode(insertTree, insert5); insert6->data = 6; bstInsertNode(insertTree, insert6); node_t *insert7 = (node_t*)malloc(sizeof(node_t)); insert7-> data = 5; bstInsertNode(insertTree, insert7); node_t *insert8 = (node_t*)malloc(sizeof(node_t)); insert8->data = 7; bstInsertNode(insertTree, insert8); node_t *insert9 = (node_t*)malloc(sizeof(node_t)); insert9->data = 12; bstInsertNode(insertTree, insert9); node_t *insert0x = (node_t*)malloc(sizeof(node_t)); insert0x->data= 10; bstInsertNode(insertTree, insert0x); node_t *insert01 = (node_t*)malloc(sizeof(node_t)); insert01->data = 9; bstInsertNode(insertTree, insert01); node_t *insert02 = (node_t*)malloc(sizeof(node_t)); insert02->data = 11; bstInsertNode(insertTree, insert02); node_t *insert03 = (node_t*)malloc(sizeof(node_t)); insert03->data = 13; bstInsertNode(insertTree, insert03); node_t *insert04 = (node_t*)malloc(sizeof(node_t)); insert04->data = 14; bstInsertNode(insertTree, insert04); node_t *insert05 = (node_t*)malloc(sizeof(node_t)); insert05->data = 15; bstInsertNode(insertTree, insert05); printBSTWithInorder(insertTree->root); puts("\n\ntest6-1: BST transplant 1"); insertTree->root = NULL; insert4->data = 12; bstInsertNode(insertTree, insert4); insert2->data = 5; bstInsertNode(insertTree, insert2); insert7->data = 18; bstInsertNode(insertTree, insert7); insert1->data = 2; bstInsertNode(insertTree, insert1); insert3->data = 9; bstInsertNode(insertTree, insert3); insert5->data = 15; bstInsertNode(insertTree, insert5); insert6->data = 17; bstInsertNode(insertTree, insert6); insert8->data = 19; bstInsertNode(insertTree, insert8); // printf("%d",isBST(insertTree->root) ); puts("(before)"); printBSTWithInorder(insertTree->root); bstTransplant(insertTree, bstSearch(insertTree->root, 15), bstSearch(insertTree->root, 17)); puts("\n(after)"); printBSTWithInorder(insertTree->root); puts("\n\ntest6-2: BST transplant 2"); insertTree->root = NULL; insert3->data = 12; bstInsertNode(insertTree, insert3); insert2->data = 5; bstInsertNode(insertTree, insert2); insert6->data = 18; bstInsertNode(insertTree, insert6); insert1->data = 2; bstInsertNode(insertTree, insert1); insert4->data = 15; bstInsertNode(insertTree, insert4); insert5->data = 17; bstInsertNode(insertTree, insert5); insert7->data = 19; bstInsertNode(insertTree, insert7); puts("(before)"); printBSTWithInorder(insertTree->root); bstTransplant(insertTree, bstSearch(insertTree->root, 5), bstSearch(insertTree->root, 2)); puts("\n(after)"); printBSTWithInorder(insertTree->root); puts("\n\ntest7-1 : BST deletion 1"); puts("(before)"); printBSTWithInorder(tree->root); bstDeleteNode(tree, bstSearch(tree->root, 13)); puts("\n(after)"); printBSTWithInorder(tree->root); puts("\n\ntest7-2 : BST deletion 2"); puts("(before)"); tree = makeSampleBST(); printBSTWithInorder(tree->root); bstDeleteNode(tree, bstSearch(tree->root, 17)); puts("\n(after)"); printBSTWithInorder(tree->root); puts("\n\ntest7-3 : BST deletion 3"); puts("(before)"); tree= makeSampleBST(); printBSTWithInorder(tree->root); bstDeleteNode(tree, bstSearch(tree->root, 12)); puts("\n(after)"); printBSTWithInorder(tree->root); puts("\n\ntest7-4 : BST deletion 4"); puts("(before)"); tree= makeSampleBST(); printBSTWithInorder(tree->root); bstDeleteNode(tree, tree->root); puts("\n(after)"); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts(" "); bstDeleteNode(tree, tree->root); printBSTWithInorder(tree->root); puts("\ntest7-5 : BST deletion 5 - 1"); insertTree->root = NULL; insert1->data = 1; bstInsertNode(insertTree, insert1); printBSTWithInorder(insertTree->root); puts(" "); insert2->data = 2; bstInsertNode(insertTree, insert2); printBSTWithInorder(insertTree->root); puts(" "); insert3->data = 3; bstInsertNode(insertTree, insert3); printBSTWithInorder(insertTree->root); puts(" "); insert4->data = 4; bstInsertNode(insertTree, insert4); printBSTWithInorder(insertTree->root); puts(" "); insert5->data = 5; bstInsertNode(insertTree, insert5); printBSTWithInorder(insertTree->root); puts(" "); insert6->data = 6; bstInsertNode(insertTree, insert6); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 1)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 2)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 3)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 4)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 5)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 6)); printBSTWithInorder(insertTree->root); puts(" "); puts("\ntest7-5 : BST deletion 5 - 2"); insertTree->root = NULL; insert1->data = 1; bstInsertNode(insertTree, insert1); printBSTWithInorder(insertTree->root); puts(" "); insert2->data = 2; bstInsertNode(insertTree, insert2); printBSTWithInorder(insertTree->root); puts(" "); insert3->data = 3; bstInsertNode(insertTree, insert3); printBSTWithInorder(insertTree->root); puts(" "); insert4->data = 4; bstInsertNode(insertTree, insert4); printBSTWithInorder(insertTree->root); puts(" "); insert5->data = 5; bstInsertNode(insertTree, insert5); printBSTWithInorder(insertTree->root); puts(" "); insert6->data = 6; bstInsertNode(insertTree, insert6); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 6)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 5)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 4)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 3)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 2)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 1)); printBSTWithInorder(insertTree->root); puts(" "); puts("\ntest7-5 : BST deletion 5 - 3"); insertTree->root = NULL; insert1->data = 8; bstInsertNode(insertTree, insert1); printBSTWithInorder(insertTree->root); puts(" "); insert2->data = 4; bstInsertNode(insertTree, insert2); printBSTWithInorder(insertTree->root); puts(" "); insert3->data = 2; bstInsertNode(insertTree, insert3); printBSTWithInorder(insertTree->root); puts(" "); insert4->data = 1; bstInsertNode(insertTree, insert4); printBSTWithInorder(insertTree->root); puts(" "); insert5->data = 3; bstInsertNode(insertTree, insert5); printBSTWithInorder(insertTree->root); puts(" "); insert6->data = 6; bstInsertNode(insertTree, insert6); printBSTWithInorder(insertTree->root); puts(" "); insert7->data = 5; bstInsertNode(insertTree, insert7); printBSTWithInorder(insertTree->root); puts(" "); insert8->data = 7; bstInsertNode(insertTree, insert8); printBSTWithInorder(insertTree->root); puts(" "); insert9->data = 12; bstInsertNode(insertTree, insert9); printBSTWithInorder(insertTree->root); puts(" "); bstInsertNode(insertTree, insert0x); printBSTWithInorder(insertTree->root); puts(" "); bstInsertNode(insertTree, insert01); printBSTWithInorder(insertTree->root); puts(" "); bstInsertNode(insertTree, insert02); printBSTWithInorder(insertTree->root); puts(" "); bstInsertNode(insertTree, insert03); printBSTWithInorder(insertTree->root); puts(" "); bstInsertNode(insertTree, insert04); printBSTWithInorder(insertTree->root); puts(" "); bstInsertNode(insertTree, insert05); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 7)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 6)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 5)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 9)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 12)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 8)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 4)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 15)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 13)); printBSTWithInorder(insertTree->root); puts(" "); bstDeleteNode(insertTree, bstSearch(insertTree->root, 9)); printBSTWithInorder(insertTree->root); puts(" "); } void bstDeleteNode(tree_t* tree, node_t* node){ if(!tree||!node) return; node_t* successor = NULL; if(!node->leftChild) bstTransplant(tree, node, node->rightChild); else if(!node->rightChild) bstTransplant(tree, node, node->leftChild); else{ successor = bstSuccessorOf(node); if(successor != node->rightChild){ bstTransplant(tree, successor, successor->rightChild); successor->rightChild = node->rightChild; node->rightChild->parent = successor; } bstTransplant(tree, node, successor); successor->leftChild = node->leftChild; node->leftChild->parent = successor; } } void bstTransplant(tree_t* tree, node_t* rmNode, node_t*mvNode){ if(!tree||!rmNode) NULL; if(rmNode == tree->root){ tree->root = mvNode; if(mvNode) mvNode->parent = NULL; } else if(rmNode == rmNode->parent->leftChild){ rmNode->parent->leftChild = mvNode; } else if(rmNode == rmNode->parent->rightChild){ rmNode->parent->rightChild = mvNode; } if(mvNode) mvNode->parent = rmNode->parent; } node_t* bstProcessorOf(node_t* node){ if(!node) return NULL; node_t* curNode = node; if(node->leftChild) return bstMaximumBelow(node->leftChild); else { while(curNode){ if(curNode == curNode->parent->rightChild) return curNode->parent; curNode = curNode->parent; } } return curNode; } int isBST(node_t* node){ if(!node) return 1; if(!node->leftChild && !node->rightChild) return 1; if(node->leftChild) if(node->leftChild->data > node->data) return 0; if(node->rightChild) if(node->data > node->rightChild->data) return 0; if(! isBST(node->leftChild) ) return 0; if(! isBST(node->rightChild) ) return 0; return 1; } int countLeafNode(node_t* node){ if(!node) return 0; if(!(node->leftChild) && !(node->rightChild) ) return 1; return countLeafNode(node->leftChild) + countLeafNode(node->rightChild); } void bstInsertNode(tree_t* tree, node_t* givenNode){ if(!tree||!givenNode) return; if(!tree->root){ tree->root = givenNode; givenNode->leftChild = NULL; givenNode->rightChild = NULL; return ; } node_t *curNode = tree->root; node_t *parent = NULL; while(curNode){ parent = curNode; if(curNode->data < givenNode->data) curNode = curNode->rightChild; else curNode = curNode->leftChild; } if(givenNode->data < parent->data) { parent->leftChild = givenNode; } else{ parent->rightChild = givenNode; } givenNode->parent = parent; givenNode->leftChild =NULL; givenNode->rightChild =NULL; } node_t* bstSuccessorOf(node_t* node){ if(!node) return NULL; if(node->rightChild) return bstMinimumBelow(node->rightChild); else{ while(node->parent){ if(node == node->parent->leftChild) return node->parent; node = node->parent; } } return NULL; } void test_successor(node_t* node){ node_t *successor = bstSuccessorOf(node); if(!successor) { printf("successor μ—†μŒ"); return ; } printf("%d, ", successor->data); if(successor->parent) printf("%p, %d, ", successor->parent, successor->parent->data); else printf("NULL, μ—†μŒ, "); if(successor->leftChild) printf("%p, %d, ", successor->leftChild, successor->leftChild->data); else printf("NULL, μ—†μŒ, "); if(successor->rightChild) printf("%p, %d \n", successor->rightChild, successor->rightChild->data); else printf("NULL, μ—†μŒ \n"); } void test_minimum(node_t* root){ node_t *min = bstMinimumBelow(root); printf("%d, ", min->data); if(min->parent) printf("%p, %d, ", min->parent, min->parent->data); else printf("NULL, μ—†μŒ, "); if(min->leftChild) printf("%p, %d, ", min->leftChild, min->leftChild->data); else printf("NULL, μ—†μŒ, "); if(min->rightChild) printf("%p, %d \n", min->rightChild, min->rightChild->data); else printf("NULL, μ—†μŒ \n"); } void test_maximun(node_t* root){ node_t *max = bstMaximumBelow(root); printf("%d, ", max->data); if(max->parent) printf("%p, %d, ", max->parent, max->parent->data); else printf("NULL, μ—†μŒ, "); if(max->leftChild) printf("%p, %d, ", max->leftChild, max->leftChild->data); else printf("NULL, μ—†μŒ, "); if(max->rightChild) printf("%p, %d \n", max->rightChild, max->rightChild->data); else printf("NULL, μ—†μŒ \n"); } node_t* bstMinimumBelow(node_t* node){ if(!node) return NULL; while(node->leftChild) node = node->leftChild; return node; } node_t* bstMaximumBelow(node_t* node){ if(!node) return NULL; while(node->rightChild) node = node->rightChild; return node; } node_t* bstSearch(node_t* node, int key){ if(!node) return NULL; while((node) && (node->data != key)){ if(node->data < key) node = node->rightChild; else node = node->leftChild; } return node; } void printBSTWithInorder(node_t* node){ if(!node) return; printBSTWithInorder(node->leftChild); printf("%d ", node->data); printBSTWithInorder(node->rightChild); } tree_t* makeSampleBST(void){ tree_t *newTree = (tree_t*)malloc(sizeof(tree_t)); node_t *depth0 = (node_t*)malloc(sizeof(node_t)); newTree->root = depth0; depth0->data = 12; depth0->parent = NULL; node_t *depth1_1 = (node_t*)malloc(sizeof(node_t)); depth1_1->data = 5; depth1_1->parent = depth0; depth0->leftChild = depth1_1; node_t *depth1_2 = (node_t*)malloc(sizeof(node_t)); depth1_2->data = 18; depth1_2->parent = depth0; depth0->rightChild =depth1_2; node_t *depth2_1 = (node_t*)malloc(sizeof(node_t)); depth2_1->data = 2; depth2_1->parent= depth1_1; depth1_1->leftChild= depth2_1; depth2_1->leftChild = NULL; depth2_1->rightChild = NULL; node_t* depth2_2 = (node_t*)malloc(sizeof(node_t)); depth2_2->data = 9; depth2_2->parent = depth1_1; depth1_1->rightChild =depth2_2; depth2_2->leftChild = NULL; depth2_2->rightChild = NULL; node_t *depth2_3 = (node_t*)malloc(sizeof(node_t)); depth2_3->data =15; depth2_3->parent = depth1_2; depth1_2->leftChild = depth2_3; node_t *depth2_4 = (node_t*)malloc(sizeof(node_t)); depth2_4->data = 19; depth2_4->parent = depth1_2; depth1_2->rightChild =depth2_4; depth2_4->leftChild = NULL; depth2_4->rightChild = NULL; node_t *depth3_1 = (node_t*)malloc(sizeof(node_t)); depth3_1->data = 13; depth3_1->parent = depth2_3; depth2_3->leftChild =depth3_1; depth3_1->leftChild = NULL; depth3_1->rightChild = NULL; node_t *depth3_2 = (node_t*)malloc(sizeof(node_t)); depth3_2->data = 17; depth3_2->parent = depth2_3; depth2_3->rightChild =depth3_2; depth3_2->leftChild= NULL; depth3_2->rightChild = NULL; return newTree; }
the_stack_data/36024.c
/* # # ---------------------------------------------------------------------------- # # Copyright 2019 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ---------------------------------------------------------------------------- # */ #include <stdlib.h> #include <stdio.h> #include <assert.h> int main(int argc, const char **argv) { if(argc != 2){ printf("Usage: chop-detrace <bin_file>\n"); if (argc == 1) { exit(0); } exit(-1); } FILE *fp = fopen(argv[1], "r"); assert(fp); long dat; int trace_id = 0; while (fread(&dat, sizeof(long), 1, fp) > 0) { switch (dat) { case -1: printf("# trace %d\n", trace_id); break; case -2: ++trace_id; break; default: printf("%lx\n", dat); }; } }
the_stack_data/418906.c
/*-----------------------------------------------------------*/ /*--- Block recoverer program for bzip2 ---*/ /*--- bzip2recover.c ---*/ /*-----------------------------------------------------------*/ /* ------------------------------------------------------------------ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. bzip2/libbzip2 version 1.0.6 of 6 September 2010 Copyright (C) 1996-2010 Julian Seward <[email protected]> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. This program is released under the terms of the license contained in the file LICENSE. ------------------------------------------------------------------ */ /* This program is a complete hack and should be rewritten properly. It isn't very complicated. */ #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <string.h> /* This program records bit locations in the file to be recovered. That means that if 64-bit ints are not supported, we will not be able to recover .bz2 files over 512MB (2^32 bits) long. On GNU supported platforms, we take advantage of the 64-bit int support to circumvent this problem. Ditto MSVC. This change occurred in version 1.0.2; all prior versions have the 512MB limitation. */ #ifdef __GNUC__ typedef unsigned long long int MaybeUInt64; # define MaybeUInt64_FMT "%Lu" #else #ifdef _MSC_VER typedef unsigned __int64 MaybeUInt64; # define MaybeUInt64_FMT "%I64u" #else typedef unsigned int MaybeUInt64; # define MaybeUInt64_FMT "%u" #endif #endif typedef unsigned int UInt32; typedef int Int32; typedef unsigned char UChar; typedef char Char; typedef unsigned char Bool; #define True ((Bool)1) #define False ((Bool)0) #define BZ_MAX_FILENAME 2000 Char inFileName[BZ_MAX_FILENAME]; Char outFileName[BZ_MAX_FILENAME]; Char progName[BZ_MAX_FILENAME]; MaybeUInt64 bytesOut = 0; MaybeUInt64 bytesIn = 0; /*---------------------------------------------------*/ /*--- Header bytes ---*/ /*---------------------------------------------------*/ #define BZ_HDR_B 0x42 /* 'B' */ #define BZ_HDR_Z 0x5a /* 'Z' */ #define BZ_HDR_h 0x68 /* 'h' */ #define BZ_HDR_0 0x30 /* '0' */ /*---------------------------------------------------*/ /*--- I/O errors ---*/ /*---------------------------------------------------*/ /*---------------------------------------------*/ static void readError ( void ) { fprintf ( stderr, "%s: I/O error reading `%s', possible reason follows.\n", progName, inFileName ); perror ( progName ); fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", progName ); exit ( 1 ); } /*---------------------------------------------*/ static void writeError ( void ) { fprintf ( stderr, "%s: I/O error reading `%s', possible reason follows.\n", progName, inFileName ); perror ( progName ); fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", progName ); exit ( 1 ); } /*---------------------------------------------*/ static void mallocFail ( Int32 n ) { fprintf ( stderr, "%s: malloc failed on request for %d bytes.\n", progName, n ); fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", progName ); exit ( 1 ); } /*---------------------------------------------*/ static void tooManyBlocks ( Int32 max_handled_blocks ) { fprintf ( stderr, "%s: `%s' appears to contain more than %d blocks\n", progName, inFileName, max_handled_blocks ); fprintf ( stderr, "%s: and cannot be handled. To fix, increase\n", progName ); fprintf ( stderr, "%s: BZ_MAX_HANDLED_BLOCKS in bzip2recover.c, and recompile.\n", progName ); exit ( 1 ); } /*---------------------------------------------------*/ /*--- Bit stream I/O ---*/ /*---------------------------------------------------*/ typedef struct { FILE* handle; Int32 buffer; Int32 buffLive; Char mode; } BitStream; /*---------------------------------------------*/ static BitStream* bsOpenReadStream ( FILE* stream ) { BitStream *bs = malloc ( sizeof(BitStream) ); if (bs == NULL) mallocFail ( sizeof(BitStream) ); bs->handle = stream; bs->buffer = 0; bs->buffLive = 0; bs->mode = 'r'; return bs; } /*---------------------------------------------*/ static BitStream* bsOpenWriteStream ( FILE* stream ) { BitStream *bs = malloc ( sizeof(BitStream) ); if (bs == NULL) mallocFail ( sizeof(BitStream) ); bs->handle = stream; bs->buffer = 0; bs->buffLive = 0; bs->mode = 'w'; return bs; } /*---------------------------------------------*/ static void bsPutBit ( BitStream* bs, Int32 bit ) { if (bs->buffLive == 8) { Int32 retVal = putc ( (UChar) bs->buffer, bs->handle ); if (retVal == EOF) writeError(); bytesOut++; bs->buffLive = 1; bs->buffer = bit & 0x1; } else { bs->buffer = ( (bs->buffer << 1) | (bit & 0x1) ); bs->buffLive++; }; } /*---------------------------------------------*/ /*-- Returns 0 or 1, or 2 to indicate EOF. --*/ static Int32 bsGetBit ( BitStream* bs ) { if (bs->buffLive > 0) { bs->buffLive --; return ( ((bs->buffer) >> (bs->buffLive)) & 0x1 ); } else { Int32 retVal = getc ( bs->handle ); if ( retVal == EOF ) { if (errno != 0) readError(); return 2; } bs->buffLive = 7; bs->buffer = retVal; return ( ((bs->buffer) >> 7) & 0x1 ); } } /*---------------------------------------------*/ static void bsClose ( BitStream* bs ) { Int32 retVal; if ( bs->mode == 'w' ) { while ( bs->buffLive < 8 ) { bs->buffLive++; bs->buffer <<= 1; }; retVal = putc ( (UChar) (bs->buffer), bs->handle ); if (retVal == EOF) writeError(); bytesOut++; retVal = fflush ( bs->handle ); if (retVal == EOF) writeError(); } retVal = fclose ( bs->handle ); if (retVal == EOF) { if (bs->mode == 'w') writeError(); else readError(); } free ( bs ); } /*---------------------------------------------*/ static void bsPutUChar ( BitStream* bs, UChar c ) { Int32 i; for (i = 7; i >= 0; i--) bsPutBit ( bs, (((UInt32) c) >> i) & 0x1 ); } /*---------------------------------------------*/ static void bsPutUInt32 ( BitStream* bs, UInt32 c ) { Int32 i; for (i = 31; i >= 0; i--) bsPutBit ( bs, (c >> i) & 0x1 ); } /*---------------------------------------------*/ static Bool endsInBz2 ( Char* name ) { Int32 n = strlen ( name ); if (n <= 4) return False; return (name[n-4] == '.' && name[n-3] == 'b' && name[n-2] == 'z' && name[n-1] == '2'); } /*---------------------------------------------------*/ /*--- ---*/ /*---------------------------------------------------*/ /* This logic isn't really right when it comes to Cygwin. */ #ifdef _WIN32 # define BZ_SPLIT_SYM '\\' /* path splitter on Windows platform */ #else # define BZ_SPLIT_SYM '/' /* path splitter on Unix platform */ #endif #define BLOCK_HEADER_HI 0x00003141UL #define BLOCK_HEADER_LO 0x59265359UL #define BLOCK_ENDMARK_HI 0x00001772UL #define BLOCK_ENDMARK_LO 0x45385090UL /* Increase if necessary. However, a .bz2 file with > 50000 blocks would have an uncompressed size of at least 40GB, so the chances are low you'll need to up this. */ #define BZ_MAX_HANDLED_BLOCKS 50000 MaybeUInt64 bStart [BZ_MAX_HANDLED_BLOCKS]; MaybeUInt64 bEnd [BZ_MAX_HANDLED_BLOCKS]; MaybeUInt64 rbStart[BZ_MAX_HANDLED_BLOCKS]; MaybeUInt64 rbEnd [BZ_MAX_HANDLED_BLOCKS]; Int32 main ( Int32 argc, Char** argv ) { FILE* inFile; FILE* outFile; BitStream* bsIn, *bsWr; Int32 b, wrBlock, currBlock, rbCtr; MaybeUInt64 bitsRead; UInt32 buffHi, buffLo, blockCRC; Char* p; strcpy ( progName, argv[0] ); inFileName[0] = outFileName[0] = 0; fprintf ( stderr, "bzip2recover 1.0.6: extracts blocks from damaged .bz2 files.\n" ); if (argc != 2) { fprintf ( stderr, "%s: usage is `%s damaged_file_name'.\n", progName, progName ); switch (sizeof(MaybeUInt64)) { case 8: fprintf(stderr, "\trestrictions on size of recovered file: None\n"); break; case 4: fprintf(stderr, "\trestrictions on size of recovered file: 512 MB\n"); fprintf(stderr, "\tto circumvent, recompile with MaybeUInt64 as an\n" "\tunsigned 64-bit int.\n"); break; default: fprintf(stderr, "\tsizeof(MaybeUInt64) is not 4 or 8 -- " "configuration error.\n"); break; } exit(1); } if (strlen(argv[1]) >= BZ_MAX_FILENAME-20) { fprintf ( stderr, "%s: supplied filename is suspiciously (>= %d chars) long. Bye!\n", progName, (int)strlen(argv[1]) ); exit(1); } strcpy ( inFileName, argv[1] ); inFile = fopen ( inFileName, "rb" ); if (inFile == NULL) { fprintf ( stderr, "%s: can't read `%s'\n", progName, inFileName ); exit(1); } bsIn = bsOpenReadStream ( inFile ); fprintf ( stderr, "%s: searching for block boundaries ...\n", progName ); bitsRead = 0; buffHi = buffLo = 0; currBlock = 0; bStart[currBlock] = 0; rbCtr = 0; while (True) { b = bsGetBit ( bsIn ); bitsRead++; if (b == 2) { if (bitsRead >= bStart[currBlock] && (bitsRead - bStart[currBlock]) >= 40) { bEnd[currBlock] = bitsRead-1; if (currBlock > 0) fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT " to " MaybeUInt64_FMT " (incomplete)\n", currBlock, bStart[currBlock], bEnd[currBlock] ); } else currBlock--; break; } buffHi = (buffHi << 1) | (buffLo >> 31); buffLo = (buffLo << 1) | (b & 1); if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI && buffLo == BLOCK_HEADER_LO) || ( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI && buffLo == BLOCK_ENDMARK_LO) ) { if (bitsRead > 49) { bEnd[currBlock] = bitsRead-49; } else { bEnd[currBlock] = 0; } if (currBlock > 0 && (bEnd[currBlock] - bStart[currBlock]) >= 130) { fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT " to " MaybeUInt64_FMT "\n", rbCtr+1, bStart[currBlock], bEnd[currBlock] ); rbStart[rbCtr] = bStart[currBlock]; rbEnd[rbCtr] = bEnd[currBlock]; rbCtr++; } if (currBlock >= BZ_MAX_HANDLED_BLOCKS) tooManyBlocks(BZ_MAX_HANDLED_BLOCKS); currBlock++; bStart[currBlock] = bitsRead; } } bsClose ( bsIn ); /*-- identified blocks run from 1 to rbCtr inclusive. --*/ if (rbCtr < 1) { fprintf ( stderr, "%s: sorry, I couldn't find any block boundaries.\n", progName ); exit(1); }; fprintf ( stderr, "%s: splitting into blocks\n", progName ); inFile = fopen ( inFileName, "rb" ); if (inFile == NULL) { fprintf ( stderr, "%s: can't open `%s'\n", progName, inFileName ); exit(1); } bsIn = bsOpenReadStream ( inFile ); /*-- placate gcc's dataflow analyser --*/ blockCRC = 0; bsWr = 0; bitsRead = 0; outFile = NULL; wrBlock = 0; while (True) { b = bsGetBit(bsIn); if (b == 2) break; buffHi = (buffHi << 1) | (buffLo >> 31); buffLo = (buffLo << 1) | (b & 1); if (bitsRead == 47+rbStart[wrBlock]) blockCRC = (buffHi << 16) | (buffLo >> 16); if (outFile != NULL && bitsRead >= rbStart[wrBlock] && bitsRead <= rbEnd[wrBlock]) { bsPutBit ( bsWr, b ); } bitsRead++; if (bitsRead == rbEnd[wrBlock]+1) { if (outFile != NULL) { bsPutUChar ( bsWr, 0x17 ); bsPutUChar ( bsWr, 0x72 ); bsPutUChar ( bsWr, 0x45 ); bsPutUChar ( bsWr, 0x38 ); bsPutUChar ( bsWr, 0x50 ); bsPutUChar ( bsWr, 0x90 ); bsPutUInt32 ( bsWr, blockCRC ); bsClose ( bsWr ); } if (wrBlock >= rbCtr) break; wrBlock++; } else if (bitsRead == rbStart[wrBlock]) { /* Create the output file name, correctly handling leading paths. (31.10.2001 by Sergey E. Kusikov) */ Char* split; Int32 ofs, k; for (k = 0; k < BZ_MAX_FILENAME; k++) outFileName[k] = 0; strcpy (outFileName, inFileName); split = strrchr (outFileName, BZ_SPLIT_SYM); if (split == NULL) { split = outFileName; } else { ++split; } /* Now split points to the start of the basename. */ ofs = split - outFileName; sprintf (split, "rec%5d", wrBlock+1); for (p = split; *p != 0; p++) if (*p == ' ') *p = '0'; strcat (outFileName, inFileName + ofs); if ( !endsInBz2(outFileName)) strcat ( outFileName, ".bz2" ); fprintf ( stderr, " writing block %d to `%s' ...\n", wrBlock+1, outFileName ); outFile = fopen ( outFileName, "wb" ); if (outFile == NULL) { fprintf ( stderr, "%s: can't write `%s'\n", progName, outFileName ); exit(1); } bsWr = bsOpenWriteStream ( outFile ); bsPutUChar ( bsWr, BZ_HDR_B ); bsPutUChar ( bsWr, BZ_HDR_Z ); bsPutUChar ( bsWr, BZ_HDR_h ); bsPutUChar ( bsWr, BZ_HDR_0 + 9 ); bsPutUChar ( bsWr, 0x31 ); bsPutUChar ( bsWr, 0x41 ); bsPutUChar ( bsWr, 0x59 ); bsPutUChar ( bsWr, 0x26 ); bsPutUChar ( bsWr, 0x53 ); bsPutUChar ( bsWr, 0x59 ); } } fprintf ( stderr, "%s: finished\n", progName ); return 0; } /*-----------------------------------------------------------*/ /*--- end bzip2recover.c ---*/ /*-----------------------------------------------------------*/
the_stack_data/99866.c
#include <stdio.h> int main(void) { int A = 3, B = 1, C = 2, D = 3, E = 4; printf("A / B = %d \n", A / B); printf("A / C = %d \n", A / C); printf("A / D = %d \n", A / D); printf("A / E = %d \n", A / E); return 0; }
the_stack_data/159516307.c
#include <stdio.h> #include <assert.h> const char* MajorColorNames[] = {"White", "Red", "Black", "Yellow", "Violet"}; const char* MinorColorNames[] = {"Blue", "Orange", "Green", "Brown", "Slate"}; int numberOfMajorColors = sizeof(MajorColorNames) / sizeof(MajorColorNames[0]); int numberOfMinorColors = sizeof(MinorColorNames) / sizeof(MinorColorNames[0]); typedef struct { const char* majorColor; const char* minorColor; } ColorPair; ColorPair GetColorFromPairNumber(int pairNumber) { ColorPair colorPair; colorPair.majorColor = MajorColorNames[(pairNumber / numberOfMinorColors)]; colorPair.minorColor = MinorColorNames[(pairNumber % numberOfMinorColors)]; return colorPair; } void testNumberToPair(int pairNumber, const char* expectedMajor, const char* expectedMinor){ ColorPair colorPair = GetColorFromPairNumber(pairNumber); assert(colorPair.majorColor == expectedMajor); assert(colorPair.minorColor == expectedMinor); } int printColorMap() { const char* majorColor[] = {"White", "Red", "Black", "Yellow", "Violet"}; const char* minorColor[] = {"Blue", "Orange", "Green", "Brown", "Slate"}; int i = 0, j = 0; for(i = 0; i < 5; i++) { for(j = 0; j < 5; j++) { printf("%d | %s | %s\n", i * 5 + j, majorColor[i], minorColor[j]); } } return i * j; } int main() { int result = printColorMap(); assert(result == 25); testNumberToPair(4, "White", "Slate"); testNumberToPair(5, "Red", "Blue"); printf("All is well (maybe!)\n"); return 0; }
the_stack_data/630116.c
#include<stdio.h> void inic(int s[]) { int i; for(i=0;i<10;i++) s[i]=0; } int main(void) { int v[10], i; inic(v); for(i=0;i<10;i++) v[i]=i; for(i=10-1; i>=0; i--) printf("\t%d\n",v[i]); return 0; }
the_stack_data/1167102.c
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int nota, x; scanf("%d", &nota); printf("%d\n", nota); printf("%d nota(s) de R$ 100,00\n", nota/100); x = (nota%100); printf("%d nota(s) de R$ 50,00\n", x/50); x = (x%50); printf("%d nota(s) de R$ 20,00\n", x/20); x = (x%20); printf("%d nota(s) de R$ 10,00\n", x/10); x = (x%10); printf("%d nota(s) de R$ 5,00\n", x/5); x = (x%5); printf("%d nota(s) de R$ 2,00\n", x/2); x = (x%2); printf("%d nota(s) de R$ 1,00\n", x/1); return 0; }
the_stack_data/813343.c
/* https://www.urionlinejudge.com.br/judge/en/problems/view/1177 */ #include <stdio.h> int main(){ int t; scanf("%d", &t); int i, j; j = 0; for (i = 0; i < 1000; i++){ printf("N[%d] = %d\n", i, j); j++; if (j == t) j = 0; } return 0; }
the_stack_data/153267360.c
/**************************************************************************** * libs/libc/math/lib_libsqrtapprox.c * * This file is a part of NuttX: * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * Ported by: Darcy Gong * * It derives from the Rhombus OS math library by Nick Johnson which has * a compatibile, MIT-style license: * * Copyright (C) 2009-2011 Nick Johnson <nickbjohnson4224 at gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <stdint.h> #include <math.h> /**************************************************************************** * Public Functions ****************************************************************************/ float lib_sqrtapprox(float x) { int32_t i; /* Floats + bit manipulation = +inf fun! */ i = *((int32_t *) & x); i = 0x1fc00000 + (i >> 1); x = *((float *)&i); return x; }
the_stack_data/82951616.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_alphabet.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mghazari <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/29 19:32:23 by mghazari #+# #+# */ /* Updated: 2020/10/23 16:48:28 by mghazari ### ########.fr */ /* */ /* ************************************************************************** */ void ft_print_alphabet(void) { char a; a = 'a'; while (a <= 'z') ft_putchar(a++); return ; }
the_stack_data/29168.c
#include <stdio.h> int main() { int A, B; scanf("%d", &A); scanf("%d", &B); int X = A + B; printf("X = %d\n", X); return 0; }
the_stack_data/31388392.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define PI 3.14159265358979323846 typedef struct node *nptr; //struct typedef struct node{ struct node* next; struct node* prev; float* f; } dll; nptr insertAtEnd(nptr head, float *f, int nattr) { nptr curr = head; nptr p = malloc(sizeof(dll)); p->f = malloc(sizeof(float)*nattr); p->f = f; if(curr==NULL) { head = p; p->next = p; p->prev = p; return(head); } else { p->next = curr; p->prev = curr->prev; (curr->prev)->next = p; curr->prev = p; return(head); } } void display(nptr head, int nattr) { if(head == NULL) { printf("Empty.\n"); return; } nptr temp = head; nptr curr = head; while(1) //looping till head if found twice { for(int i=0; i<nattr; i++) printf("%g, ", curr->f[i]); printf("\n"); curr = curr->next; if(curr==temp) break; //breaking if head found second time } } nptr listify(char* filename, int nattr, nptr head) { int flag = 0; FILE *dataset = fopen(filename, "r"); while(1) { int c = 0; float* f = malloc(sizeof(float)*nattr); while(c!=nattr) { fscanf(dataset, "%g%*c", &f[c]); if(feof(dataset)) flag = 1; c++; } head = insertAtEnd(head, f, nattr); if(flag) break; } return(head); } int splitdata(nptr* train, nptr* test, int nattr) { nptr curr,temp; int c = 0; for(curr=(*train)->next;curr!=(*train);curr=curr->next) { if(rand()>((0.67)*(RAND_MAX))) { (*test)=insertAtEnd((*test),curr->f,nattr); (curr->next)->prev = curr->prev; (curr->prev)->next = curr->next; temp=curr; curr=curr->prev; free(temp); c++; } } return c; } double probability(double x, double mean, double stdev) { double expo = exp(-(pow(x-mean,2)/(2*pow(stdev,2)))); double numo = 1/(sqrt(2*PI)*stdev); return (numo*expo); } double predict(int* predictions, nptr test, double** mean, double** stdev, int size, int nattr, int nclass) { nptr curr = test; for(int i=0; i<size; i++) { double prob[nclass]; for(int j=0; j<nclass; j++) { prob[j] = 1; for(int k=0; k<nattr-1; k++) { prob[j]=prob[j]*probability(curr->f[k], mean[j][k], stdev[j][k]); // if (prob[j]>1) // printf("Something's wrong\n"); } } int class = -1; double maxprob = -1; for(int l=0; l<nclass; l++) { if(class==-1 || prob[l]>maxprob) { class = l; maxprob = prob[l]; } } predictions[i] = class; curr = curr->next; } } void statistics(nptr head, int nattr, double* mean, double* variance, double* stdev, int class) { if(head) { nptr temp = head; nptr curr = head; for(int i=0; i<nattr-1; i++) { double sum = 0; double sumv = 0; int c = 0; while(1) //looping till head if found twice { c++; curr = curr->next; if(curr->f[nattr-1] != class) { c--; if(curr==temp) break; continue; } sum = sum+curr->f[i]; if(curr==temp) break; //breaking if head found second time } mean[i] = sum/c; c = 0; while(1) //looping till head if found twice { c++; curr = curr->next; if(curr->f[nattr-1] != class) { c--; if(curr==temp) break; continue; } sumv = sumv+pow((curr->f[i]-mean[i]), 2); if(curr==temp) break; //breaking if head found second time } variance[i] = sumv/c; stdev[i] = sqrt(variance[i]); //printf("Mean: %g\nStDev%g\n\n", mean[i], stdev[i]); } } } int main(void) { srand ( time(NULL) ); nptr head; head = NULL; char* filename = "cleanIris.csv"; int nattr = 5; int nclass = 3; nptr test; test = NULL; head = listify(filename, nattr, head); int testS = splitdata(&head, &test, nattr); printf("TEST SIZE: %d\n", testS); double** mean, **variance, **stdev; mean = malloc(sizeof(int)); variance = malloc(sizeof(int)); stdev = malloc(sizeof(int)); for(int i=0; i<nclass; i++) { mean[i] = malloc(sizeof(double)*nattr); variance[i] = malloc(sizeof(double)*nattr); stdev[i] = malloc(sizeof(double)*nattr); statistics(head, nattr, mean[i], variance[i], stdev[i], i); } int* predictions = malloc(sizeof(int)*testS); predict(predictions, test, mean, stdev, testS, nattr, nclass); float error = 0; int wCount = 0; for(int i=0; i<testS; i++) { error = error + abs(test->f[nattr-1] - predictions[i]); if((int)test->f[nattr-1]!=(int)predictions[i]) wCount++; test = test->next; } printf("Accuracy: %g\n", ((float)(testS-wCount)/(float)testS)*100.0); printf("MAE: %g\n", error/testS); }
the_stack_data/111076865.c
/* */ #include<stdio.h> void school(void); void name(void); main() { school(); name(); } /* school ι–’ζ•° */ void school(void) { printf("Ass Hole\n"); } /* name ι–’ζ•° */ void name(void) { printf("your name\n"); }
the_stack_data/107017.c
#include <stdio.h> #include <stdbool.h> #include <string.h> #define MAX_FILE_NAME 100 int MARK=0; //MODE 1= Off, 0= On bool DEBUG_MODE=0; struct node { int ID; int* neighbours; int mark; }; void debug_line(char *text){ if (!DEBUG_MODE){ printf("%s\n", text); }else{ } }; void read_input(){ int count; // give some prompt... printf("Enter a line of text:\n"); printf("EOF to stop.\n"); // get character from standard input store in variable count count = getchar(); // while the End Of File is not encountered... while(count != EOF) { // put character on the standard output putchar(count); // carry on getting character from the standard input count = getchar(); } } int select_neighbour(int* initial_node){ return 0; } int next_node(struct node input_node){ int next_neighbour = input_node.ID; return next_neighbour; } void testsuite(struct node *init){ //make local copy struct node test = *init; int i=0; test.ID= 0; test.neighbours= (int*) malloc(sizeof (int)*4); for ( i=0 ;i < 4 ;i++){ test.neighbours[i]=rand() %10; printf("%d\n",test.neighbours[i]); } debug_line("Exit: Finished testsuite();"); test.mark= 0; //make changes to referenced struct *init= test; free(test.neighbours); debug_line("Step: Freed space."); for ( i=0 ;i < 4 ;i++){ printf("%d\n",test.neighbours[i]); } } int main(void) { debug_line("Compile complete;"); int c= getchar(); int i =0; while ((c = fgetc(stdin)) != EOF) { /* process `c' */ printf("%c \n",c); } debug_line("Reading completed"); struct node init; printf("1st: Enter testsuite();\n"); testsuite(&init); //read_file(); //scanf("%s", &name); - deprecated printf("Thomas is the best summoner."); return 0; }