file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/231394621.c | #include <stdio.h>
extern void a();
extern void b();
int main()
{
a();
b();
return 0;
}
|
the_stack_data/126701861.c | #include<stdio.h>
int main()
{
int i,n,a,j,k;
while(scanf("%d",&n)!=EOF){
j=0;
for(i = 0;i < n;i++){
scanf("%d",&a);
if(a>j)j=a;
}
if(j<10)k=1;
else if(j>=20)k=3;
else k=2;
printf("%d\n",k);
}
return 0;
}
|
the_stack_data/664978.c | // PARAM: --set solver td3 --enable ana.int.interval --set exp.partition-arrays.keep-expr last --enable exp.partition-arrays.enabled --set ana.activated "['base','threadid','threadflag','escape','expRelation','octagon','mallocWrapper']" --set exp.privatization none
void main(void) {
example1();
}
void example1(void) {
int a[42];
a[40] = 2;
int i = 0;
while(i < 41) {
a[i] = 0;
i++;
}
assert(a[2] == 0);
assert(a[3] == 0);
}
|
the_stack_data/104826805.c | /*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. 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.
* 4. 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.
*
* @(#)random.c 8.1 (Berkeley) 6/10/93
* $FreeBSD: src/lib/libstand/random.c,v 1.2.2.1 2000/09/10 01:25:52 ps Exp $
* $DragonFly: src/lib/libstand/random.c,v 1.4 2005/12/11 02:27:26 swildner Exp $
*/
#include <sys/types.h>
static u_long randseed = 1;
void
srandom(u_long seed)
{
randseed = seed;
}
/*
* Pseudo-random number generator for randomizing the profiling clock,
* and whatever else we might use it for. The result is uniform on
* [0, 2^31 - 1].
*/
u_long
random(void)
{
long x, hi, lo, t;
/*
* Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1).
* From "Random number generators: good ones are hard to find",
* Park and Miller, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195.
*/
x = randseed;
hi = x / 127773;
lo = x % 127773;
t = 16807 * lo - 2836 * hi;
if (t <= 0)
t += 0x7fffffff;
randseed = t;
return (t);
}
|
the_stack_data/232955711.c | #include <stdio.h>
int factorial(int fact);
int main(void)
{
int number;
printf("Please Enter an Integer Number:\n");
scanf("%d", &number);
int result = factorial(number);
printf("Your Result is: %d", result);
return 0;
}
int factorial(int fact)
{
if(fact <= 1)
return 1;
else
return (fact*factorial(fact-1));
}
|
the_stack_data/92326315.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h> //for clock() function
// Driver code to test above function
int main1()
{
//printf("Clocks per second = %d", CLOCKS_PER_SEC);
for (;;) {
printf("%d \n",clock());
}
return 0;
} |
the_stack_data/89201287.c | void f(void (*h)(int), int I) {
#pragma spf transform inline
h(I);
}
void g(int I) {
#pragma spf transform inline
f(g, I);
}
|
the_stack_data/54824890.c | /*
*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2019 Broadcom Inc. All rights reserved.
*
* File: util.c
*
* Purpose:
*
* Functions:
* _bcm_ptp_uint16_read
* _bcm_ptp_uint32_read
* _bcm_ptp_uint64_read
* _bcm_ptp_uint16_write
* _bcm_ptp_uint32_write
* _bcm_ptp_uint64_write
* _bcm_ptp_int64_read
* _bcm_ptp_function_precheck
* _bcm_ptp_clock_lookup
* _bcm_ptp_peer_address_convert
* _bcm_ptp_port_address_convert
* _bcm_ptp_peer_address_raw_compare
* _bcm_ptp_peer_address_compare
* _bcm_ptp_port_address_compare
* _bcm_ptp_addr_len
* _bcm_ptp_is_clockid_null
* _bcm_ptp_port_address_cmp
* _bcm_ptp_dump_hex
*/
#if defined(INCLUDE_PTP)
#include <shared/bsl.h>
#include <soc/defs.h>
#include <soc/drv.h>
#include <shared/bsl.h>
#include <sal/core/time.h>
#include <sal/core/dpc.h>
#include <shared/bsl.h>
#include <bcm/ptp.h>
#include <bcm_int/common/ptp.h>
#include <bcm/error.h>
#if defined(BCM_PTP_INTERNAL_STACK_SUPPORT)
#ifdef NO_SAL_APPL
#include <string.h>
#else
#include <sal/appl/sal.h>
#endif
#include <include/soc/uc.h>
#endif /* BCM_PTP_INTERNAL_STACK_SUPPORT */
#include <bcm_int/control.h>
#define PTP_UTIL_HEXDUMP_LINE_WIDTH_OCTETS (100)
static const bcm_ptp_clock_identity_t BCM_PTP_ALL_CLOCKS = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
/*
* Function:
* _bcm_ptp_uint16_read
* Purpose:
* Read a 16-bit unsigned integer from a buffer in network byte order.
* Parameters:
* buffer - (IN) Data buffer.
* Returns:
* Result.
* Notes:
*/
uint16
_bcm_ptp_uint16_read(
uint8* buffer)
{
return ((((uint16)(buffer[0])) << 8) + (((uint16)(buffer[1]))));
}
/*
* Function:
* _bcm_ptp_uint32_read
* Purpose:
* Read a 32-bit unsigned integer from a buffer in network byte order.
* Parameters:
* buffer - (IN) Data buffer.
* Returns:
* Result.
* Notes:
*/
uint32
_bcm_ptp_uint32_read(
uint8* buffer)
{
return ((((uint32)(buffer[0])) << 24) +
(((uint32)(buffer[1])) << 16) +
(((uint32)(buffer[2])) << 8) +
(((uint32)(buffer[3]))));
}
/*
* Function:
* _bcm_ptp_uint64_read
* Purpose:
* Read a 64-bit unsigned integer from a buffer in network byte order.
* Parameters:
* buffer - (IN) Data buffer.
* Returns:
* Result.
* Notes:
*/
uint64
_bcm_ptp_uint64_read(uint8* buffer)
{
uint64 val64;
COMPILER_64_SET(val64,
(buffer[0] << 24) + (buffer[1] << 16) +
(buffer[2] << 8) + buffer[3],
(buffer[4] << 24) + (buffer[5] << 16) +
(buffer[6] << 8) + buffer[7]);
return val64;
}
/*
* Function:
* _bcm_ptp_uint16_write
* Purpose:
* Write a 16-bit unsigned integer to a buffer in network byte order.
* Parameters:
* value - (IN) Data.
* buffer - (OUT) Data buffer.
* Returns:
* None.
* Notes:
*/
void
_bcm_ptp_uint16_write(
uint8* buffer,
const uint16 value)
{
buffer[0] = ((value >> 8) & 0xff);
buffer[1] = ((value) & 0xff);
}
/*
* Function:
* _bcm_ptp_uint32_write
* Purpose:
* Write a 32-bit unsigned integer to a buffer in network byte order.
* Parameters:
* value - (IN) Data.
* buffer - (OUT) Data buffer.
* Returns:
* None.
* Notes:
*/
void
_bcm_ptp_uint32_write(
uint8* buffer,
const uint32 value)
{
buffer[0] = ((value >> 24) & 0xff);
buffer[1] = ((value >> 16) & 0xff);
buffer[2] = ((value >> 8) & 0xff);
buffer[3] = ((value) & 0xff);
}
/*
* Function:
* _bcm_ptp_uint64_write
* Purpose:
* Write a 64-bit unsigned integer to a buffer in network byte order.
* Parameters:
* value - (IN) Data.
* buffer - (OUT) Data buffer.
* Returns:
* None.
* Notes:
*/
void
_bcm_ptp_uint64_write(
uint8* buffer,
const uint64 value)
{
uint32 low;
uint32 high;
COMPILER_64_TO_32_LO(low,value);
COMPILER_64_TO_32_HI(high,value);
buffer[0] = ((high >> 24) & 0xff);
buffer[1] = ((high >> 16) & 0xff);
buffer[2] = ((high >> 8) & 0xff);
buffer[3] = ((high) & 0xff);
buffer[4] = ((low >> 24) & 0xff);
buffer[5] = ((low >> 16) & 0xff);
buffer[6] = ((low >> 8) & 0xff);
buffer[7] = ((low) & 0xff);
}
/*
* Function:
* _bcm_ptp_int64_write
* Purpose:
* Write a 64-bit signed integer to a buffer in network byte order.
* Parameters:
* value - (IN) Data.
* buffer - (OUT) Data buffer.
* Returns:
* None.
* Notes:
* Casting to and from int64_t is not available on some platforms
*/
void
_bcm_ptp_int64_write(
uint8* buffer,
const int64 value)
{
buffer[0] = (COMPILER_64_HI(value) >> 24) & 0xff;
buffer[1] = (COMPILER_64_HI(value) >> 16) & 0xff;
buffer[2] = (COMPILER_64_HI(value) >> 8) & 0xff;
buffer[3] = (COMPILER_64_HI(value) & 0xff);
buffer[4] = (COMPILER_64_LO(value) >> 24) & 0xff;
buffer[5] = (COMPILER_64_LO(value) >> 16) & 0xff;
buffer[6] = (COMPILER_64_LO(value) >> 8) & 0xff;
buffer[7] = (COMPILER_64_LO(value) & 0xff);
}
/*
* Function:
* _bcm_ptp_int64_read
* Purpose:
* Read a 64-bit signed integer from a buffer in network byte order.
* Parameters:
* buffer - (IN) Data buffer.
* Returns:
* Result.
* Notes:
* Casting to and from int64_t is not available on some platforms
*/
int64
_bcm_ptp_int64_read(uint8* buffer)
{
int64 val;
int64 temp;
COMPILER_64_SET(temp, buffer[0] << 24, 0);
val = temp;
COMPILER_64_SET(temp, buffer[1] << 16, 0);
COMPILER_64_ADD_64(val, temp);
COMPILER_64_SET(temp, buffer[2] << 8, 0);
COMPILER_64_ADD_64(val, temp);
COMPILER_64_SET(temp, buffer[3], 0);
COMPILER_64_ADD_64(val, temp);
COMPILER_64_SET(temp, 0, buffer[4] << 24);
COMPILER_64_ADD_64(val, temp);
COMPILER_64_SET(temp, 0, buffer[5] << 16);
COMPILER_64_ADD_64(val, temp);
COMPILER_64_SET(temp, 0, buffer[6] << 8);
COMPILER_64_ADD_64(val, temp);
COMPILER_64_SET(temp, 0, buffer[7]);
COMPILER_64_ADD_64(val, temp);
return val;
}
/*
* Function:
* _bcm_ptp_function_precheck
* Purpose:
* Perform basic argument and PTP module prechecks on a function.
* Parameters:
* unit - (IN) Unit number.
* ptp_id - (IN) PTP stack ID.
* clock_num - (IN) PTP clock number.
* clock_port - (IN) PTP clock port number.
* Returns:
* BCM_E_XXX
* Notes:
*/
int
_bcm_ptp_function_precheck(
int unit,
bcm_ptp_stack_id_t ptp_id,
int clock_num,
uint32 clock_port)
{
int rv = BCM_E_UNAVAIL;
_bcm_ptp_info_t *ptp_info_p;
bcm_ptp_clock_info_t ci;
if ((unit < PTP_UNIT_NUMBER_DEFAULT) ||
(unit >= BCM_MAX_NUM_UNITS)) {
return BCM_E_PARAM;
}
if (soc_feature(unit, soc_feature_ptp)) {
SET_PTP_INFO;
if (ptp_info_p->memstate != PTP_MEMSTATE_INITIALIZED) {
return BCM_E_UNAVAIL;
}
/* Argument checking and error handling. */
if ((ptp_id < PTP_STACK_ID_DEFAULT) ||
(ptp_id >= PTP_MAX_STACKS_PER_UNIT) ||
(clock_num < PTP_CLOCK_NUMBER_DEFAULT) ||
(clock_num >= PTP_MAX_CLOCK_INSTANCES)) {
return BCM_E_PARAM;
}
if ((clock_port == PTP_IEEE1588_ALL_PORTS) ||
(clock_port == PTP_CLOCK_PORT_NUMBER_DEFAULT)) {
return BCM_E_NONE;
} else {
if (BCM_FAILURE(rv = _bcm_ptp_clock_cache_info_get(unit, ptp_id,
clock_num, &ci))) {
return rv;
}
if ((clock_port < PTP_CLOCK_PORT_NUMBER_DEFAULT) ||
(clock_port > ci.num_ports)) {
return BCM_E_PORT;
}
switch (ci.type) {
case bcmPTPClockTypeOrdinary:
case bcmPTPClockTypeBoundary:
case bcmPTPClockTypeTransparent:
break;
default:
return BCM_E_PARAM;
}
}
}
return rv;
}
/*
* Function:
* _bcm_ptp_clock_lookup
* Purpose:
* Lookup the PTP clock number of a PTP clock for a given unit / PTP stack ID
* based on caller-provided clock identity.
* Parameters:
* clock_identity - (IN) PTP clock identity to lookup.
* unit - (IN) Unit number.
* ptp_id - (IN) PTP stack ID.
* clock_num - (OUT) PTP clock number.
* Returns:
* BCM_E_XXX
* Notes:
*/
int _bcm_ptp_clock_lookup(
const bcm_ptp_clock_identity_t clock_identity,
int unit,
bcm_ptp_stack_id_t ptp_id,
int *clock_num)
{
bcm_ptp_clock_info_t ci;
int i;
/* Affiliate "all-clocks" clockIdentity with default stack, unit, and clock number. */
if (!memcmp(BCM_PTP_ALL_CLOCKS, clock_identity, sizeof(bcm_ptp_clock_identity_t))) {
/* this should only match if the unit/ptp_id match the defaults */
if (unit == PTP_UNIT_NUMBER_DEFAULT && ptp_id == PTP_STACK_ID_DEFAULT) {
*clock_num = PTP_CLOCK_NUMBER_DEFAULT;
return BCM_E_NONE;
} else {
return BCM_E_NOT_FOUND;
}
}
if (!BCM_UNIT_VALID(unit)) {
return BCM_E_NOT_FOUND;
}
if ((unit < PTP_UNIT_NUMBER_DEFAULT) ||
(unit >= BCM_MAX_NUM_UNITS))
{
return BCM_E_PARAM;
}
for (i = PTP_CLOCK_NUMBER_DEFAULT; i < PTP_MAX_CLOCK_INSTANCES; ++i) {
if (BCM_FAILURE(_bcm_ptp_clock_cache_info_get(unit, ptp_id, i, &ci))) {
continue;
}
if (!memcmp(ci.clock_identity, clock_identity, sizeof(bcm_ptp_clock_identity_t))) {
*clock_num = i;
return BCM_E_NONE;
}
}
return BCM_E_NOT_FOUND;
}
/* Function:
* _bcm_ptp_peer_address_convert
* Purpose:
* Convert address from peer format to clock-port format.
* Parameters:
* peer_addr - (IN) Address (peer format).
* port_addr - (OUT) Address (clock-port format).
* Returns:
* BCM_E_XXX - Function status.
* Notes:
*/
int
_bcm_ptp_peer_address_convert(
bcm_ptp_clock_peer_address_t *peer_addr,
bcm_ptp_clock_port_address_t *port_addr)
{
port_addr->addr_type = peer_addr->addr_type;
memset(port_addr->address, 0, BCM_PTP_MAX_NETW_ADDR_SIZE);
switch (peer_addr->addr_type) {
case bcmPTPUDPIPv4:
_bcm_ptp_uint32_write(port_addr->address, peer_addr->ipv4_addr);
break;
case bcmPTPUDPIPv6:
memcpy(port_addr->address, peer_addr->ipv6_addr, PTP_IPV6_ADDR_SIZE_BYTES);
break;
default:
return BCM_E_PARAM;
}
return BCM_E_NONE;
}
/*
* Function:
* _bcm_ptp_port_address_convert
* Purpose:
* Convert address from clock-port format to peer format.
* Parameters:
* port_addr - (IN) Address (clock-port format).
* peer_addr - (OUT) Address (peer format).
* Returns:
* BCM_E_XXX - Function status.
* Notes:
*/
int
_bcm_ptp_port_address_convert(
bcm_ptp_clock_port_address_t *port_addr,
bcm_ptp_clock_peer_address_t *peer_addr)
{
peer_addr->addr_type = port_addr->addr_type;
switch (port_addr->addr_type) {
case bcmPTPUDPIPv4:
peer_addr->ipv4_addr = _bcm_ptp_uint32_read(port_addr->address);
break;
case bcmPTPUDPIPv6:
memcpy(peer_addr->ipv6_addr, port_addr->address, PTP_IPV6_ADDR_SIZE_BYTES);
break;
default:
return BCM_E_PARAM;
}
return BCM_E_NONE;
}
/*
* Function:
* _bcm_ptp_peer_address_raw_compare
* Purpose:
* Compare addresses.
* Address "A" is a peer-address type.
* Address "B" is a raw multi-octet buffer.
* Parameters:
* a - (IN) Address "A".
* b - (IN) Address "B".
* protocol - (IN) Address "B" network protocol.
* Returns:
* 0: Addresses do not match.
* 1: Addresses match.
* Notes:
*/
int
_bcm_ptp_peer_address_raw_compare(
const bcm_ptp_clock_peer_address_t *a,
uint8 *b,
bcm_ptp_protocol_t protocol)
{
if (a->addr_type != protocol) {
return 0;
}
switch (protocol) {
case bcmPTPUDPIPv4:
return (a->ipv4_addr == _bcm_ptp_uint32_read(b));
case bcmPTPUDPIPv6:
return !memcmp(a->ipv6_addr, b, PTP_IPV6_ADDR_SIZE_BYTES);
default:
return 0;
}
}
/*
* Function:
* _bcm_ptp_peer_address_compare
* Purpose:
* Compare addresses.
* Parameters:
* a - (IN) Address "A".
* b - (IN) Address "B".
* Returns:
* 0: Addresses do not match.
* 1: Addresses match.
* Notes:
*/
int
_bcm_ptp_peer_address_compare(
const bcm_ptp_clock_peer_address_t *a,
const bcm_ptp_clock_peer_address_t *b)
{
if (a->addr_type != b->addr_type) {
return 0;
}
switch (a->addr_type) {
case bcmPTPUDPIPv4:
return (a->ipv4_addr == b->ipv4_addr);
case bcmPTPUDPIPv6:
return !memcmp(a->ipv6_addr, b->ipv6_addr, PTP_IPV6_ADDR_SIZE_BYTES);
default:
return 0;
}
}
/*
* Function:
* _bcm_ptp_peer_portid_compare
* Purpose:
* Compare port Identity.
* Parameters:
* a - (IN) ClockId "A".
* b - (IN) ClockId "B".
* Returns:
* 0: Not match.
* 1: Match.
* Notes:
*/
int
_bcm_ptp_peer_portid_compare(
const bcm_ptp_port_identity_t *a,
const bcm_ptp_port_identity_t *b)
{
/*
LOG_VERBOSE(BSL_LS_BCM_PTP,
(BSL_META_U(0, " PortId_A[%0x %0x %0x %0x %0x %0x %0x %0x : %d] PortId_B[%0x %0x %0x %0x %0x %0x %0x %0x : %d] \n"),
a->clock_identity[0],a->clock_identity[1],a->clock_identity[2],
a->clock_identity[3],a->clock_identity[4],a->clock_identity[5],
a->clock_identity[6],a->clock_identity[7],
a->port_number,
b->clock_identity[0],b->clock_identity[1],b->clock_identity[2],
b->clock_identity[3],b->clock_identity[4],b->clock_identity[5],
b->clock_identity[6],b->clock_identity[7],
b->port_number));
*/
if (a->port_number != b->port_number) {
return 0;
}
return !memcmp(a->clock_identity, b->clock_identity, sizeof(bcm_ptp_clock_identity_t));
}
/*
* Function:
* _bcm_ptp_port_address_compare
* Purpose:
* Compare addresses (clock-port address format).
* Parameters:
* a - (IN) Address "A".
* b - (IN) Address "B".
* Returns:
* 0: Addresses do not match.
* 1: Addresses match.
* Notes:
*/
int
_bcm_ptp_port_address_compare(
const bcm_ptp_clock_port_address_t *a,
const bcm_ptp_clock_port_address_t *b)
{
if (a->addr_type != b->addr_type) {
return 0;
}
return !memcmp(a->address, b->address, _bcm_ptp_addr_len((int)a->addr_type));
}
/*
* Function:
* _bcm_ptp_addr_len
* Purpose:
* Determine address length.
* Parameters:
* addr_type - (IN) Address Type
* Returns:
* 0 : Invalid Address Type.
* Address Length : Valid Address Type
*
* Notes:
*/
int _bcm_ptp_addr_len(int addr_type) {
switch (addr_type) {
case bcmPTPUDPIPv4:
return PTP_IPV4_ADDR_SIZE_BYTES;
case bcmPTPUDPIPv6:
return PTP_IPV6_ADDR_SIZE_BYTES;
case bcmPTPIEEE8023:
return 6;
default:
return 0;
}
}
/*
* Function:
* _bcm_ptp_is_clock_id_null
* Purpose:
* Check if PTP clock identity is all zeros.
* Parameters:
* clockID - (IN) PTP Clock Identity.
* Returns:
* 0: Clock Identity is not NULL
* 1: Clock Identity is NULL
* Notes:
*/
int _bcm_ptp_is_clockid_null(bcm_ptp_clock_identity_t clockID)
{
int i;
for (i = 0; i < BCM_PTP_CLOCK_EUID_IEEE1588_SIZE; ++i) {
if (clockID[i] != 0) {
return 0;
}
}
return 1;
}
/*
* Function:
* _bcm_ptp_port_address_cmp
* Purpose:
* Compare addresses.
* Parameters:
* a - (IN) Address "A".
* b - (IN) Address "B".
* Returns:
* 0: Addresses match.
* Nonzero: Addresses do not match.
* Notes:
*/
int _bcm_ptp_port_address_cmp(bcm_ptp_clock_port_address_t *a, bcm_ptp_clock_port_address_t *b)
{
if (a->addr_type > b->addr_type) {
return 1;
}
if (a->addr_type < b->addr_type) {
return -1;
}
return memcmp(a->address, b->address, _bcm_ptp_addr_len(a->addr_type));
}
/*
* Function:
* _bcm_ptp_dump_hex
* Purpose:
* Print hexadecimal buffer.
* Parameters:
* buf - (IN) buffer to be printed
* len - (IN) message length
* indent - (IN) number of spaces to indent
* Returns:
* none
* Notes:
*/
void _bcm_ptp_dump_hex(uint8 *buf, int len, int indent)
{
char line[PTP_UTIL_HEXDUMP_LINE_WIDTH_OCTETS];
int i,j;
int linepos = 0;
/*
* Limit number of spaces to indent based on line width and the
* maximum hexadecimal data width (32 x 3 + 1 null terminator).
*/
indent = indent > (PTP_UTIL_HEXDUMP_LINE_WIDTH_OCTETS - 97) ?
(PTP_UTIL_HEXDUMP_LINE_WIDTH_OCTETS - 97) : indent;
for (j = 0; j < indent; j++) {
sal_sprintf(line+linepos++," ");
}
for (i = 0; i < len; ++i) {
sal_sprintf(line + linepos, "%02x", *buf++);
linepos += 2;
sal_sprintf(line + linepos, " ");
++linepos;
if ((i & 0x1f) == 0x1f) {
LOG_CLI((BSL_META("%s\n"), line));
line[0] = 0;
linepos = 0;
for (j = 0; j < indent; j++) {
sal_sprintf(line+linepos++," ");
}
}
}
/* output last line if it wasn't complete */
if (len & 0x1f) {
LOG_CLI((BSL_META("%s\n"), line));
}
}
sal_time_t _bcm_ptp_monotonic_time()
{
static _bcm_ptp_mutex_t mutex = 0;
static int32 time_offset = 0;
static sal_time_t last_time;
static sal_usecs_t last_usecs;
sal_time_t this_time = sal_time(), offset_time;
sal_usecs_t this_usecs = sal_time_usecs();
int32 usecs_diff, time_diff, time_jump;
int rv;
if (!mutex) {
mutex = _bcm_ptp_mutex_create("ptp_monotonic_time");
last_time = this_time;
last_usecs = this_usecs;
}
rv = _bcm_ptp_mutex_take(mutex, 1000000); /* one second timeout */
if (rv != BCM_E_NONE) {
LOG_ERROR(BSL_LS_BCM_COMMON,
(BSL_META("Failed to get PTP monotonic_time mutex: %d (%s)\n"), rv, bcm_errmsg(rv)));
return this_time + time_offset;
}
time_diff = (int32)(this_time - last_time);
usecs_diff = (int32)(this_usecs - last_usecs);
/* if the clock hasn't been adjusted, the difference between these two differences
should be zero. If it has been adjusted, the difference is the magnitude of the
"time jump"
*/
time_jump = time_diff - (usecs_diff / 1000000);
if (time_jump < -2 || time_jump > 2) {
LOG_INFO(BSL_LS_BCM_PTP,
(BSL_META("Time jumped by %d seconds \n"), (int)time_jump));
/* the output of sal_time() evidently jumped, so incorporate that jump into future output */
time_offset -= time_jump;
}
last_time = this_time;
last_usecs = this_usecs;
offset_time = this_time + time_offset;
_bcm_ptp_mutex_give(mutex);
return offset_time;
}
#if defined(BCM_PTP_INTERNAL_STACK_SUPPORT)
/*
* Function:
* _bcm_ptp_check_firmware_exist
* Purpose:
* Check if the system is running provided firmware
* Parameters:
* fw_str - (IN) firmware string
* Returns:
* BCM_E_XXX;
* Notes:
* Function tells whether the provided firmware
* is running on the system, return unavail if not
*/
int
_bcm_ptp_check_firmware_exist (char* fw_str)
{
int uc;
char *version = NULL;
int firmware = 0;
int unit = 0;
for(uc=0; uc<SOC_INFO(unit).num_ucs; uc++) {
if (!soc_uc_in_reset(unit, uc)) {
version = soc_uc_firmware_version(unit, uc);
if (version) {
#ifdef NO_SAL_APPL
if (strstr((char *)version,(char *)fw_str)) {
#else
if (sal_strcasestr((char *)version,(char *)fw_str)) {
#endif
firmware = 1;
}
soc_cm_sfree(unit, version);
if (1 == firmware) {
break;
}
}
}
}
if (firmware == 0) {
return BCM_E_UNAVAIL;
}
return BCM_E_NONE;
}
#endif /* BCM_PTP_INTERNAL_STACK_SUPPORT */
#endif /* defined(INCLUDE_PTP)*/
|
the_stack_data/12638970.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct var_s {
int x[5];
} var_t;
void print_arr(int *arr, int len);
int main() {
int len = 5;
int i[5] = {1, 2, 3, 4, 5};
var_t *var = (var_t *) malloc(sizeof (var_t));
memcpy(var->x, i, sizeof (var_t));
print_arr(var->x, len);
free(var);
return 0;
}
void print_arr(int *arr, int len) {
for (int i = 0; i < len; i++) {
printf("arr[%d] = %d \n", i, arr[i]);
}
}
|
the_stack_data/153879.c | /*
- Welcome to the program!.
- The program was designed to save information about books,
- such as its owner, publication date and house, its topic etc.
- Every single book will have its own .text file that contains these informations.
- I hope you find that useful.
- That program was created using C language with Microsoft Visual Studio 2017.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct library {
char title[50];
char tutor[20];
char subject[100];
int PageNumber;
char PublicationDate[8];
char PublicationHouse[100];
};
int main() {
printf("%s", "Welcome to the Library with C\n\n");
printf("%s", "That program creates .text files,\n");
printf("%s", "that contains its owner of book, publication date, number of pages,\n");
printf("%s", "for every single book entered to program.\n\n");
choose: printf("%s", "Do you wish to add a new book to library, or search for?\nPlease choose below according to your wishes:\n");
printf("%s", "1- Add a new book\n");
printf("%s", "2- Search a book\n");
int user_choice = 0;
scanf_s("%d", &user_choice);
struct library book;
char BookName[50];
char BookWriter[20];
char BookTopic[100];
char BookPublicationDate[9];
char BookPublicationHouse[100];
int BookPageNumber;
char Storage[] = "TotalAmountOfBook";
if (user_choice == 1) {
printf("%s", "Please, enter the following information about the book to save it.\n");
printf("%s", "Book Name: ");
scanf_s("%49s", BookName, (unsigned)_countof(BookName));
printf("%s", "Tutor Name: ");
scanf_s("%19s", BookWriter, (unsigned)_countof(BookWriter));
printf("%s", "Subject: ");
scanf_s("%99s", BookTopic, (unsigned)_countof(BookTopic));
printf("%s", "Book Page: ");
scanf_s("%d", &BookPageNumber);
printf("%s", "Book' Publication Date: ");
scanf_s("%8s", BookPublicationDate, (unsigned)_countof(BookPublicationDate));
printf("%s", "Book' Publication House: ");
scanf_s("%99s", BookPublicationHouse, (unsigned)_countof(BookPublicationHouse));
strcpy_s(book.title, sizeof book.title, BookName);
strcpy_s(book.tutor, sizeof book.tutor, BookWriter);
strcpy_s(book.subject, sizeof book.subject, BookTopic);
book.PageNumber = BookPageNumber;
strcpy_s(book.PublicationDate, sizeof book.PublicationDate, BookPublicationDate);
strcpy_s(book.PublicationHouse, sizeof book.PublicationHouse, BookPublicationHouse);
FILE *AddBook;
fopen_s(&AddBook, book.title, "w+");
fprintf(AddBook, "%s %s %d %s %s", &book.tutor[0], &book.subject[0], book.PageNumber, &book.PublicationDate[0], &book.PublicationHouse[0]);
fclose(AddBook);
FILE *SaveBook;
fopen_s(&SaveBook, Storage, "a");
fprintf_s(SaveBook, "*");
fclose(SaveBook);
FILE *CountBook;
char c;
int BookCounter = 0;
fopen_s(&CountBook, Storage, "r");
for ( c=getc(CountBook) ; c != EOF ; c = getc(CountBook) )
{
BookCounter++;
}
fclose(CountBook);
printf_s("Total Number of Book in Library = %d", BookCounter);
}
else if (user_choice == 2) {
choose_2: printf("%s", "Type Book Name: ");
scanf_s("%49s", BookName, (unsigned)_countof(BookName));
FILE *SearchBook;
int FileOperationResult = 0;
FileOperationResult = fopen_s(&SearchBook, BookName, "r");
if (!FileOperationResult) {
fscanf_s(SearchBook, "%19s", BookWriter, (unsigned)_countof(BookWriter));
fscanf_s(SearchBook, "%99s", BookTopic, (unsigned)_countof(BookTopic));
fscanf_s(SearchBook, "%d", &BookPageNumber);
fscanf_s(SearchBook, "%8s", BookPublicationDate, (unsigned)_countof(BookPublicationDate));
fscanf_s(SearchBook, "%99s", BookPublicationHouse, (unsigned)_countof(BookPublicationHouse));
fclose(SearchBook);
printf("\n\nBook Name: %s\n", BookName);
printf("Book Writer: %s\n", BookWriter);
printf("Book Topic: %s\n", BookTopic);
printf("Book Page Number: %d\n", BookPageNumber);
printf("Book Publication Date: %s\n", BookPublicationDate);
printf("Book Publication House: %s\n", BookPublicationHouse);
}
else
printf_s("%s", "Something has gone wrong!\n");
exit(0);
}
else {
printf("%s", "Please press only 0 or 1.. Try again!\n");
goto choose;
}
/*
printf("\n\n\n%s is the name of book.\n\n", BookName);
printf("%s is the tutor of book.\n\n", BookWriter);
printf("%s is the topic of book.\n\n", BookTopic);
printf("%d is the page of book.\n\n", BookPageNumber);
printf("%s is the publication date of book.\n\n", BookPublicationDate);
printf("%s is the publication house of book.\n\n", BookPublicationHouse);
printf("\n\n%s is title.\n", book.title);
printf("%s is tutor.\n", book.tutor);
printf("%s is subject.\n", book.subject);
printf("%d is total page.\n", book.PageNumber);
printf("%s is publication date.\n", book.PublicationDate);
printf("%s is publication house.\n", book.PublicationHouse);
*/
return 0;
} |
the_stack_data/34513079.c | /*
Autor: Abel Hernández
fecha: Wed May 11 10:31:37 CST 2022
compilador: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
compilar: gcc -o Problema2.out Problema2.c
Librerias: stdio, stdlib
resumen: Este programa solicita al usuario ingresar cinco valores enteros
una vez ingresados los almacena y luego los ordena en forma ascendente
*/
//librerias
#include <stdio.h>
#include <stdlib.h>
//Se inicializa la función principal
int main ()
{
//Se declaran las variables
// Inicializar el vector en el cual se almacenaran cinco valores
int n=5;
int numero[n];
int i;
printf("Ingrese cinco números enteros a guardar\n");
for (int i = 0; i < 5; i++)
{
//Se leen y muestran los valores ingresados al vector
printf("No: ");
scanf("%d", &numero[i]);
}
//Se coloca una etiqueta para que el usuario tenga conocimiento del proceso
//que se ejecutó, se usa el ordenamiento por burbuja
puts("\nOrdenando el valor del vector");
//Se declaran las variables
//El interruptor hace un parar acá cuando está en 1 = verdadero
int interruptor = 1;
//Variable de pasada de cada iteracción
int pasada, j;
//Bucle que controla la cantidad de pasadas en el vector
//Si pasada es menro que n-1 y tambien el interruptor sea verdadero
for (pasada = 0; pasada < n-1 && interruptor; pasada++)
{
//Se coloca igual a cero para que las pasadas sean primero por el vector escaneado
interruptor = 0;
//Escanea todas la variables j que corresponden a una posición i en el vector
//que maneja el paso por el vector, n menos la pasada menos 1 porque el método de
//burbujas así lo establece >>>> El for maneja el paso por el vector
for (j = 0; j < n-pasada-1; j++)
{
//validando que el valor seleccionado sea mayor al siguiente hasta terminar de pasar
//por todo el vector
if (numero[j] > numero[j+1])
{
//Se declara una variable local llamada auxiliar porque cuando se hace el cambio el valor se
//pierde y necesitamos guardar el valor anterior de manera momentanea
int aux;
//Imprime los primeros cambios, el valor del vector a en la posición j a la
//posición del vector a j+1
printf("cambio %d %d a ",numero[j],numero[j+1]);
//En la variable auxiliar se almacena la posición del vector j en la
//que se está actualmente
aux = numero[j];
//Ahora el valor del vector número que tiene la posición j se convierte en la posicón j+1
numero[j] = numero[j+1];
//La posición de j+1 pasa a ser ahora la posición de la variable auxiliar
numero[j+1] = aux;
//Se imprime las nuevas posiciones de los valores del vector
printf("%d %d \n", numero[j], numero[j+1]);
}
//El interruptor se pasa a 1 es decir verdadero, significa que lo anterior se
//valido y así vuelva a hacer la siguiente pasada.
interruptor = 1;
}
}
//Mostramos en pantalla los valores del vector ordenado en forma ascendente
puts("\nVector Ordenado en forma ascendente");
//Se muestra nuevamente los valores del vector
for (int i = 0; i < n; i++)
{
//Imprime el valor del vector ya ordenado en forma ascendente
printf("%d ", numero[i]);
}
//Fin del programa
puts("\n*************************************");
puts("Gracias por participar");
puts("*************************************\n");
} |
the_stack_data/32402.c | #include <yaml.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef NDEBUG
#undef NDEBUG
#endif
#include <assert.h>
int
main(int argc, char *argv[])
{
int number;
if (argc < 2) {
printf("Usage: %s file1.yaml ...\n", argv[0]);
return 0;
}
for (number = 1; number < argc; number ++)
{
FILE *file;
yaml_parser_t parser;
yaml_document_t document;
int done = 0;
int count = 0;
int error = 0;
printf("[%d] Loading '%s': ", number, argv[number]);
fflush(stdout);
file = fopen(argv[number], "rb");
assert(file);
assert(yaml_parser_initialize(&parser));
yaml_parser_set_input_file(&parser, file);
while (!done)
{
if (!yaml_parser_load(&parser, &document)) {
error = 1;
break;
}
done = (!yaml_document_get_root_node(&document));
yaml_document_delete(&document);
if (!done) count ++;
}
yaml_parser_delete(&parser);
assert(!fclose(file));
printf("%s (%d documents)\n", (error ? "FAILURE" : "SUCCESS"), count);
}
return 0;
}
|
the_stack_data/192330093.c | // RUN: %clang_cc1 -fsyntax-only -fopenmp=libiomp5 -verify %s
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp for'}}
#pragma omp for
// expected-error@+1 {{unexpected OpenMP directive '#pragma omp for'}}
#pragma omp for foo
void test_no_clause() {
int i;
#pragma omp for
for (i = 0; i < 16; ++i)
;
// expected-error@+2 {{statement after '#pragma omp for' must be a for loop}}
#pragma omp for
++i;
}
void test_branch_protected_scope() {
int i = 0;
L1:
++i;
int x[24];
#pragma omp parallel
#pragma omp for
for (i = 0; i < 16; ++i) {
if (i == 5)
goto L1; // expected-error {{use of undeclared label 'L1'}}
else if (i == 6)
return; // expected-error {{cannot return from OpenMP region}}
else if (i == 7)
goto L2;
else if (i == 8) {
L2:
x[i]++;
}
}
if (x[0] == 0)
goto L2; // expected-error {{use of undeclared label 'L2'}}
else if (x[1] == 1)
goto L1;
}
void test_invalid_clause() {
int i;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for foo bar
for (i = 0; i < 16; ++i)
;
}
void test_non_identifiers() {
int i, x;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for;
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{unexpected OpenMP clause 'linear' in directive '#pragma omp for'}}
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for linear(x);
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for private(x);
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+1 {{extra tokens at the end of '#pragma omp for' are ignored}}
#pragma omp for, private(x);
for (i = 0; i < 16; ++i)
;
}
extern int foo();
void test_collapse() {
int i;
#pragma omp parallel
// expected-error@+1 {{expected '('}}
#pragma omp for collapse
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for collapse(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for collapse()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for collapse(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for collapse(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-warning@+2 {{extra tokens at the end of '#pragma omp for' are ignored}}
// expected-error@+1 {{expected '('}}
#pragma omp for collapse 4)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4,
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4, )
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4, , 4)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
#pragma omp for collapse(4)
for (int i1 = 0; i1 < 16; ++i1)
for (int i2 = 0; i2 < 16; ++i2)
for (int i3 = 0; i3 < 16; ++i3)
for (int i4 = 0; i4 < 16; ++i4)
foo();
#pragma omp parallel
// expected-error@+2 {{expected ')'}}
// expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}}
#pragma omp for collapse(4, 8)
for (i = 0; i < 16; ++i)
; // expected-error {{expected 4 for loops after '#pragma omp for', but found only 1}}
#pragma omp parallel
// expected-error@+1 {{expression is not an integer constant expression}}
#pragma omp for collapse(2.5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expression is not an integer constant expression}}
#pragma omp for collapse(foo())
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp for collapse(-5)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp for collapse(0)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{argument to 'collapse' clause must be a positive integer value}}
#pragma omp for collapse(5 - 5)
for (i = 0; i < 16; ++i)
;
}
void test_private() {
int i;
#pragma omp parallel
// expected-error@+2 {{expected expression}}
// expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}}
#pragma omp for private(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp for private(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp for private(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for private()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for private(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp for private(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp for private(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for private(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for private(x, y, z)
for (i = 0; i < 16; ++i) {
x = y * i + z;
}
}
void test_lastprivate() {
int i;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp for lastprivate(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp for lastprivate(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp for lastprivate(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for lastprivate()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for lastprivate(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp for lastprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp for lastprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_firstprivate() {
int i;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 {{expected expression}}
#pragma omp for firstprivate(
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}}
// expected-error@+1 2 {{expected expression}}
#pragma omp for firstprivate(,
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 2 {{expected expression}}
#pragma omp for firstprivate(, )
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for firstprivate()
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected expression}}
#pragma omp for firstprivate(int)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
// expected-error@+1 {{expected variable name}}
#pragma omp for firstprivate(0)
for (i = 0; i < 16; ++i)
;
int x, y, z;
#pragma omp parallel
#pragma omp for lastprivate(x) firstprivate(x)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y) firstprivate(x, y)
for (i = 0; i < 16; ++i)
;
#pragma omp parallel
#pragma omp for lastprivate(x, y, z) firstprivate(x, y, z)
for (i = 0; i < 16; ++i)
;
}
void test_loop_messages() {
float a[100], b[100], c[100];
#pragma omp parallel
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp for
for (float fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
#pragma omp parallel
// expected-error@+2 {{variable must be of integer or pointer type}}
#pragma omp for
for (double fi = 0; fi < 10.0; fi++) {
c[(int)fi] = a[(int)fi] + b[(int)fi];
}
}
|
the_stack_data/15344.c | /* -*- mode: c; c-basic-offset: 8; -*-
* vim: noexpandtab sw=8 ts=8 sts=0:
*
* netdebug.c
*
* debug functionality for o2net
*
* Copyright (C) 2005, 2008 Oracle. All rights reserved.
*
* 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 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
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 021110-1307, USA.
*
*/
#ifdef CONFIG_DEBUG_FS
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/idr.h>
#include <linux/kref.h>
#include <linux/seq_file.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include "tcp.h"
#include "nodemanager.h"
#define MLOG_MASK_PREFIX ML_TCP
#include "masklog.h"
#include "tcp_internal.h"
#define O2NET_DEBUG_DIR "o2net"
#define SC_DEBUG_NAME "sock_containers"
#define NST_DEBUG_NAME "send_tracking"
static struct dentry *o2net_dentry;
static struct dentry *sc_dentry;
static struct dentry *nst_dentry;
static DEFINE_SPINLOCK(o2net_debug_lock);
static LIST_HEAD(sock_containers);
static LIST_HEAD(send_tracking);
void o2net_debug_add_nst(struct o2net_send_tracking *nst)
{
spin_lock(&o2net_debug_lock);
list_add(&nst->st_net_debug_item, &send_tracking);
spin_unlock(&o2net_debug_lock);
}
void o2net_debug_del_nst(struct o2net_send_tracking *nst)
{
spin_lock(&o2net_debug_lock);
if (!list_empty(&nst->st_net_debug_item))
list_del_init(&nst->st_net_debug_item);
spin_unlock(&o2net_debug_lock);
}
static struct o2net_send_tracking
*next_nst(struct o2net_send_tracking *nst_start)
{
struct o2net_send_tracking *nst, *ret = NULL;
assert_spin_locked(&o2net_debug_lock);
list_for_each_entry(nst, &nst_start->st_net_debug_item,
st_net_debug_item) {
/* discover the head of the list */
if (&nst->st_net_debug_item == &send_tracking)
break;
/* use st_task to detect real nsts in the list */
if (nst->st_task != NULL) {
ret = nst;
break;
}
}
return ret;
}
static void *nst_seq_start(struct seq_file *seq, loff_t *pos)
{
struct o2net_send_tracking *nst, *dummy_nst = seq->private;
spin_lock(&o2net_debug_lock);
nst = next_nst(dummy_nst);
spin_unlock(&o2net_debug_lock);
return nst;
}
static void *nst_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct o2net_send_tracking *nst, *dummy_nst = seq->private;
spin_lock(&o2net_debug_lock);
nst = next_nst(dummy_nst);
list_del_init(&dummy_nst->st_net_debug_item);
if (nst)
list_add(&dummy_nst->st_net_debug_item,
&nst->st_net_debug_item);
spin_unlock(&o2net_debug_lock);
return nst; /* unused, just needs to be null when done */
}
static int nst_seq_show(struct seq_file *seq, void *v)
{
struct o2net_send_tracking *nst, *dummy_nst = seq->private;
spin_lock(&o2net_debug_lock);
nst = next_nst(dummy_nst);
if (nst != NULL) {
/* get_task_comm isn't exported. oh well. */
seq_printf(seq, "%p:\n"
" pid: %lu\n"
" tgid: %lu\n"
" process name: %s\n"
" node: %u\n"
" sc: %p\n"
" message id: %d\n"
" message type: %u\n"
" message key: 0x%08x\n"
" sock acquiry: %lu.%ld\n"
" send start: %lu.%ld\n"
" wait start: %lu.%ld\n",
nst, (unsigned long)nst->st_task->pid,
(unsigned long)nst->st_task->tgid,
nst->st_task->comm, nst->st_node,
nst->st_sc, nst->st_id, nst->st_msg_type,
nst->st_msg_key,
nst->st_sock_time.tv_sec,
(long)nst->st_sock_time.tv_usec,
nst->st_send_time.tv_sec,
(long)nst->st_send_time.tv_usec,
nst->st_status_time.tv_sec,
(long)nst->st_status_time.tv_usec);
}
spin_unlock(&o2net_debug_lock);
return 0;
}
static void nst_seq_stop(struct seq_file *seq, void *v)
{
}
static const struct seq_operations nst_seq_ops = {
.start = nst_seq_start,
.next = nst_seq_next,
.stop = nst_seq_stop,
.show = nst_seq_show,
};
static int nst_fop_open(struct inode *inode, struct file *file)
{
struct o2net_send_tracking *dummy_nst;
struct seq_file *seq;
int ret;
dummy_nst = kmalloc(sizeof(struct o2net_send_tracking), GFP_KERNEL);
if (dummy_nst == NULL) {
ret = -ENOMEM;
goto out;
}
dummy_nst->st_task = NULL;
ret = seq_open(file, &nst_seq_ops);
if (ret)
goto out;
seq = file->private_data;
seq->private = dummy_nst;
o2net_debug_add_nst(dummy_nst);
dummy_nst = NULL;
out:
kfree(dummy_nst);
return ret;
}
static int nst_fop_release(struct inode *inode, struct file *file)
{
struct seq_file *seq = file->private_data;
struct o2net_send_tracking *dummy_nst = seq->private;
o2net_debug_del_nst(dummy_nst);
return seq_release_private(inode, file);
}
static const struct file_operations nst_seq_fops = {
.open = nst_fop_open,
.read = seq_read,
.llseek = seq_lseek,
.release = nst_fop_release,
};
void o2net_debug_add_sc(struct o2net_sock_container *sc)
{
spin_lock(&o2net_debug_lock);
list_add(&sc->sc_net_debug_item, &sock_containers);
spin_unlock(&o2net_debug_lock);
}
void o2net_debug_del_sc(struct o2net_sock_container *sc)
{
spin_lock(&o2net_debug_lock);
list_del_init(&sc->sc_net_debug_item);
spin_unlock(&o2net_debug_lock);
}
static struct o2net_sock_container
*next_sc(struct o2net_sock_container *sc_start)
{
struct o2net_sock_container *sc, *ret = NULL;
assert_spin_locked(&o2net_debug_lock);
list_for_each_entry(sc, &sc_start->sc_net_debug_item,
sc_net_debug_item) {
/* discover the head of the list miscast as a sc */
if (&sc->sc_net_debug_item == &sock_containers)
break;
/* use sc_page to detect real scs in the list */
if (sc->sc_page != NULL) {
ret = sc;
break;
}
}
return ret;
}
static void *sc_seq_start(struct seq_file *seq, loff_t *pos)
{
struct o2net_sock_container *sc, *dummy_sc = seq->private;
spin_lock(&o2net_debug_lock);
sc = next_sc(dummy_sc);
spin_unlock(&o2net_debug_lock);
return sc;
}
static void *sc_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct o2net_sock_container *sc, *dummy_sc = seq->private;
spin_lock(&o2net_debug_lock);
sc = next_sc(dummy_sc);
list_del_init(&dummy_sc->sc_net_debug_item);
if (sc)
list_add(&dummy_sc->sc_net_debug_item, &sc->sc_net_debug_item);
spin_unlock(&o2net_debug_lock);
return sc; /* unused, just needs to be null when done */
}
#define TV_SEC_USEC(TV) TV.tv_sec, (long)TV.tv_usec
static int sc_seq_show(struct seq_file *seq, void *v)
{
struct o2net_sock_container *sc, *dummy_sc = seq->private;
spin_lock(&o2net_debug_lock);
sc = next_sc(dummy_sc);
if (sc != NULL) {
struct inet_sock *inet = NULL;
__be32 saddr = 0, daddr = 0;
__be16 sport = 0, dport = 0;
if (sc->sc_sock) {
inet = inet_sk(sc->sc_sock->sk);
/* the stack's structs aren't sparse endian clean */
saddr = (__force __be32)inet->inet_saddr;
daddr = (__force __be32)inet->inet_daddr;
sport = (__force __be16)inet->inet_sport;
dport = (__force __be16)inet->inet_dport;
}
/* XXX sigh, inet-> doesn't have sparse annotation so any
* use of it here generates a warning with -Wbitwise */
seq_printf(seq, "%p:\n"
" krefs: %d\n"
" sock: %pI4:%u -> "
"%pI4:%u\n"
" remote node: %s\n"
" page off: %zu\n"
" handshake ok: %u\n"
" timer: %lu.%ld\n"
" data ready: %lu.%ld\n"
" advance start: %lu.%ld\n"
" advance stop: %lu.%ld\n"
" func start: %lu.%ld\n"
" func stop: %lu.%ld\n"
" func key: %u\n"
" func type: %u\n",
sc,
atomic_read(&sc->sc_kref.refcount),
&saddr, inet ? ntohs(sport) : 0,
&daddr, inet ? ntohs(dport) : 0,
sc->sc_node->nd_name,
sc->sc_page_off,
sc->sc_handshake_ok,
TV_SEC_USEC(sc->sc_tv_timer),
TV_SEC_USEC(sc->sc_tv_data_ready),
TV_SEC_USEC(sc->sc_tv_advance_start),
TV_SEC_USEC(sc->sc_tv_advance_stop),
TV_SEC_USEC(sc->sc_tv_func_start),
TV_SEC_USEC(sc->sc_tv_func_stop),
sc->sc_msg_key,
sc->sc_msg_type);
}
spin_unlock(&o2net_debug_lock);
return 0;
}
static void sc_seq_stop(struct seq_file *seq, void *v)
{
}
static const struct seq_operations sc_seq_ops = {
.start = sc_seq_start,
.next = sc_seq_next,
.stop = sc_seq_stop,
.show = sc_seq_show,
};
static int sc_fop_open(struct inode *inode, struct file *file)
{
struct o2net_sock_container *dummy_sc;
struct seq_file *seq;
int ret;
dummy_sc = kmalloc(sizeof(struct o2net_sock_container), GFP_KERNEL);
if (dummy_sc == NULL) {
ret = -ENOMEM;
goto out;
}
dummy_sc->sc_page = NULL;
ret = seq_open(file, &sc_seq_ops);
if (ret)
goto out;
seq = file->private_data;
seq->private = dummy_sc;
o2net_debug_add_sc(dummy_sc);
dummy_sc = NULL;
out:
kfree(dummy_sc);
return ret;
}
static int sc_fop_release(struct inode *inode, struct file *file)
{
struct seq_file *seq = file->private_data;
struct o2net_sock_container *dummy_sc = seq->private;
o2net_debug_del_sc(dummy_sc);
return seq_release_private(inode, file);
}
static const struct file_operations sc_seq_fops = {
.open = sc_fop_open,
.read = seq_read,
.llseek = seq_lseek,
.release = sc_fop_release,
};
int o2net_debugfs_init(void)
{
o2net_dentry = debugfs_create_dir(O2NET_DEBUG_DIR, NULL);
if (!o2net_dentry) {
mlog_errno(-ENOMEM);
goto bail;
}
nst_dentry = debugfs_create_file(NST_DEBUG_NAME, S_IFREG|S_IRUSR,
o2net_dentry, NULL,
&nst_seq_fops);
if (!nst_dentry) {
mlog_errno(-ENOMEM);
goto bail;
}
sc_dentry = debugfs_create_file(SC_DEBUG_NAME, S_IFREG|S_IRUSR,
o2net_dentry, NULL,
&sc_seq_fops);
if (!sc_dentry) {
mlog_errno(-ENOMEM);
goto bail;
}
return 0;
bail:
if (sc_dentry)
debugfs_remove(sc_dentry);
if (nst_dentry)
debugfs_remove(nst_dentry);
if (o2net_dentry)
debugfs_remove(o2net_dentry);
return -ENOMEM;
}
void o2net_debugfs_exit(void)
{
if (sc_dentry)
debugfs_remove(sc_dentry);
if (nst_dentry)
debugfs_remove(nst_dentry);
if (o2net_dentry)
debugfs_remove(o2net_dentry);
}
#endif /* CONFIG_DEBUG_FS */
|
the_stack_data/75137403.c | #include <stdio.h>
void main(void){
printf("%d\n", sizeof(int));
printf("%d\n", sizeof(char));
printf("%d\n", sizeof(float));
} |
the_stack_data/273394.c |
#include <stdio.h>
void scilab_rt_plot3d_i2i2d2d0d0s0i2i2_(int in00, int in01, int matrixin0[in00][in01],
int in10, int in11, int matrixin1[in10][in11],
int in20, int in21, double matrixin2[in20][in21],
double scalarin0,
double scalarin1,
char* scalarin2,
int in30, int in31, int matrixin3[in30][in31],
int in40, int in41, int matrixin4[in40][in41])
{
int i;
int j;
int val0 = 0;
int val1 = 0;
double val2 = 0;
int val3 = 0;
int val4 = 0;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
val0 += matrixin0[i][j];
}
}
printf("%d", val0);
for (i = 0; i < in10; ++i) {
for (j = 0; j < in11; ++j) {
val1 += matrixin1[i][j];
}
}
printf("%d", val1);
for (i = 0; i < in20; ++i) {
for (j = 0; j < in21; ++j) {
val2 += matrixin2[i][j];
}
}
printf("%f", val2);
printf("%f", scalarin0);
printf("%f", scalarin1);
printf("%s", scalarin2);
for (i = 0; i < in30; ++i) {
for (j = 0; j < in31; ++j) {
val3 += matrixin3[i][j];
}
}
printf("%d", val3);
for (i = 0; i < in40; ++i) {
for (j = 0; j < in41; ++j) {
val4 += matrixin4[i][j];
}
}
printf("%d", val4);
}
|
the_stack_data/103266687.c | // This file is part of the SV-Benchmarks collection of verification tasks:
// https://github.com/sosy-lab/sv-benchmarks
//
// SPDX-FileCopyrightText: 2011-2020 The SV-Benchmarks community
// SPDX-FileCopyrightText: The ESBMC project
//
// SPDX-License-Identifier: Apache-2.0
extern int __VERIFIER_nondet_int(void);
extern void abort(void);
#include <assert.h>
void reach_error() { assert(0); }
#include <pthread.h>
#include <stdio.h>
#include <assert.h>
#define SIZE (400)
#define EMPTY (-1)
#define FULL (-2)
#define FALSE (0)
#define TRUE (1)
typedef struct {
int element[SIZE];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[SIZE];
_Bool enqueue_flag, dequeue_flag;
QType queue;
void init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\n");
return EMPTY;
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == SIZE)
{
printf("queue is full\n");
return FULL;
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == SIZE)
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == SIZE)
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(i=0; i<(SIZE-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=FALSE;
dequeue_flag=TRUE;
}
pthread_mutex_unlock(&m);
}
return NULL;
ERROR:{reach_error();abort();}
}
void *t2(void *arg)
{
int i;
for(i=0; i<SIZE; i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:{reach_error();abort();}
}
dequeue_flag=FALSE;
enqueue_flag=TRUE;
}
pthread_mutex_unlock(&m);
}
return NULL;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=TRUE;
dequeue_flag=FALSE;
init(&queue);
if (!empty(&queue)==EMPTY) {
ERROR:{reach_error();abort();}
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, NULL, t1, &queue);
pthread_create(&id2, NULL, t2, &queue);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
return 0;
}
|
the_stack_data/12637966.c | #define FOO
#define BAR
void fn_1() FOO BAR {}
void *fn_2() FOO BAR { return 0; }
void fn_3() {}
void *fn_4() { return 0; }
void **fn_5() { return 0; }
typedef enum {
kVal,
} kEnum;
typedef struct {
int field;
} St_1;
|
the_stack_data/26699480.c | // BUILD: $CC dylib.c -dynamiclib -o $BUILD_DIR/signed.dylib
// BUILD: $CC dylib.c -dynamiclib -o $BUILD_DIR/unsigned.dylib
// BUILD: $CC main.c -o $BUILD_DIR/dlopen-signed.exe
// BUILD: $CC main.c -o $BUILD_DIR/dlopen-unsigned.exe
// FIXME: add builds that sign the executable and the dylib in in various ways
// At this time we don't have a way to do that, so this test must be run
// manually.
#include <stdio.h>
#include <dlfcn.h>
int main() {
printf("[BEGIN] dlopen-signing\n");
void* handle = dlopen("signed.dylib", RTLD_LAZY);
if ( handle == NULL ) {
printf("dlerror(): %s\n", dlerror());
printf("[FAIL] dlopen-signing (signed loading signed)\n");
return 0;
} else {
int result = dlclose(handle);
if ( result != 0 ) {
printf("dlclose() returned %c\n", result);
printf("[FAIL] dlopen-signing (signed unloading signed)\n");
return 0;
}
}
handle = dlopen("unsigned.dylib", RTLD_LAZY);
if ( handle != NULL ) {
printf("dlerror(): %s\n", dlerror());
printf("[FAIL] dlopen-signing (signed loading unsigned)\n");
return 0;
} else {
int result = dlclose(handle);
if ( result != 0 ) {
printf("dlclose() returned %c\n", result);
printf("[FAIL] dlopen-signing (signed unloading signed)\n");
return 0;
}
}
printf("[PASS] dlopen-signing\n");
return 0;
}
|
the_stack_data/75138415.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_iterative_factorial.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rodaniel <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/08/06 15:32:33 by rodaniel #+# #+# */
/* Updated: 2017/08/06 15:32:41 by rodaniel ### ########.fr */
/* */
/* ************************************************************************** */
int ft_iterative_factorial(int nb)
{
long i;
i = nb;
if (nb <= 0 || nb >= 13)
return ((nb == 0) ? 1 : 0);
nb--;
while (nb > 0)
{
i = nb * i;
nb--;
}
return (i);
}
|
the_stack_data/72910.c | #include <CL/cl.h>
int main()
{
return sizeof(cl_platform_id) - sizeof(cl_context);
}
|
the_stack_data/200143172.c | #include <stdio.h>
int mod(int number2, int m2)
{
int result = number2 - number2 / m2 * m2;
int result2 = result;
return result;
}
int power(int base1, int p1) {
int ret1 = 1 + p1 - p1;
while(p1 > (ret1 - ret1 + 90 - 89 + 1 - 2))
{
ret1 = ret1 * base1;
p1 = 2 * 1 * p1 - 1 * p1 - 1;
}
return ret1;
}
int getNumDigits(int number3)
{
int ret3 = 0;
if(number3 < 0)
return -1;
while(number3 > 0) {
number3 = number3 / 10;
ret3 = ret3 + 2;
ret3 = ret3 + 2;
ret3 = ret3 - 3;
}
return ret3;
}
int isNarcissistic(int number4)
{
int numDigits4 = getNumDigits(1 + number4 - 1);
int sum4 = 0;
int n4 = number4;
int s4;
while(n4>0) {
s4 = mod(n4, 10);
n4 = (n4 - s4) / 10;
sum4 = sum4 + power(s4, numDigits4);
}
if(sum4 == number4)
return 1;
else
return 0;
}
int main() {
int count = 0;
int i = 300;
while(i < 500)
{
if(isNarcissistic(i) == 1)
{
printf("%d\n", i);
count = count + 1;
}
i = i + 1;
}
printf("%d\n", count);
return count;
}
|
the_stack_data/98576457.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <stdint.h>
typedef unsigned char uchar;
static void die(const char *msg);
static void read_hex(const char *hex, uchar *out, size_t outmax, size_t *outlen);
static void build_iv(uchar *iv, uint64_t seq);
const int gcm_ivlen = 12;
const int gcm_taglen = 16;
const int aes_keylen = 32; // aes-256
int main(int argc, char **argv)
{
if (argc != 5) {
fprintf(stderr, "Usage: %s hexiv seq hexkey hexaad\n", argv[0]);
fprintf(stderr, "\n");
fprintf(stderr, "Reads plaintext on stdin and prints ciphertext and tag on stdout\n");
exit(1);
}
uchar iv[1024], key[1024], aad[1024];
size_t ivlen, keylen, aadlen;
read_hex(argv[1], iv, sizeof(iv), &ivlen);
uint64_t seq = atoi(argv[2]);
read_hex(argv[3], key, sizeof(key), &keylen);
read_hex(argv[4], aad, sizeof(aad), &aadlen);
if (keylen != aes_keylen)
die("Incorrect key length, expected 32 bytes");
if (ivlen != gcm_ivlen)
die("Incorrect IV length, expected 12 bytes");
build_iv(iv, seq);
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx)
die("cipher ctx create failed");
if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
die("init algorithm failed");
if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, ivlen, NULL))
die("set ivlen failed");
if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
die("set key/iv failed");
int len = 0;
if (!EVP_EncryptUpdate(ctx, NULL, &len, aad, aadlen))
die("set aad failed");
uchar bufin[512], bufout[1024];
while (!feof(stdin)) {
size_t num = fread(bufin, 1, sizeof(bufin), stdin);
if (!EVP_EncryptUpdate(ctx, bufout, &len, bufin, num))
die("decrypt failed");
fwrite(bufout, 1, len, stdout);
}
EVP_EncryptFinal_ex(ctx, bufout, &len);
fwrite(bufout, 1, len, stdout);
if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, gcm_taglen, bufout))
die("generate tag failed");
fwrite(bufout, 1, gcm_taglen, stdout);
EVP_CIPHER_CTX_free(ctx);
}
static void die(const char *msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}
static void read_hex(const char *hex, uchar *out, size_t outmax, size_t *outlen)
{
*outlen = 0;
if (strlen(hex) > 2*outmax)
die("read_hex overflow");
size_t i;
for (i = 0; hex[i] && hex[i+1]; i += 2) {
unsigned int value = 0;
if (!sscanf(hex + i, "%02x", &value))
die("sscanf failure");
out[(*outlen)++] = value;
}
}
static void build_iv(uchar *iv, uint64_t seq)
{
size_t i;
for (i = 0; i < 8; i++) {
iv[gcm_ivlen-1-i] ^= ((seq>>(i*8))&0xFF);
}
}
|
the_stack_data/181393254.c | #include <assert.h>
extern int z;
int f(int x) {
assert(x < 10000);
if(x > 10) {
z += x;
return 10;
}
return -79;
}
|
the_stack_data/92329303.c | #include <stdio.h>
#include <stdlib.h>
void binary()
{
int x;
int bin [8];
int num = x;
for (x = 7; x >= 0; x--)
{
if (num % 2 == 0)
bin[x] = 0;
else
bin[x] = 1;
num = num / 2;
}
for (x = 0; x < 8; x++)
printf("%d", bin[x]);
}
int main()
{
int x;
printf("Digite o número (base decimal) para ser convertido: ");
scanf("%d", &x);
binary();
printf("\n");
return 0;
}
|
the_stack_data/37637589.c | #include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *thread(void *arg)
{
int *num = (int *)arg;
printf("%d wants to enter the critical section\n", *num);
printf("%d is finished with the critical section\n", *num);
return NULL;
}
int
main(int argc, char **argv)
{
pthread_t threads[4];
int i;
int nums[] = {2, 1, 4, 3};
for(i = 0; i < 4; ++i) {
pthread_create(&threads[i], NULL, thread, &nums[i]);
if(i == 2)
sleep(3);
}
for(i = 0; i < 4; ++i) {
pthread_join(threads[i], NULL);
}
printf("Everything finished\n");
return 0;
} |
the_stack_data/911706.c | #include <stdio.h>
int cube(int *a)
{
return *a * *a * *a;
}
int main()
{
int a;
printf("Enter Two Value:- ");
scanf("%d", &a);
printf("The Cube is - %d", cube(&a));
return 0;
} |
the_stack_data/22558.c | extern float __VERIFIER_nondet_float(void);
extern int __VERIFIER_nondet_int(void);
typedef enum {false, true} bool;
bool __VERIFIER_nondet_bool(void) {
return __VERIFIER_nondet_int() != 0;
}
int main()
{
float x_10, _x_x_10;
bool _J2421, _x__J2421;
bool _J2411, _x__J2411;
bool _EL_X_2395, _x__EL_X_2395;
float x_14, _x_x_14;
float x_4, _x_x_4;
float x_3, _x_x_3;
float x_22, _x_x_22;
float x_8, _x_x_8;
float x_23, _x_x_23;
float x_9, _x_x_9;
float x_24, _x_x_24;
float x_11, _x_x_11;
float x_26, _x_x_26;
float x_12, _x_x_12;
float x_13, _x_x_13;
float x_15, _x_x_15;
bool _EL_U_2394, _x__EL_U_2394;
float x_16, _x_x_16;
bool _EL_U_2392, _x__EL_U_2392;
float x_18, _x_x_18;
float x_19, _x_x_19;
float x_20, _x_x_20;
float x_21, _x_x_21;
float x_1, _x_x_1;
float x_25, _x_x_25;
float x_0, _x_x_0;
float x_27, _x_x_27;
float x_6, _x_x_6;
float x_7, _x_x_7;
float x_2, _x_x_2;
float x_17, _x_x_17;
float x_5, _x_x_5;
int __steps_to_fair = __VERIFIER_nondet_int();
x_10 = __VERIFIER_nondet_float();
_J2421 = __VERIFIER_nondet_bool();
_J2411 = __VERIFIER_nondet_bool();
_EL_X_2395 = __VERIFIER_nondet_bool();
x_14 = __VERIFIER_nondet_float();
x_4 = __VERIFIER_nondet_float();
x_3 = __VERIFIER_nondet_float();
x_22 = __VERIFIER_nondet_float();
x_8 = __VERIFIER_nondet_float();
x_23 = __VERIFIER_nondet_float();
x_9 = __VERIFIER_nondet_float();
x_24 = __VERIFIER_nondet_float();
x_11 = __VERIFIER_nondet_float();
x_26 = __VERIFIER_nondet_float();
x_12 = __VERIFIER_nondet_float();
x_13 = __VERIFIER_nondet_float();
x_15 = __VERIFIER_nondet_float();
_EL_U_2394 = __VERIFIER_nondet_bool();
x_16 = __VERIFIER_nondet_float();
_EL_U_2392 = __VERIFIER_nondet_bool();
x_18 = __VERIFIER_nondet_float();
x_19 = __VERIFIER_nondet_float();
x_20 = __VERIFIER_nondet_float();
x_21 = __VERIFIER_nondet_float();
x_1 = __VERIFIER_nondet_float();
x_25 = __VERIFIER_nondet_float();
x_0 = __VERIFIER_nondet_float();
x_27 = __VERIFIER_nondet_float();
x_6 = __VERIFIER_nondet_float();
x_7 = __VERIFIER_nondet_float();
x_2 = __VERIFIER_nondet_float();
x_17 = __VERIFIER_nondet_float();
x_5 = __VERIFIER_nondet_float();
bool __ok = (1 && ((( !_EL_X_2395) && ( !_J2411)) && ( !_J2421)));
while (__steps_to_fair >= 0 && __ok) {
if ((_J2411 && _J2421)) {
__steps_to_fair = __VERIFIER_nondet_int();
} else {
__steps_to_fair--;
}
_x_x_10 = __VERIFIER_nondet_float();
_x__J2421 = __VERIFIER_nondet_bool();
_x__J2411 = __VERIFIER_nondet_bool();
_x__EL_X_2395 = __VERIFIER_nondet_bool();
_x_x_14 = __VERIFIER_nondet_float();
_x_x_4 = __VERIFIER_nondet_float();
_x_x_3 = __VERIFIER_nondet_float();
_x_x_22 = __VERIFIER_nondet_float();
_x_x_8 = __VERIFIER_nondet_float();
_x_x_23 = __VERIFIER_nondet_float();
_x_x_9 = __VERIFIER_nondet_float();
_x_x_24 = __VERIFIER_nondet_float();
_x_x_11 = __VERIFIER_nondet_float();
_x_x_26 = __VERIFIER_nondet_float();
_x_x_12 = __VERIFIER_nondet_float();
_x_x_13 = __VERIFIER_nondet_float();
_x_x_15 = __VERIFIER_nondet_float();
_x__EL_U_2394 = __VERIFIER_nondet_bool();
_x_x_16 = __VERIFIER_nondet_float();
_x__EL_U_2392 = __VERIFIER_nondet_bool();
_x_x_18 = __VERIFIER_nondet_float();
_x_x_19 = __VERIFIER_nondet_float();
_x_x_20 = __VERIFIER_nondet_float();
_x_x_21 = __VERIFIER_nondet_float();
_x_x_1 = __VERIFIER_nondet_float();
_x_x_25 = __VERIFIER_nondet_float();
_x_x_0 = __VERIFIER_nondet_float();
_x_x_27 = __VERIFIER_nondet_float();
_x_x_6 = __VERIFIER_nondet_float();
_x_x_7 = __VERIFIER_nondet_float();
_x_x_2 = __VERIFIER_nondet_float();
_x_x_17 = __VERIFIER_nondet_float();
_x_x_5 = __VERIFIER_nondet_float();
__ok = ((((((((((((((((((((((((((((((((x_24 + (-1.0 * _x_x_0)) <= -16.0) && (((x_23 + (-1.0 * _x_x_0)) <= -6.0) && (((x_22 + (-1.0 * _x_x_0)) <= -2.0) && (((x_20 + (-1.0 * _x_x_0)) <= -7.0) && (((x_19 + (-1.0 * _x_x_0)) <= -17.0) && (((x_18 + (-1.0 * _x_x_0)) <= -1.0) && (((x_16 + (-1.0 * _x_x_0)) <= -16.0) && (((x_13 + (-1.0 * _x_x_0)) <= -19.0) && (((x_8 + (-1.0 * _x_x_0)) <= -9.0) && (((x_7 + (-1.0 * _x_x_0)) <= -19.0) && (((x_6 + (-1.0 * _x_x_0)) <= -14.0) && (((x_3 + (-1.0 * _x_x_0)) <= -6.0) && (((x_0 + (-1.0 * _x_x_0)) <= -15.0) && ((x_1 + (-1.0 * _x_x_0)) <= -19.0)))))))))))))) && (((x_24 + (-1.0 * _x_x_0)) == -16.0) || (((x_23 + (-1.0 * _x_x_0)) == -6.0) || (((x_22 + (-1.0 * _x_x_0)) == -2.0) || (((x_20 + (-1.0 * _x_x_0)) == -7.0) || (((x_19 + (-1.0 * _x_x_0)) == -17.0) || (((x_18 + (-1.0 * _x_x_0)) == -1.0) || (((x_16 + (-1.0 * _x_x_0)) == -16.0) || (((x_13 + (-1.0 * _x_x_0)) == -19.0) || (((x_8 + (-1.0 * _x_x_0)) == -9.0) || (((x_7 + (-1.0 * _x_x_0)) == -19.0) || (((x_6 + (-1.0 * _x_x_0)) == -14.0) || (((x_3 + (-1.0 * _x_x_0)) == -6.0) || (((x_0 + (-1.0 * _x_x_0)) == -15.0) || ((x_1 + (-1.0 * _x_x_0)) == -19.0))))))))))))))) && ((((x_27 + (-1.0 * _x_x_1)) <= -2.0) && (((x_26 + (-1.0 * _x_x_1)) <= -20.0) && (((x_23 + (-1.0 * _x_x_1)) <= -18.0) && (((x_21 + (-1.0 * _x_x_1)) <= -8.0) && (((x_20 + (-1.0 * _x_x_1)) <= -13.0) && (((x_19 + (-1.0 * _x_x_1)) <= -1.0) && (((x_18 + (-1.0 * _x_x_1)) <= -17.0) && (((x_16 + (-1.0 * _x_x_1)) <= -20.0) && (((x_15 + (-1.0 * _x_x_1)) <= -7.0) && (((x_14 + (-1.0 * _x_x_1)) <= -10.0) && (((x_13 + (-1.0 * _x_x_1)) <= -17.0) && (((x_12 + (-1.0 * _x_x_1)) <= -15.0) && (((x_9 + (-1.0 * _x_x_1)) <= -3.0) && ((x_11 + (-1.0 * _x_x_1)) <= -10.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_1)) == -2.0) || (((x_26 + (-1.0 * _x_x_1)) == -20.0) || (((x_23 + (-1.0 * _x_x_1)) == -18.0) || (((x_21 + (-1.0 * _x_x_1)) == -8.0) || (((x_20 + (-1.0 * _x_x_1)) == -13.0) || (((x_19 + (-1.0 * _x_x_1)) == -1.0) || (((x_18 + (-1.0 * _x_x_1)) == -17.0) || (((x_16 + (-1.0 * _x_x_1)) == -20.0) || (((x_15 + (-1.0 * _x_x_1)) == -7.0) || (((x_14 + (-1.0 * _x_x_1)) == -10.0) || (((x_13 + (-1.0 * _x_x_1)) == -17.0) || (((x_12 + (-1.0 * _x_x_1)) == -15.0) || (((x_9 + (-1.0 * _x_x_1)) == -3.0) || ((x_11 + (-1.0 * _x_x_1)) == -10.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_2)) <= -12.0) && (((x_26 + (-1.0 * _x_x_2)) <= -8.0) && (((x_25 + (-1.0 * _x_x_2)) <= -11.0) && (((x_22 + (-1.0 * _x_x_2)) <= -10.0) && (((x_21 + (-1.0 * _x_x_2)) <= -14.0) && (((x_19 + (-1.0 * _x_x_2)) <= -13.0) && (((x_17 + (-1.0 * _x_x_2)) <= -19.0) && (((x_16 + (-1.0 * _x_x_2)) <= -9.0) && (((x_15 + (-1.0 * _x_x_2)) <= -14.0) && (((x_13 + (-1.0 * _x_x_2)) <= -11.0) && (((x_12 + (-1.0 * _x_x_2)) <= -8.0) && (((x_6 + (-1.0 * _x_x_2)) <= -15.0) && (((x_3 + (-1.0 * _x_x_2)) <= -6.0) && ((x_5 + (-1.0 * _x_x_2)) <= -17.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_2)) == -12.0) || (((x_26 + (-1.0 * _x_x_2)) == -8.0) || (((x_25 + (-1.0 * _x_x_2)) == -11.0) || (((x_22 + (-1.0 * _x_x_2)) == -10.0) || (((x_21 + (-1.0 * _x_x_2)) == -14.0) || (((x_19 + (-1.0 * _x_x_2)) == -13.0) || (((x_17 + (-1.0 * _x_x_2)) == -19.0) || (((x_16 + (-1.0 * _x_x_2)) == -9.0) || (((x_15 + (-1.0 * _x_x_2)) == -14.0) || (((x_13 + (-1.0 * _x_x_2)) == -11.0) || (((x_12 + (-1.0 * _x_x_2)) == -8.0) || (((x_6 + (-1.0 * _x_x_2)) == -15.0) || (((x_3 + (-1.0 * _x_x_2)) == -6.0) || ((x_5 + (-1.0 * _x_x_2)) == -17.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_3)) <= -8.0) && (((x_24 + (-1.0 * _x_x_3)) <= -4.0) && (((x_21 + (-1.0 * _x_x_3)) <= -16.0) && (((x_19 + (-1.0 * _x_x_3)) <= -8.0) && (((x_17 + (-1.0 * _x_x_3)) <= -20.0) && (((x_16 + (-1.0 * _x_x_3)) <= -16.0) && (((x_14 + (-1.0 * _x_x_3)) <= -2.0) && (((x_13 + (-1.0 * _x_x_3)) <= -7.0) && (((x_9 + (-1.0 * _x_x_3)) <= -20.0) && (((x_7 + (-1.0 * _x_x_3)) <= -12.0) && (((x_6 + (-1.0 * _x_x_3)) <= -15.0) && (((x_5 + (-1.0 * _x_x_3)) <= -17.0) && (((x_0 + (-1.0 * _x_x_3)) <= -4.0) && ((x_2 + (-1.0 * _x_x_3)) <= -11.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_3)) == -8.0) || (((x_24 + (-1.0 * _x_x_3)) == -4.0) || (((x_21 + (-1.0 * _x_x_3)) == -16.0) || (((x_19 + (-1.0 * _x_x_3)) == -8.0) || (((x_17 + (-1.0 * _x_x_3)) == -20.0) || (((x_16 + (-1.0 * _x_x_3)) == -16.0) || (((x_14 + (-1.0 * _x_x_3)) == -2.0) || (((x_13 + (-1.0 * _x_x_3)) == -7.0) || (((x_9 + (-1.0 * _x_x_3)) == -20.0) || (((x_7 + (-1.0 * _x_x_3)) == -12.0) || (((x_6 + (-1.0 * _x_x_3)) == -15.0) || (((x_5 + (-1.0 * _x_x_3)) == -17.0) || (((x_0 + (-1.0 * _x_x_3)) == -4.0) || ((x_2 + (-1.0 * _x_x_3)) == -11.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_4)) <= -12.0) && (((x_26 + (-1.0 * _x_x_4)) <= -17.0) && (((x_25 + (-1.0 * _x_x_4)) <= -7.0) && (((x_22 + (-1.0 * _x_x_4)) <= -13.0) && (((x_21 + (-1.0 * _x_x_4)) <= -13.0) && (((x_19 + (-1.0 * _x_x_4)) <= -5.0) && (((x_18 + (-1.0 * _x_x_4)) <= -7.0) && (((x_13 + (-1.0 * _x_x_4)) <= -1.0) && (((x_12 + (-1.0 * _x_x_4)) <= -19.0) && (((x_11 + (-1.0 * _x_x_4)) <= -19.0) && (((x_10 + (-1.0 * _x_x_4)) <= -15.0) && (((x_8 + (-1.0 * _x_x_4)) <= -9.0) && (((x_1 + (-1.0 * _x_x_4)) <= -6.0) && ((x_3 + (-1.0 * _x_x_4)) <= -3.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_4)) == -12.0) || (((x_26 + (-1.0 * _x_x_4)) == -17.0) || (((x_25 + (-1.0 * _x_x_4)) == -7.0) || (((x_22 + (-1.0 * _x_x_4)) == -13.0) || (((x_21 + (-1.0 * _x_x_4)) == -13.0) || (((x_19 + (-1.0 * _x_x_4)) == -5.0) || (((x_18 + (-1.0 * _x_x_4)) == -7.0) || (((x_13 + (-1.0 * _x_x_4)) == -1.0) || (((x_12 + (-1.0 * _x_x_4)) == -19.0) || (((x_11 + (-1.0 * _x_x_4)) == -19.0) || (((x_10 + (-1.0 * _x_x_4)) == -15.0) || (((x_8 + (-1.0 * _x_x_4)) == -9.0) || (((x_1 + (-1.0 * _x_x_4)) == -6.0) || ((x_3 + (-1.0 * _x_x_4)) == -3.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_5)) <= -17.0) && (((x_23 + (-1.0 * _x_x_5)) <= -15.0) && (((x_19 + (-1.0 * _x_x_5)) <= -7.0) && (((x_17 + (-1.0 * _x_x_5)) <= -15.0) && (((x_16 + (-1.0 * _x_x_5)) <= -20.0) && (((x_15 + (-1.0 * _x_x_5)) <= -2.0) && (((x_14 + (-1.0 * _x_x_5)) <= -4.0) && (((x_13 + (-1.0 * _x_x_5)) <= -9.0) && (((x_11 + (-1.0 * _x_x_5)) <= -16.0) && (((x_10 + (-1.0 * _x_x_5)) <= -18.0) && (((x_7 + (-1.0 * _x_x_5)) <= -4.0) && (((x_6 + (-1.0 * _x_x_5)) <= -10.0) && (((x_0 + (-1.0 * _x_x_5)) <= -13.0) && ((x_1 + (-1.0 * _x_x_5)) <= -6.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_5)) == -17.0) || (((x_23 + (-1.0 * _x_x_5)) == -15.0) || (((x_19 + (-1.0 * _x_x_5)) == -7.0) || (((x_17 + (-1.0 * _x_x_5)) == -15.0) || (((x_16 + (-1.0 * _x_x_5)) == -20.0) || (((x_15 + (-1.0 * _x_x_5)) == -2.0) || (((x_14 + (-1.0 * _x_x_5)) == -4.0) || (((x_13 + (-1.0 * _x_x_5)) == -9.0) || (((x_11 + (-1.0 * _x_x_5)) == -16.0) || (((x_10 + (-1.0 * _x_x_5)) == -18.0) || (((x_7 + (-1.0 * _x_x_5)) == -4.0) || (((x_6 + (-1.0 * _x_x_5)) == -10.0) || (((x_0 + (-1.0 * _x_x_5)) == -13.0) || ((x_1 + (-1.0 * _x_x_5)) == -6.0)))))))))))))))) && ((((x_23 + (-1.0 * _x_x_6)) <= -5.0) && (((x_19 + (-1.0 * _x_x_6)) <= -19.0) && (((x_18 + (-1.0 * _x_x_6)) <= -14.0) && (((x_17 + (-1.0 * _x_x_6)) <= -16.0) && (((x_15 + (-1.0 * _x_x_6)) <= -1.0) && (((x_14 + (-1.0 * _x_x_6)) <= -15.0) && (((x_13 + (-1.0 * _x_x_6)) <= -5.0) && (((x_12 + (-1.0 * _x_x_6)) <= -9.0) && (((x_11 + (-1.0 * _x_x_6)) <= -8.0) && (((x_9 + (-1.0 * _x_x_6)) <= -12.0) && (((x_6 + (-1.0 * _x_x_6)) <= -10.0) && (((x_5 + (-1.0 * _x_x_6)) <= -13.0) && (((x_3 + (-1.0 * _x_x_6)) <= -15.0) && ((x_4 + (-1.0 * _x_x_6)) <= -7.0)))))))))))))) && (((x_23 + (-1.0 * _x_x_6)) == -5.0) || (((x_19 + (-1.0 * _x_x_6)) == -19.0) || (((x_18 + (-1.0 * _x_x_6)) == -14.0) || (((x_17 + (-1.0 * _x_x_6)) == -16.0) || (((x_15 + (-1.0 * _x_x_6)) == -1.0) || (((x_14 + (-1.0 * _x_x_6)) == -15.0) || (((x_13 + (-1.0 * _x_x_6)) == -5.0) || (((x_12 + (-1.0 * _x_x_6)) == -9.0) || (((x_11 + (-1.0 * _x_x_6)) == -8.0) || (((x_9 + (-1.0 * _x_x_6)) == -12.0) || (((x_6 + (-1.0 * _x_x_6)) == -10.0) || (((x_5 + (-1.0 * _x_x_6)) == -13.0) || (((x_3 + (-1.0 * _x_x_6)) == -15.0) || ((x_4 + (-1.0 * _x_x_6)) == -7.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_7)) <= -13.0) && (((x_26 + (-1.0 * _x_x_7)) <= -17.0) && (((x_25 + (-1.0 * _x_x_7)) <= -2.0) && (((x_24 + (-1.0 * _x_x_7)) <= -7.0) && (((x_23 + (-1.0 * _x_x_7)) <= -8.0) && (((x_20 + (-1.0 * _x_x_7)) <= -19.0) && (((x_19 + (-1.0 * _x_x_7)) <= -14.0) && (((x_18 + (-1.0 * _x_x_7)) <= -12.0) && (((x_17 + (-1.0 * _x_x_7)) <= -16.0) && (((x_14 + (-1.0 * _x_x_7)) <= -7.0) && (((x_11 + (-1.0 * _x_x_7)) <= -11.0) && (((x_10 + (-1.0 * _x_x_7)) <= -6.0) && (((x_3 + (-1.0 * _x_x_7)) <= -8.0) && ((x_4 + (-1.0 * _x_x_7)) <= -11.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_7)) == -13.0) || (((x_26 + (-1.0 * _x_x_7)) == -17.0) || (((x_25 + (-1.0 * _x_x_7)) == -2.0) || (((x_24 + (-1.0 * _x_x_7)) == -7.0) || (((x_23 + (-1.0 * _x_x_7)) == -8.0) || (((x_20 + (-1.0 * _x_x_7)) == -19.0) || (((x_19 + (-1.0 * _x_x_7)) == -14.0) || (((x_18 + (-1.0 * _x_x_7)) == -12.0) || (((x_17 + (-1.0 * _x_x_7)) == -16.0) || (((x_14 + (-1.0 * _x_x_7)) == -7.0) || (((x_11 + (-1.0 * _x_x_7)) == -11.0) || (((x_10 + (-1.0 * _x_x_7)) == -6.0) || (((x_3 + (-1.0 * _x_x_7)) == -8.0) || ((x_4 + (-1.0 * _x_x_7)) == -11.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_8)) <= -6.0) && (((x_26 + (-1.0 * _x_x_8)) <= -19.0) && (((x_23 + (-1.0 * _x_x_8)) <= -9.0) && (((x_22 + (-1.0 * _x_x_8)) <= -19.0) && (((x_19 + (-1.0 * _x_x_8)) <= -1.0) && (((x_18 + (-1.0 * _x_x_8)) <= -4.0) && (((x_11 + (-1.0 * _x_x_8)) <= -9.0) && (((x_10 + (-1.0 * _x_x_8)) <= -19.0) && (((x_8 + (-1.0 * _x_x_8)) <= -11.0) && (((x_7 + (-1.0 * _x_x_8)) <= -10.0) && (((x_5 + (-1.0 * _x_x_8)) <= -18.0) && (((x_2 + (-1.0 * _x_x_8)) <= -19.0) && (((x_0 + (-1.0 * _x_x_8)) <= -16.0) && ((x_1 + (-1.0 * _x_x_8)) <= -5.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_8)) == -6.0) || (((x_26 + (-1.0 * _x_x_8)) == -19.0) || (((x_23 + (-1.0 * _x_x_8)) == -9.0) || (((x_22 + (-1.0 * _x_x_8)) == -19.0) || (((x_19 + (-1.0 * _x_x_8)) == -1.0) || (((x_18 + (-1.0 * _x_x_8)) == -4.0) || (((x_11 + (-1.0 * _x_x_8)) == -9.0) || (((x_10 + (-1.0 * _x_x_8)) == -19.0) || (((x_8 + (-1.0 * _x_x_8)) == -11.0) || (((x_7 + (-1.0 * _x_x_8)) == -10.0) || (((x_5 + (-1.0 * _x_x_8)) == -18.0) || (((x_2 + (-1.0 * _x_x_8)) == -19.0) || (((x_0 + (-1.0 * _x_x_8)) == -16.0) || ((x_1 + (-1.0 * _x_x_8)) == -5.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_9)) <= -10.0) && (((x_24 + (-1.0 * _x_x_9)) <= -14.0) && (((x_23 + (-1.0 * _x_x_9)) <= -10.0) && (((x_22 + (-1.0 * _x_x_9)) <= -20.0) && (((x_20 + (-1.0 * _x_x_9)) <= -15.0) && (((x_19 + (-1.0 * _x_x_9)) <= -17.0) && (((x_18 + (-1.0 * _x_x_9)) <= -11.0) && (((x_17 + (-1.0 * _x_x_9)) <= -15.0) && (((x_16 + (-1.0 * _x_x_9)) <= -20.0) && (((x_10 + (-1.0 * _x_x_9)) <= -12.0) && (((x_8 + (-1.0 * _x_x_9)) <= -4.0) && (((x_6 + (-1.0 * _x_x_9)) <= -16.0) && (((x_0 + (-1.0 * _x_x_9)) <= -10.0) && ((x_2 + (-1.0 * _x_x_9)) <= -14.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_9)) == -10.0) || (((x_24 + (-1.0 * _x_x_9)) == -14.0) || (((x_23 + (-1.0 * _x_x_9)) == -10.0) || (((x_22 + (-1.0 * _x_x_9)) == -20.0) || (((x_20 + (-1.0 * _x_x_9)) == -15.0) || (((x_19 + (-1.0 * _x_x_9)) == -17.0) || (((x_18 + (-1.0 * _x_x_9)) == -11.0) || (((x_17 + (-1.0 * _x_x_9)) == -15.0) || (((x_16 + (-1.0 * _x_x_9)) == -20.0) || (((x_10 + (-1.0 * _x_x_9)) == -12.0) || (((x_8 + (-1.0 * _x_x_9)) == -4.0) || (((x_6 + (-1.0 * _x_x_9)) == -16.0) || (((x_0 + (-1.0 * _x_x_9)) == -10.0) || ((x_2 + (-1.0 * _x_x_9)) == -14.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_10)) <= -5.0) && (((x_25 + (-1.0 * _x_x_10)) <= -3.0) && (((x_24 + (-1.0 * _x_x_10)) <= -5.0) && (((x_23 + (-1.0 * _x_x_10)) <= -16.0) && (((x_22 + (-1.0 * _x_x_10)) <= -13.0) && (((x_21 + (-1.0 * _x_x_10)) <= -11.0) && (((x_20 + (-1.0 * _x_x_10)) <= -17.0) && (((x_16 + (-1.0 * _x_x_10)) <= -8.0) && (((x_15 + (-1.0 * _x_x_10)) <= -17.0) && (((x_7 + (-1.0 * _x_x_10)) <= -12.0) && (((x_5 + (-1.0 * _x_x_10)) <= -20.0) && (((x_3 + (-1.0 * _x_x_10)) <= -20.0) && (((x_1 + (-1.0 * _x_x_10)) <= -15.0) && ((x_2 + (-1.0 * _x_x_10)) <= -19.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_10)) == -5.0) || (((x_25 + (-1.0 * _x_x_10)) == -3.0) || (((x_24 + (-1.0 * _x_x_10)) == -5.0) || (((x_23 + (-1.0 * _x_x_10)) == -16.0) || (((x_22 + (-1.0 * _x_x_10)) == -13.0) || (((x_21 + (-1.0 * _x_x_10)) == -11.0) || (((x_20 + (-1.0 * _x_x_10)) == -17.0) || (((x_16 + (-1.0 * _x_x_10)) == -8.0) || (((x_15 + (-1.0 * _x_x_10)) == -17.0) || (((x_7 + (-1.0 * _x_x_10)) == -12.0) || (((x_5 + (-1.0 * _x_x_10)) == -20.0) || (((x_3 + (-1.0 * _x_x_10)) == -20.0) || (((x_1 + (-1.0 * _x_x_10)) == -15.0) || ((x_2 + (-1.0 * _x_x_10)) == -19.0)))))))))))))))) && ((((x_24 + (-1.0 * _x_x_11)) <= -14.0) && (((x_23 + (-1.0 * _x_x_11)) <= -14.0) && (((x_21 + (-1.0 * _x_x_11)) <= -9.0) && (((x_20 + (-1.0 * _x_x_11)) <= -10.0) && (((x_19 + (-1.0 * _x_x_11)) <= -18.0) && (((x_17 + (-1.0 * _x_x_11)) <= -9.0) && (((x_13 + (-1.0 * _x_x_11)) <= -17.0) && (((x_12 + (-1.0 * _x_x_11)) <= -16.0) && (((x_10 + (-1.0 * _x_x_11)) <= -9.0) && (((x_8 + (-1.0 * _x_x_11)) <= -7.0) && (((x_7 + (-1.0 * _x_x_11)) <= -8.0) && (((x_5 + (-1.0 * _x_x_11)) <= -4.0) && (((x_1 + (-1.0 * _x_x_11)) <= -5.0) && ((x_4 + (-1.0 * _x_x_11)) <= -5.0)))))))))))))) && (((x_24 + (-1.0 * _x_x_11)) == -14.0) || (((x_23 + (-1.0 * _x_x_11)) == -14.0) || (((x_21 + (-1.0 * _x_x_11)) == -9.0) || (((x_20 + (-1.0 * _x_x_11)) == -10.0) || (((x_19 + (-1.0 * _x_x_11)) == -18.0) || (((x_17 + (-1.0 * _x_x_11)) == -9.0) || (((x_13 + (-1.0 * _x_x_11)) == -17.0) || (((x_12 + (-1.0 * _x_x_11)) == -16.0) || (((x_10 + (-1.0 * _x_x_11)) == -9.0) || (((x_8 + (-1.0 * _x_x_11)) == -7.0) || (((x_7 + (-1.0 * _x_x_11)) == -8.0) || (((x_5 + (-1.0 * _x_x_11)) == -4.0) || (((x_1 + (-1.0 * _x_x_11)) == -5.0) || ((x_4 + (-1.0 * _x_x_11)) == -5.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_12)) <= -19.0) && (((x_23 + (-1.0 * _x_x_12)) <= -19.0) && (((x_21 + (-1.0 * _x_x_12)) <= -17.0) && (((x_18 + (-1.0 * _x_x_12)) <= -6.0) && (((x_16 + (-1.0 * _x_x_12)) <= -14.0) && (((x_15 + (-1.0 * _x_x_12)) <= -10.0) && (((x_13 + (-1.0 * _x_x_12)) <= -2.0) && (((x_9 + (-1.0 * _x_x_12)) <= -7.0) && (((x_7 + (-1.0 * _x_x_12)) <= -6.0) && (((x_6 + (-1.0 * _x_x_12)) <= -18.0) && (((x_5 + (-1.0 * _x_x_12)) <= -1.0) && (((x_3 + (-1.0 * _x_x_12)) <= -14.0) && (((x_0 + (-1.0 * _x_x_12)) <= -18.0) && ((x_2 + (-1.0 * _x_x_12)) <= -12.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_12)) == -19.0) || (((x_23 + (-1.0 * _x_x_12)) == -19.0) || (((x_21 + (-1.0 * _x_x_12)) == -17.0) || (((x_18 + (-1.0 * _x_x_12)) == -6.0) || (((x_16 + (-1.0 * _x_x_12)) == -14.0) || (((x_15 + (-1.0 * _x_x_12)) == -10.0) || (((x_13 + (-1.0 * _x_x_12)) == -2.0) || (((x_9 + (-1.0 * _x_x_12)) == -7.0) || (((x_7 + (-1.0 * _x_x_12)) == -6.0) || (((x_6 + (-1.0 * _x_x_12)) == -18.0) || (((x_5 + (-1.0 * _x_x_12)) == -1.0) || (((x_3 + (-1.0 * _x_x_12)) == -14.0) || (((x_0 + (-1.0 * _x_x_12)) == -18.0) || ((x_2 + (-1.0 * _x_x_12)) == -12.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_13)) <= -19.0) && (((x_22 + (-1.0 * _x_x_13)) <= -4.0) && (((x_21 + (-1.0 * _x_x_13)) <= -16.0) && (((x_19 + (-1.0 * _x_x_13)) <= -19.0) && (((x_18 + (-1.0 * _x_x_13)) <= -14.0) && (((x_15 + (-1.0 * _x_x_13)) <= -10.0) && (((x_13 + (-1.0 * _x_x_13)) <= -5.0) && (((x_12 + (-1.0 * _x_x_13)) <= -4.0) && (((x_11 + (-1.0 * _x_x_13)) <= -12.0) && (((x_9 + (-1.0 * _x_x_13)) <= -20.0) && (((x_6 + (-1.0 * _x_x_13)) <= -17.0) && (((x_3 + (-1.0 * _x_x_13)) <= -10.0) && (((x_1 + (-1.0 * _x_x_13)) <= -3.0) && ((x_2 + (-1.0 * _x_x_13)) <= -17.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_13)) == -19.0) || (((x_22 + (-1.0 * _x_x_13)) == -4.0) || (((x_21 + (-1.0 * _x_x_13)) == -16.0) || (((x_19 + (-1.0 * _x_x_13)) == -19.0) || (((x_18 + (-1.0 * _x_x_13)) == -14.0) || (((x_15 + (-1.0 * _x_x_13)) == -10.0) || (((x_13 + (-1.0 * _x_x_13)) == -5.0) || (((x_12 + (-1.0 * _x_x_13)) == -4.0) || (((x_11 + (-1.0 * _x_x_13)) == -12.0) || (((x_9 + (-1.0 * _x_x_13)) == -20.0) || (((x_6 + (-1.0 * _x_x_13)) == -17.0) || (((x_3 + (-1.0 * _x_x_13)) == -10.0) || (((x_1 + (-1.0 * _x_x_13)) == -3.0) || ((x_2 + (-1.0 * _x_x_13)) == -17.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_14)) <= -16.0) && (((x_26 + (-1.0 * _x_x_14)) <= -20.0) && (((x_23 + (-1.0 * _x_x_14)) <= -3.0) && (((x_22 + (-1.0 * _x_x_14)) <= -4.0) && (((x_19 + (-1.0 * _x_x_14)) <= -14.0) && (((x_15 + (-1.0 * _x_x_14)) <= -1.0) && (((x_10 + (-1.0 * _x_x_14)) <= -6.0) && (((x_9 + (-1.0 * _x_x_14)) <= -15.0) && (((x_8 + (-1.0 * _x_x_14)) <= -15.0) && (((x_7 + (-1.0 * _x_x_14)) <= -19.0) && (((x_6 + (-1.0 * _x_x_14)) <= -4.0) && (((x_5 + (-1.0 * _x_x_14)) <= -9.0) && (((x_0 + (-1.0 * _x_x_14)) <= -7.0) && ((x_1 + (-1.0 * _x_x_14)) <= -8.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_14)) == -16.0) || (((x_26 + (-1.0 * _x_x_14)) == -20.0) || (((x_23 + (-1.0 * _x_x_14)) == -3.0) || (((x_22 + (-1.0 * _x_x_14)) == -4.0) || (((x_19 + (-1.0 * _x_x_14)) == -14.0) || (((x_15 + (-1.0 * _x_x_14)) == -1.0) || (((x_10 + (-1.0 * _x_x_14)) == -6.0) || (((x_9 + (-1.0 * _x_x_14)) == -15.0) || (((x_8 + (-1.0 * _x_x_14)) == -15.0) || (((x_7 + (-1.0 * _x_x_14)) == -19.0) || (((x_6 + (-1.0 * _x_x_14)) == -4.0) || (((x_5 + (-1.0 * _x_x_14)) == -9.0) || (((x_0 + (-1.0 * _x_x_14)) == -7.0) || ((x_1 + (-1.0 * _x_x_14)) == -8.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_15)) <= -12.0) && (((x_25 + (-1.0 * _x_x_15)) <= -10.0) && (((x_22 + (-1.0 * _x_x_15)) <= -7.0) && (((x_20 + (-1.0 * _x_x_15)) <= -5.0) && (((x_17 + (-1.0 * _x_x_15)) <= -20.0) && (((x_15 + (-1.0 * _x_x_15)) <= -16.0) && (((x_13 + (-1.0 * _x_x_15)) <= -2.0) && (((x_11 + (-1.0 * _x_x_15)) <= -6.0) && (((x_7 + (-1.0 * _x_x_15)) <= -18.0) && (((x_6 + (-1.0 * _x_x_15)) <= -10.0) && (((x_4 + (-1.0 * _x_x_15)) <= -13.0) && (((x_3 + (-1.0 * _x_x_15)) <= -19.0) && (((x_0 + (-1.0 * _x_x_15)) <= -5.0) && ((x_2 + (-1.0 * _x_x_15)) <= -13.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_15)) == -12.0) || (((x_25 + (-1.0 * _x_x_15)) == -10.0) || (((x_22 + (-1.0 * _x_x_15)) == -7.0) || (((x_20 + (-1.0 * _x_x_15)) == -5.0) || (((x_17 + (-1.0 * _x_x_15)) == -20.0) || (((x_15 + (-1.0 * _x_x_15)) == -16.0) || (((x_13 + (-1.0 * _x_x_15)) == -2.0) || (((x_11 + (-1.0 * _x_x_15)) == -6.0) || (((x_7 + (-1.0 * _x_x_15)) == -18.0) || (((x_6 + (-1.0 * _x_x_15)) == -10.0) || (((x_4 + (-1.0 * _x_x_15)) == -13.0) || (((x_3 + (-1.0 * _x_x_15)) == -19.0) || (((x_0 + (-1.0 * _x_x_15)) == -5.0) || ((x_2 + (-1.0 * _x_x_15)) == -13.0)))))))))))))))) && ((((x_25 + (-1.0 * _x_x_16)) <= -7.0) && (((x_23 + (-1.0 * _x_x_16)) <= -13.0) && (((x_22 + (-1.0 * _x_x_16)) <= -10.0) && (((x_21 + (-1.0 * _x_x_16)) <= -10.0) && (((x_16 + (-1.0 * _x_x_16)) <= -15.0) && (((x_15 + (-1.0 * _x_x_16)) <= -8.0) && (((x_13 + (-1.0 * _x_x_16)) <= -15.0) && (((x_12 + (-1.0 * _x_x_16)) <= -6.0) && (((x_11 + (-1.0 * _x_x_16)) <= -5.0) && (((x_10 + (-1.0 * _x_x_16)) <= -6.0) && (((x_6 + (-1.0 * _x_x_16)) <= -3.0) && (((x_4 + (-1.0 * _x_x_16)) <= -1.0) && (((x_2 + (-1.0 * _x_x_16)) <= -16.0) && ((x_3 + (-1.0 * _x_x_16)) <= -10.0)))))))))))))) && (((x_25 + (-1.0 * _x_x_16)) == -7.0) || (((x_23 + (-1.0 * _x_x_16)) == -13.0) || (((x_22 + (-1.0 * _x_x_16)) == -10.0) || (((x_21 + (-1.0 * _x_x_16)) == -10.0) || (((x_16 + (-1.0 * _x_x_16)) == -15.0) || (((x_15 + (-1.0 * _x_x_16)) == -8.0) || (((x_13 + (-1.0 * _x_x_16)) == -15.0) || (((x_12 + (-1.0 * _x_x_16)) == -6.0) || (((x_11 + (-1.0 * _x_x_16)) == -5.0) || (((x_10 + (-1.0 * _x_x_16)) == -6.0) || (((x_6 + (-1.0 * _x_x_16)) == -3.0) || (((x_4 + (-1.0 * _x_x_16)) == -1.0) || (((x_2 + (-1.0 * _x_x_16)) == -16.0) || ((x_3 + (-1.0 * _x_x_16)) == -10.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_17)) <= -8.0) && (((x_25 + (-1.0 * _x_x_17)) <= -12.0) && (((x_23 + (-1.0 * _x_x_17)) <= -13.0) && (((x_21 + (-1.0 * _x_x_17)) <= -11.0) && (((x_20 + (-1.0 * _x_x_17)) <= -7.0) && (((x_19 + (-1.0 * _x_x_17)) <= -17.0) && (((x_15 + (-1.0 * _x_x_17)) <= -14.0) && (((x_13 + (-1.0 * _x_x_17)) <= -18.0) && (((x_10 + (-1.0 * _x_x_17)) <= -5.0) && (((x_8 + (-1.0 * _x_x_17)) <= -20.0) && (((x_6 + (-1.0 * _x_x_17)) <= -5.0) && (((x_5 + (-1.0 * _x_x_17)) <= -3.0) && (((x_1 + (-1.0 * _x_x_17)) <= -8.0) && ((x_4 + (-1.0 * _x_x_17)) <= -18.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_17)) == -8.0) || (((x_25 + (-1.0 * _x_x_17)) == -12.0) || (((x_23 + (-1.0 * _x_x_17)) == -13.0) || (((x_21 + (-1.0 * _x_x_17)) == -11.0) || (((x_20 + (-1.0 * _x_x_17)) == -7.0) || (((x_19 + (-1.0 * _x_x_17)) == -17.0) || (((x_15 + (-1.0 * _x_x_17)) == -14.0) || (((x_13 + (-1.0 * _x_x_17)) == -18.0) || (((x_10 + (-1.0 * _x_x_17)) == -5.0) || (((x_8 + (-1.0 * _x_x_17)) == -20.0) || (((x_6 + (-1.0 * _x_x_17)) == -5.0) || (((x_5 + (-1.0 * _x_x_17)) == -3.0) || (((x_1 + (-1.0 * _x_x_17)) == -8.0) || ((x_4 + (-1.0 * _x_x_17)) == -18.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_18)) <= -6.0) && (((x_24 + (-1.0 * _x_x_18)) <= -10.0) && (((x_22 + (-1.0 * _x_x_18)) <= -7.0) && (((x_21 + (-1.0 * _x_x_18)) <= -9.0) && (((x_16 + (-1.0 * _x_x_18)) <= -6.0) && (((x_15 + (-1.0 * _x_x_18)) <= -7.0) && (((x_12 + (-1.0 * _x_x_18)) <= -9.0) && (((x_11 + (-1.0 * _x_x_18)) <= -1.0) && (((x_8 + (-1.0 * _x_x_18)) <= -6.0) && (((x_7 + (-1.0 * _x_x_18)) <= -13.0) && (((x_6 + (-1.0 * _x_x_18)) <= -9.0) && (((x_5 + (-1.0 * _x_x_18)) <= -9.0) && (((x_0 + (-1.0 * _x_x_18)) <= -1.0) && ((x_3 + (-1.0 * _x_x_18)) <= -6.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_18)) == -6.0) || (((x_24 + (-1.0 * _x_x_18)) == -10.0) || (((x_22 + (-1.0 * _x_x_18)) == -7.0) || (((x_21 + (-1.0 * _x_x_18)) == -9.0) || (((x_16 + (-1.0 * _x_x_18)) == -6.0) || (((x_15 + (-1.0 * _x_x_18)) == -7.0) || (((x_12 + (-1.0 * _x_x_18)) == -9.0) || (((x_11 + (-1.0 * _x_x_18)) == -1.0) || (((x_8 + (-1.0 * _x_x_18)) == -6.0) || (((x_7 + (-1.0 * _x_x_18)) == -13.0) || (((x_6 + (-1.0 * _x_x_18)) == -9.0) || (((x_5 + (-1.0 * _x_x_18)) == -9.0) || (((x_0 + (-1.0 * _x_x_18)) == -1.0) || ((x_3 + (-1.0 * _x_x_18)) == -6.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_19)) <= -8.0) && (((x_26 + (-1.0 * _x_x_19)) <= -17.0) && (((x_23 + (-1.0 * _x_x_19)) <= -19.0) && (((x_21 + (-1.0 * _x_x_19)) <= -18.0) && (((x_20 + (-1.0 * _x_x_19)) <= -4.0) && (((x_19 + (-1.0 * _x_x_19)) <= -10.0) && (((x_18 + (-1.0 * _x_x_19)) <= -5.0) && (((x_16 + (-1.0 * _x_x_19)) <= -12.0) && (((x_15 + (-1.0 * _x_x_19)) <= -19.0) && (((x_13 + (-1.0 * _x_x_19)) <= -6.0) && (((x_12 + (-1.0 * _x_x_19)) <= -19.0) && (((x_10 + (-1.0 * _x_x_19)) <= -16.0) && (((x_6 + (-1.0 * _x_x_19)) <= -18.0) && ((x_8 + (-1.0 * _x_x_19)) <= -3.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_19)) == -8.0) || (((x_26 + (-1.0 * _x_x_19)) == -17.0) || (((x_23 + (-1.0 * _x_x_19)) == -19.0) || (((x_21 + (-1.0 * _x_x_19)) == -18.0) || (((x_20 + (-1.0 * _x_x_19)) == -4.0) || (((x_19 + (-1.0 * _x_x_19)) == -10.0) || (((x_18 + (-1.0 * _x_x_19)) == -5.0) || (((x_16 + (-1.0 * _x_x_19)) == -12.0) || (((x_15 + (-1.0 * _x_x_19)) == -19.0) || (((x_13 + (-1.0 * _x_x_19)) == -6.0) || (((x_12 + (-1.0 * _x_x_19)) == -19.0) || (((x_10 + (-1.0 * _x_x_19)) == -16.0) || (((x_6 + (-1.0 * _x_x_19)) == -18.0) || ((x_8 + (-1.0 * _x_x_19)) == -3.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_20)) <= -9.0) && (((x_25 + (-1.0 * _x_x_20)) <= -3.0) && (((x_22 + (-1.0 * _x_x_20)) <= -17.0) && (((x_20 + (-1.0 * _x_x_20)) <= -16.0) && (((x_19 + (-1.0 * _x_x_20)) <= -3.0) && (((x_18 + (-1.0 * _x_x_20)) <= -15.0) && (((x_16 + (-1.0 * _x_x_20)) <= -7.0) && (((x_14 + (-1.0 * _x_x_20)) <= -18.0) && (((x_12 + (-1.0 * _x_x_20)) <= -1.0) && (((x_11 + (-1.0 * _x_x_20)) <= -10.0) && (((x_7 + (-1.0 * _x_x_20)) <= -20.0) && (((x_6 + (-1.0 * _x_x_20)) <= -16.0) && (((x_1 + (-1.0 * _x_x_20)) <= -19.0) && ((x_4 + (-1.0 * _x_x_20)) <= -7.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_20)) == -9.0) || (((x_25 + (-1.0 * _x_x_20)) == -3.0) || (((x_22 + (-1.0 * _x_x_20)) == -17.0) || (((x_20 + (-1.0 * _x_x_20)) == -16.0) || (((x_19 + (-1.0 * _x_x_20)) == -3.0) || (((x_18 + (-1.0 * _x_x_20)) == -15.0) || (((x_16 + (-1.0 * _x_x_20)) == -7.0) || (((x_14 + (-1.0 * _x_x_20)) == -18.0) || (((x_12 + (-1.0 * _x_x_20)) == -1.0) || (((x_11 + (-1.0 * _x_x_20)) == -10.0) || (((x_7 + (-1.0 * _x_x_20)) == -20.0) || (((x_6 + (-1.0 * _x_x_20)) == -16.0) || (((x_1 + (-1.0 * _x_x_20)) == -19.0) || ((x_4 + (-1.0 * _x_x_20)) == -7.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_21)) <= -5.0) && (((x_26 + (-1.0 * _x_x_21)) <= -17.0) && (((x_23 + (-1.0 * _x_x_21)) <= -7.0) && (((x_22 + (-1.0 * _x_x_21)) <= -8.0) && (((x_21 + (-1.0 * _x_x_21)) <= -7.0) && (((x_19 + (-1.0 * _x_x_21)) <= -20.0) && (((x_18 + (-1.0 * _x_x_21)) <= -1.0) && (((x_16 + (-1.0 * _x_x_21)) <= -11.0) && (((x_15 + (-1.0 * _x_x_21)) <= -5.0) && (((x_13 + (-1.0 * _x_x_21)) <= -13.0) && (((x_11 + (-1.0 * _x_x_21)) <= -4.0) && (((x_10 + (-1.0 * _x_x_21)) <= -14.0) && (((x_1 + (-1.0 * _x_x_21)) <= -19.0) && ((x_4 + (-1.0 * _x_x_21)) <= -13.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_21)) == -5.0) || (((x_26 + (-1.0 * _x_x_21)) == -17.0) || (((x_23 + (-1.0 * _x_x_21)) == -7.0) || (((x_22 + (-1.0 * _x_x_21)) == -8.0) || (((x_21 + (-1.0 * _x_x_21)) == -7.0) || (((x_19 + (-1.0 * _x_x_21)) == -20.0) || (((x_18 + (-1.0 * _x_x_21)) == -1.0) || (((x_16 + (-1.0 * _x_x_21)) == -11.0) || (((x_15 + (-1.0 * _x_x_21)) == -5.0) || (((x_13 + (-1.0 * _x_x_21)) == -13.0) || (((x_11 + (-1.0 * _x_x_21)) == -4.0) || (((x_10 + (-1.0 * _x_x_21)) == -14.0) || (((x_1 + (-1.0 * _x_x_21)) == -19.0) || ((x_4 + (-1.0 * _x_x_21)) == -13.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_22)) <= -15.0) && (((x_25 + (-1.0 * _x_x_22)) <= -4.0) && (((x_24 + (-1.0 * _x_x_22)) <= -2.0) && (((x_22 + (-1.0 * _x_x_22)) <= -10.0) && (((x_19 + (-1.0 * _x_x_22)) <= -20.0) && (((x_13 + (-1.0 * _x_x_22)) <= -17.0) && (((x_10 + (-1.0 * _x_x_22)) <= -8.0) && (((x_9 + (-1.0 * _x_x_22)) <= -9.0) && (((x_7 + (-1.0 * _x_x_22)) <= -20.0) && (((x_6 + (-1.0 * _x_x_22)) <= -8.0) && (((x_5 + (-1.0 * _x_x_22)) <= -5.0) && (((x_4 + (-1.0 * _x_x_22)) <= -16.0) && (((x_0 + (-1.0 * _x_x_22)) <= -4.0) && ((x_3 + (-1.0 * _x_x_22)) <= -13.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_22)) == -15.0) || (((x_25 + (-1.0 * _x_x_22)) == -4.0) || (((x_24 + (-1.0 * _x_x_22)) == -2.0) || (((x_22 + (-1.0 * _x_x_22)) == -10.0) || (((x_19 + (-1.0 * _x_x_22)) == -20.0) || (((x_13 + (-1.0 * _x_x_22)) == -17.0) || (((x_10 + (-1.0 * _x_x_22)) == -8.0) || (((x_9 + (-1.0 * _x_x_22)) == -9.0) || (((x_7 + (-1.0 * _x_x_22)) == -20.0) || (((x_6 + (-1.0 * _x_x_22)) == -8.0) || (((x_5 + (-1.0 * _x_x_22)) == -5.0) || (((x_4 + (-1.0 * _x_x_22)) == -16.0) || (((x_0 + (-1.0 * _x_x_22)) == -4.0) || ((x_3 + (-1.0 * _x_x_22)) == -13.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_23)) <= -17.0) && (((x_23 + (-1.0 * _x_x_23)) <= -3.0) && (((x_22 + (-1.0 * _x_x_23)) <= -20.0) && (((x_21 + (-1.0 * _x_x_23)) <= -13.0) && (((x_18 + (-1.0 * _x_x_23)) <= -3.0) && (((x_17 + (-1.0 * _x_x_23)) <= -2.0) && (((x_15 + (-1.0 * _x_x_23)) <= -19.0) && (((x_14 + (-1.0 * _x_x_23)) <= -3.0) && (((x_13 + (-1.0 * _x_x_23)) <= -16.0) && (((x_10 + (-1.0 * _x_x_23)) <= -7.0) && (((x_7 + (-1.0 * _x_x_23)) <= -16.0) && (((x_5 + (-1.0 * _x_x_23)) <= -20.0) && (((x_0 + (-1.0 * _x_x_23)) <= -15.0) && ((x_2 + (-1.0 * _x_x_23)) <= -13.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_23)) == -17.0) || (((x_23 + (-1.0 * _x_x_23)) == -3.0) || (((x_22 + (-1.0 * _x_x_23)) == -20.0) || (((x_21 + (-1.0 * _x_x_23)) == -13.0) || (((x_18 + (-1.0 * _x_x_23)) == -3.0) || (((x_17 + (-1.0 * _x_x_23)) == -2.0) || (((x_15 + (-1.0 * _x_x_23)) == -19.0) || (((x_14 + (-1.0 * _x_x_23)) == -3.0) || (((x_13 + (-1.0 * _x_x_23)) == -16.0) || (((x_10 + (-1.0 * _x_x_23)) == -7.0) || (((x_7 + (-1.0 * _x_x_23)) == -16.0) || (((x_5 + (-1.0 * _x_x_23)) == -20.0) || (((x_0 + (-1.0 * _x_x_23)) == -15.0) || ((x_2 + (-1.0 * _x_x_23)) == -13.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_24)) <= -4.0) && (((x_25 + (-1.0 * _x_x_24)) <= -18.0) && (((x_24 + (-1.0 * _x_x_24)) <= -6.0) && (((x_20 + (-1.0 * _x_x_24)) <= -19.0) && (((x_18 + (-1.0 * _x_x_24)) <= -8.0) && (((x_17 + (-1.0 * _x_x_24)) <= -4.0) && (((x_16 + (-1.0 * _x_x_24)) <= -1.0) && (((x_14 + (-1.0 * _x_x_24)) <= -6.0) && (((x_13 + (-1.0 * _x_x_24)) <= -11.0) && (((x_11 + (-1.0 * _x_x_24)) <= -16.0) && (((x_5 + (-1.0 * _x_x_24)) <= -1.0) && (((x_3 + (-1.0 * _x_x_24)) <= -17.0) && (((x_0 + (-1.0 * _x_x_24)) <= -14.0) && ((x_1 + (-1.0 * _x_x_24)) <= -2.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_24)) == -4.0) || (((x_25 + (-1.0 * _x_x_24)) == -18.0) || (((x_24 + (-1.0 * _x_x_24)) == -6.0) || (((x_20 + (-1.0 * _x_x_24)) == -19.0) || (((x_18 + (-1.0 * _x_x_24)) == -8.0) || (((x_17 + (-1.0 * _x_x_24)) == -4.0) || (((x_16 + (-1.0 * _x_x_24)) == -1.0) || (((x_14 + (-1.0 * _x_x_24)) == -6.0) || (((x_13 + (-1.0 * _x_x_24)) == -11.0) || (((x_11 + (-1.0 * _x_x_24)) == -16.0) || (((x_5 + (-1.0 * _x_x_24)) == -1.0) || (((x_3 + (-1.0 * _x_x_24)) == -17.0) || (((x_0 + (-1.0 * _x_x_24)) == -14.0) || ((x_1 + (-1.0 * _x_x_24)) == -2.0)))))))))))))))) && ((((x_26 + (-1.0 * _x_x_25)) <= -3.0) && (((x_25 + (-1.0 * _x_x_25)) <= -5.0) && (((x_23 + (-1.0 * _x_x_25)) <= -1.0) && (((x_17 + (-1.0 * _x_x_25)) <= -5.0) && (((x_16 + (-1.0 * _x_x_25)) <= -7.0) && (((x_14 + (-1.0 * _x_x_25)) <= -12.0) && (((x_12 + (-1.0 * _x_x_25)) <= -6.0) && (((x_11 + (-1.0 * _x_x_25)) <= -15.0) && (((x_9 + (-1.0 * _x_x_25)) <= -15.0) && (((x_7 + (-1.0 * _x_x_25)) <= -5.0) && (((x_6 + (-1.0 * _x_x_25)) <= -7.0) && (((x_5 + (-1.0 * _x_x_25)) <= -1.0) && (((x_0 + (-1.0 * _x_x_25)) <= -2.0) && ((x_1 + (-1.0 * _x_x_25)) <= -19.0)))))))))))))) && (((x_26 + (-1.0 * _x_x_25)) == -3.0) || (((x_25 + (-1.0 * _x_x_25)) == -5.0) || (((x_23 + (-1.0 * _x_x_25)) == -1.0) || (((x_17 + (-1.0 * _x_x_25)) == -5.0) || (((x_16 + (-1.0 * _x_x_25)) == -7.0) || (((x_14 + (-1.0 * _x_x_25)) == -12.0) || (((x_12 + (-1.0 * _x_x_25)) == -6.0) || (((x_11 + (-1.0 * _x_x_25)) == -15.0) || (((x_9 + (-1.0 * _x_x_25)) == -15.0) || (((x_7 + (-1.0 * _x_x_25)) == -5.0) || (((x_6 + (-1.0 * _x_x_25)) == -7.0) || (((x_5 + (-1.0 * _x_x_25)) == -1.0) || (((x_0 + (-1.0 * _x_x_25)) == -2.0) || ((x_1 + (-1.0 * _x_x_25)) == -19.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_26)) <= -3.0) && (((x_26 + (-1.0 * _x_x_26)) <= -11.0) && (((x_24 + (-1.0 * _x_x_26)) <= -8.0) && (((x_23 + (-1.0 * _x_x_26)) <= -16.0) && (((x_22 + (-1.0 * _x_x_26)) <= -13.0) && (((x_21 + (-1.0 * _x_x_26)) <= -18.0) && (((x_15 + (-1.0 * _x_x_26)) <= -6.0) && (((x_14 + (-1.0 * _x_x_26)) <= -7.0) && (((x_12 + (-1.0 * _x_x_26)) <= -11.0) && (((x_11 + (-1.0 * _x_x_26)) <= -19.0) && (((x_10 + (-1.0 * _x_x_26)) <= -1.0) && (((x_8 + (-1.0 * _x_x_26)) <= -19.0) && (((x_4 + (-1.0 * _x_x_26)) <= -4.0) && ((x_5 + (-1.0 * _x_x_26)) <= -15.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_26)) == -3.0) || (((x_26 + (-1.0 * _x_x_26)) == -11.0) || (((x_24 + (-1.0 * _x_x_26)) == -8.0) || (((x_23 + (-1.0 * _x_x_26)) == -16.0) || (((x_22 + (-1.0 * _x_x_26)) == -13.0) || (((x_21 + (-1.0 * _x_x_26)) == -18.0) || (((x_15 + (-1.0 * _x_x_26)) == -6.0) || (((x_14 + (-1.0 * _x_x_26)) == -7.0) || (((x_12 + (-1.0 * _x_x_26)) == -11.0) || (((x_11 + (-1.0 * _x_x_26)) == -19.0) || (((x_10 + (-1.0 * _x_x_26)) == -1.0) || (((x_8 + (-1.0 * _x_x_26)) == -19.0) || (((x_4 + (-1.0 * _x_x_26)) == -4.0) || ((x_5 + (-1.0 * _x_x_26)) == -15.0)))))))))))))))) && ((((x_27 + (-1.0 * _x_x_27)) <= -12.0) && (((x_25 + (-1.0 * _x_x_27)) <= -16.0) && (((x_21 + (-1.0 * _x_x_27)) <= -12.0) && (((x_20 + (-1.0 * _x_x_27)) <= -13.0) && (((x_19 + (-1.0 * _x_x_27)) <= -16.0) && (((x_18 + (-1.0 * _x_x_27)) <= -4.0) && (((x_16 + (-1.0 * _x_x_27)) <= -11.0) && (((x_15 + (-1.0 * _x_x_27)) <= -4.0) && (((x_12 + (-1.0 * _x_x_27)) <= -8.0) && (((x_11 + (-1.0 * _x_x_27)) <= -16.0) && (((x_9 + (-1.0 * _x_x_27)) <= -18.0) && (((x_8 + (-1.0 * _x_x_27)) <= -1.0) && (((x_3 + (-1.0 * _x_x_27)) <= -10.0) && ((x_4 + (-1.0 * _x_x_27)) <= -18.0)))))))))))))) && (((x_27 + (-1.0 * _x_x_27)) == -12.0) || (((x_25 + (-1.0 * _x_x_27)) == -16.0) || (((x_21 + (-1.0 * _x_x_27)) == -12.0) || (((x_20 + (-1.0 * _x_x_27)) == -13.0) || (((x_19 + (-1.0 * _x_x_27)) == -16.0) || (((x_18 + (-1.0 * _x_x_27)) == -4.0) || (((x_16 + (-1.0 * _x_x_27)) == -11.0) || (((x_15 + (-1.0 * _x_x_27)) == -4.0) || (((x_12 + (-1.0 * _x_x_27)) == -8.0) || (((x_11 + (-1.0 * _x_x_27)) == -16.0) || (((x_9 + (-1.0 * _x_x_27)) == -18.0) || (((x_8 + (-1.0 * _x_x_27)) == -1.0) || (((x_3 + (-1.0 * _x_x_27)) == -10.0) || ((x_4 + (-1.0 * _x_x_27)) == -18.0)))))))))))))))) && ((((_EL_X_2395 == ((_x__EL_U_2394 && ((_x_x_0 + (-1.0 * _x_x_12)) <= 10.0)) || ( !(_x__EL_U_2392 || ( !((_x_x_4 + (-1.0 * _x_x_18)) <= 18.0)))))) && ((_EL_U_2392 == (_x__EL_U_2392 || ( !((_x_x_4 + (-1.0 * _x_x_18)) <= 18.0)))) && (_EL_U_2394 == ((_x__EL_U_2394 && ((_x_x_0 + (-1.0 * _x_x_12)) <= 10.0)) || ( !(_x__EL_U_2392 || ( !((_x_x_4 + (-1.0 * _x_x_18)) <= 18.0)))))))) && (_x__J2411 == (( !(_J2411 && _J2421)) && ((_J2411 && _J2421) || ((( !((x_4 + (-1.0 * x_18)) <= 18.0)) || ( !(( !((x_4 + (-1.0 * x_18)) <= 18.0)) || _EL_U_2392))) || _J2411))))) && (_x__J2421 == (( !(_J2411 && _J2421)) && ((_J2411 && _J2421) || ((( !(( !((x_4 + (-1.0 * x_18)) <= 18.0)) || _EL_U_2392)) || ( !(( !(( !((x_4 + (-1.0 * x_18)) <= 18.0)) || _EL_U_2392)) || (((x_0 + (-1.0 * x_12)) <= 10.0) && _EL_U_2394)))) || _J2421))))));
x_10 = _x_x_10;
_J2421 = _x__J2421;
_J2411 = _x__J2411;
_EL_X_2395 = _x__EL_X_2395;
x_14 = _x_x_14;
x_4 = _x_x_4;
x_3 = _x_x_3;
x_22 = _x_x_22;
x_8 = _x_x_8;
x_23 = _x_x_23;
x_9 = _x_x_9;
x_24 = _x_x_24;
x_11 = _x_x_11;
x_26 = _x_x_26;
x_12 = _x_x_12;
x_13 = _x_x_13;
x_15 = _x_x_15;
_EL_U_2394 = _x__EL_U_2394;
x_16 = _x_x_16;
_EL_U_2392 = _x__EL_U_2392;
x_18 = _x_x_18;
x_19 = _x_x_19;
x_20 = _x_x_20;
x_21 = _x_x_21;
x_1 = _x_x_1;
x_25 = _x_x_25;
x_0 = _x_x_0;
x_27 = _x_x_27;
x_6 = _x_x_6;
x_7 = _x_x_7;
x_2 = _x_x_2;
x_17 = _x_x_17;
x_5 = _x_x_5;
}
}
|
the_stack_data/151706697.c | /*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2016 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. 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. Neither the name of
the Intel Corporation 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 INTEL 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.
END_LEGAL */
/*
* gcc_thread_local_vars_app.c
* This example code checks GCC's __thread variable:
* 1. Each of the threads writes a different value to its own __thread variable
* 2. All threads are synchronized
* 3. Each thread reads the value of the __thread variable and returns it back
* to the main thread
* 4. The main thread prints the values of each thread's variable in order
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <pthread.h>
#define THREADS_COUNT 10
__thread int tid_local[16] = {0};
int barrier = THREADS_COUNT;
pthread_mutex_t barrier_mutex;
pthread_cond_t barrier_threshold_cv;
void Fail(const char* format, ...)
{
va_list args;
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
exit(1);
}
void AddToThreadLocalVar(int i)
{
tid_local[5] += i;
}
void *thread_main(void *ptr)
{
AddToThreadLocalVar(*(int*)ptr);
AddToThreadLocalVar(*(int*)ptr);
pthread_mutex_lock(&barrier_mutex);
if (--barrier <= 0)
{
pthread_cond_signal(&barrier_threshold_cv);
}
pthread_mutex_unlock(&barrier_mutex);
*(int*)ptr = tid_local[5];
return NULL;
}
int main()
{
pthread_t threads[THREADS_COUNT] = {0};
int results[THREADS_COUNT] = {0};
int res = -1;
int i = 0;
res = pthread_mutex_init(&barrier_mutex, NULL);
if (0 != res)
{
Fail("Failed to initialize mutex (error %d)\n", res);
}
res = pthread_cond_init (&barrier_threshold_cv, NULL);
if (0 != res)
{
Fail("Failed to initialize condition variable (error %d)\n", res);
}
for (i = 0; i < THREADS_COUNT; i++)
{
results[i] = i;
res = pthread_create( &threads[i], NULL, thread_main, (void*)&results[i]);
if (0 != res)
{
Fail("Failed to create thread number %d (error %d)\n", i, res);
}
}
pthread_mutex_lock(&barrier_mutex);
/*
* Waits for all the threads to write to their '__thread' variables
*/
while (barrier > 0)
{
pthread_cond_wait(&barrier_threshold_cv, &barrier_mutex);
}
pthread_mutex_unlock(&barrier_mutex);
/*
* Waits for all the threads to terminate, reading their '__thread' variables before
*/
for (i = 0; i < THREADS_COUNT; i++)
{
pthread_join(threads[i], NULL);
printf("TLS%d=%d\n", i, results[i]);
}
pthread_mutex_destroy(&barrier_mutex);
pthread_cond_destroy(&barrier_threshold_cv);
return 0;
}
|
the_stack_data/143923.c | #include "openssl/bn.h"
#include "openssl/sha.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
/* Copyright (C) 2008 Ben Laurie ([email protected]) */
/*
* Implement J-PAKE, as described in
* http://grouper.ieee.org/groups/1363/Research/contributions/hao-ryan-2008.pdf
*
* With hints from http://www.cl.cam.ac.uk/~fh240/software/JPAKE2.java.
*/
static void showbn(const char *name, const BIGNUM *bn)
{
fputs(name, stdout);
fputs(" = ", stdout);
BN_print_fp(stdout, bn);
putc('\n', stdout);
}
typedef struct {
BN_CTX *ctx; // Perhaps not the best place for this?
BIGNUM *p;
BIGNUM *q;
BIGNUM *g;
} JPakeParameters;
static void JPakeParametersInit(JPakeParameters * params)
{
params->ctx = BN_CTX_new();
// For now use p, q, g from Java sample code. Later, generate them.
params->p = NULL;
BN_hex2bn(¶ms->p,
"fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c7");
params->q = NULL;
BN_hex2bn(¶ms->q, "9760508f15230bccb292b982a2eb840bf0581cf5");
params->g = NULL;
BN_hex2bn(¶ms->g,
"f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a");
showbn("p", params->p);
showbn("q", params->q);
showbn("g", params->g);
}
typedef struct {
BIGNUM *gr; // g^r (r random)
BIGNUM *b; // b = r - x*h, h=hash(g, g^r, g^x, name)
} JPakeZKP;
typedef struct {
BIGNUM *gx; // g^x
JPakeZKP zkpx; // ZKP(x)
} JPakeStep1;
typedef struct {
BIGNUM *X; // g^(xa + xc + xd) * xb * s
JPakeZKP zkpxbs; // ZKP(xb * s)
} JPakeStep2;
typedef struct {
const char *name; // Must be unique
int base; // 1 for Alice, 3 for Bob. Only used for
// printing stuff.
JPakeStep1 s1c; // Alice's g^x3, ZKP(x3) or Bob's g^x1,
// ZKP(x1)
JPakeStep1 s1d; // Alice's g^x4, ZKP(x4) or Bob's g^x2,
// ZKP(x2)
JPakeStep2 s2; // Alice's A, ZKP(x2 * s) or Bob's B, ZKP(x4
// * s)
} JPakeUserPublic;
/*
* The user structure. In the definition, (xa, xb, xc, xd) are Alice's
* (x1, x2, x3, x4) or Bob's (x3, x4, x1, x2). If you see what I mean.
*/
typedef struct {
JPakeUserPublic p;
BIGNUM *secret; // The shared secret
BIGNUM *key; // The calculated (shared) key
BIGNUM *xa; // Alice's x1 or Bob's x3
BIGNUM *xb; // Alice's x2 or Bob's x4
} JPakeUser;
// Generate each party's random numbers. xa is in [0, q), xb is in [1, q).
static void genrand(JPakeUser * user, const JPakeParameters * params)
{
BIGNUM *qm1;
// xa in [0, q)
user->xa = BN_new();
BN_rand_range(user->xa, params->q);
// q-1
qm1 = BN_new();
BN_copy(qm1, params->q);
BN_sub_word(qm1, 1);
// ... and xb in [0, q-1)
user->xb = BN_new();
BN_rand_range(user->xb, qm1);
// [1, q)
BN_add_word(user->xb, 1);
// cleanup
BN_free(qm1);
// Show
printf("x%d", user->p.base);
showbn("", user->xa);
printf("x%d", user->p.base + 1);
showbn("", user->xb);
}
static void hashlength(SHA_CTX *sha, size_t l)
{
unsigned char b[2];
assert(l <= 0xffff);
b[0] = l >> 8;
b[1] = l & 0xff;
SHA1_Update(sha, b, 2);
}
static void hashstring(SHA_CTX *sha, const char *string)
{
size_t l = strlen(string);
hashlength(sha, l);
SHA1_Update(sha, string, l);
}
static void hashbn(SHA_CTX *sha, const BIGNUM *bn)
{
size_t l = BN_num_bytes(bn);
unsigned char *bin = alloca(l);
hashlength(sha, l);
BN_bn2bin(bn, bin);
SHA1_Update(sha, bin, l);
}
// h=hash(g, g^r, g^x, name)
static void zkpHash(BIGNUM *h, const JPakeZKP * zkp, const BIGNUM *gx,
const JPakeUserPublic * from,
const JPakeParameters * params)
{
unsigned char md[SHA_DIGEST_LENGTH];
SHA_CTX sha;
// XXX: hash should not allow moving of the boundaries - Java code
// is flawed in this respect. Length encoding seems simplest.
SHA1_Init(&sha);
hashbn(&sha, params->g);
hashbn(&sha, zkp->gr);
hashbn(&sha, gx);
hashstring(&sha, from->name);
SHA1_Final(md, &sha);
BN_bin2bn(md, SHA_DIGEST_LENGTH, h);
}
// Prove knowledge of x
// Note that we don't send g^x because, as it happens, we've always
// sent it elsewhere. Also note that because of that, we could avoid
// calculating it here, but we don't, for clarity...
static void CreateZKP(JPakeZKP * zkp, const BIGNUM *x, const JPakeUser * us,
const BIGNUM *zkpg, const JPakeParameters * params,
int n, const char *suffix)
{
BIGNUM *r = BN_new();
BIGNUM *gx = BN_new();
BIGNUM *h = BN_new();
BIGNUM *t = BN_new();
// r in [0,q)
// XXX: Java chooses r in [0, 2^160) - i.e. distribution not uniform
BN_rand_range(r, params->q);
// g^r
zkp->gr = BN_new();
BN_mod_exp(zkp->gr, zkpg, r, params->p, params->ctx);
// g^x
BN_mod_exp(gx, zkpg, x, params->p, params->ctx);
// h=hash...
zkpHash(h, zkp, gx, &us->p, params);
// b = r - x*h
BN_mod_mul(t, x, h, params->q, params->ctx);
zkp->b = BN_new();
BN_mod_sub(zkp->b, r, t, params->q, params->ctx);
// show
printf(" ZKP(x%d%s)\n", n, suffix);
showbn(" zkpg", zkpg);
showbn(" g^x", gx);
showbn(" g^r", zkp->gr);
showbn(" b", zkp->b);
// cleanup
BN_free(t);
BN_free(h);
BN_free(gx);
BN_free(r);
}
static int VerifyZKP(const JPakeZKP * zkp, BIGNUM *gx,
const JPakeUserPublic * them, const BIGNUM *zkpg,
const JPakeParameters * params, int n,
const char *suffix)
{
BIGNUM *h = BN_new();
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
int ret = 0;
zkpHash(h, zkp, gx, them, params);
// t1 = g^b
BN_mod_exp(t1, zkpg, zkp->b, params->p, params->ctx);
// t2 = (g^x)^h = g^{hx}
BN_mod_exp(t2, gx, h, params->p, params->ctx);
// t3 = t1 * t2 = g^{hx} * g^b = g^{hx+b} = g^r (allegedly)
BN_mod_mul(t3, t1, t2, params->p, params->ctx);
printf(" ZKP(x%d%s)\n", n, suffix);
showbn(" zkpg", zkpg);
showbn(" g^r'", t3);
// verify t3 == g^r
if (BN_cmp(t3, zkp->gr) == 0)
ret = 1;
// cleanup
BN_free(t3);
BN_free(t2);
BN_free(t1);
BN_free(h);
if (ret)
puts(" OK");
else
puts(" FAIL");
return ret;
}
static void sendstep1_substep(JPakeStep1 * s1, const BIGNUM *x,
const JPakeUser * us,
const JPakeParameters * params, int n)
{
s1->gx = BN_new();
BN_mod_exp(s1->gx, params->g, x, params->p, params->ctx);
printf(" g^{x%d}", n);
showbn("", s1->gx);
CreateZKP(&s1->zkpx, x, us, params->g, params, n, "");
}
static void sendstep1(const JPakeUser * us, JPakeUserPublic * them,
const JPakeParameters * params)
{
printf("\n%s sends %s:\n\n", us->p.name, them->name);
// from's g^xa (which becomes to's g^xc) and ZKP(xa)
sendstep1_substep(&them->s1c, us->xa, us, params, us->p.base);
// from's g^xb (which becomes to's g^xd) and ZKP(xb)
sendstep1_substep(&them->s1d, us->xb, us, params, us->p.base + 1);
}
static int verifystep1(const JPakeUser * us, const JPakeUserPublic * them,
const JPakeParameters * params)
{
printf("\n%s verifies %s:\n\n", us->p.name, them->name);
// verify their ZKP(xc)
if (!VerifyZKP(&us->p.s1c.zkpx, us->p.s1c.gx, them, params->g, params,
them->base, ""))
return 0;
// verify their ZKP(xd)
if (!VerifyZKP(&us->p.s1d.zkpx, us->p.s1d.gx, them, params->g, params,
them->base + 1, ""))
return 0;
// g^xd != 1
printf(" g^{x%d} != 1: ", them->base + 1);
if (BN_is_one(us->p.s1d.gx)) {
puts("FAIL");
return 0;
}
puts("OK");
return 1;
}
static void sendstep2(const JPakeUser * us, JPakeUserPublic * them,
const JPakeParameters * params)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
printf("\n%s sends %s:\n\n", us->p.name, them->name);
// X = g^{(xa + xc + xd) * xb * s}
// t1 = g^xa
BN_mod_exp(t1, params->g, us->xa, params->p, params->ctx);
// t2 = t1 * g^{xc} = g^{xa} * g^{xc} = g^{xa + xc}
BN_mod_mul(t2, t1, us->p.s1c.gx, params->p, params->ctx);
// t1 = t2 * g^{xd} = g^{xa + xc + xd}
BN_mod_mul(t1, t2, us->p.s1d.gx, params->p, params->ctx);
// t2 = xb * s
BN_mod_mul(t2, us->xb, us->secret, params->q, params->ctx);
// X = t1^{t2} = t1^{xb * s} = g^{(xa + xc + xd) * xb * s}
them->s2.X = BN_new();
BN_mod_exp(them->s2.X, t1, t2, params->p, params->ctx);
// Show
printf(" g^{(x%d + x%d + x%d) * x%d * s)", us->p.base, them->base,
them->base + 1, us->p.base + 1);
showbn("", them->s2.X);
// ZKP(xb * s)
// XXX: this is kinda funky, because we're using
//
// g' = g^{xa + xc + xd}
//
// as the generator, which means X is g'^{xb * s}
CreateZKP(&them->s2.zkpxbs, t2, us, t1, params, us->p.base + 1, " * s");
// cleanup
BN_free(t1);
BN_free(t2);
}
static int verifystep2(const JPakeUser * us, const JPakeUserPublic * them,
const JPakeParameters * params)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
int ret = 0;
printf("\n%s verifies %s:\n\n", us->p.name, them->name);
// g' = g^{xc + xa + xb} [from our POV]
// t1 = xa + xb
BN_mod_add(t1, us->xa, us->xb, params->q, params->ctx);
// t2 = g^{t1} = g^{xa+xb}
BN_mod_exp(t2, params->g, t1, params->p, params->ctx);
// t1 = g^{xc} * t2 = g^{xc + xa + xb}
BN_mod_mul(t1, us->p.s1c.gx, t2, params->p, params->ctx);
if (VerifyZKP
(&us->p.s2.zkpxbs, us->p.s2.X, them, t1, params, them->base + 1,
" * s"))
ret = 1;
// cleanup
BN_free(t2);
BN_free(t1);
return ret;
}
static void computekey(JPakeUser * us, const JPakeParameters * params)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
printf("\n%s calculates the shared key:\n\n", us->p.name);
// K = (X/g^{xb * xd * s})^{xb}
// = (g^{(xc + xa + xb) * xd * s - xb * xd *s})^{xb}
// = (g^{(xa + xc) * xd * s})^{xb}
// = g^{(xa + xc) * xb * xd * s}
// [which is the same regardless of who calculates it]
// t1 = (g^{xd})^{xb} = g^{xb * xd}
BN_mod_exp(t1, us->p.s1d.gx, us->xb, params->p, params->ctx);
// t2 = -s = q-s
BN_sub(t2, params->q, us->secret);
// t3 = t1^t2 = g^{-xb * xd * s}
BN_mod_exp(t3, t1, t2, params->p, params->ctx);
// t1 = X * t3 = X/g^{xb * xd * s}
BN_mod_mul(t1, us->p.s2.X, t3, params->p, params->ctx);
// K = t1^{xb}
us->key = BN_new();
BN_mod_exp(us->key, t1, us->xb, params->p, params->ctx);
// show
showbn(" K", us->key);
// cleanup
BN_free(t3);
BN_free(t2);
BN_free(t1);
}
int main(int argc, char **argv)
{
JPakeParameters params;
JPakeUser alice, bob;
alice.p.name = "Alice";
alice.p.base = 1;
bob.p.name = "Bob";
bob.p.base = 3;
JPakeParametersInit(¶ms);
// Shared secret
alice.secret = BN_new();
BN_rand(alice.secret, 32, -1, 0);
bob.secret = alice.secret;
showbn("secret", alice.secret);
assert(BN_cmp(alice.secret, params.q) < 0);
// Alice's x1, x2
genrand(&alice, ¶ms);
// Bob's x3, x4
genrand(&bob, ¶ms);
// Now send stuff to each other...
sendstep1(&alice, &bob.p, ¶ms);
sendstep1(&bob, &alice.p, ¶ms);
// And verify what each other sent
if (!verifystep1(&alice, &bob.p, ¶ms))
return 1;
if (!verifystep1(&bob, &alice.p, ¶ms))
return 2;
// Second send
sendstep2(&alice, &bob.p, ¶ms);
sendstep2(&bob, &alice.p, ¶ms);
// And second verify
if (!verifystep2(&alice, &bob.p, ¶ms))
return 3;
if (!verifystep2(&bob, &alice.p, ¶ms))
return 4;
// Compute common key
computekey(&alice, ¶ms);
computekey(&bob, ¶ms);
// Confirm the common key is identical
// XXX: if the two secrets are not the same, everything works up
// to this point, so the only way to detect a failure is by the
// difference in the calculated keys.
// Since we're all the same code, just compare them directly. In a
// real system, Alice sends Bob H(H(K)), Bob checks it, then sends
// back H(K), which Alice checks, or something equivalent.
puts("\nAlice and Bob check keys are the same:");
if (BN_cmp(alice.key, bob.key) == 0)
puts(" OK");
else {
puts(" FAIL");
return 5;
}
return 0;
}
|
the_stack_data/198580297.c | // Check that -dwarf-column-info does not get added to the cc1 line:
// 1) When -gcodeview is present via the clang or clang++ driver
// 2) When /Z7 is present via the cl driver.
// RUN: %clang -### --target=x86_64-windows-msvc -c -g -gcodeview %s 2> %t1
// RUN: FileCheck < %t1 %s
// RUN: %clangxx -### --target=x86_64-windows-msvc -c -g -gcodeview %s 2> %t2
// RUN: FileCheck < %t2 %s
// RUN: %clang_cl -### --target=x86_64-windows-msvc /c /Z7 -- %s 2> %t2
// RUN: FileCheck < %t2 %s
// CHECK: "-cc1"
// CHECK-NOT: "-dwarf-column-info"
|
the_stack_data/282400.c | #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define MSG_LEN 80
bool is_palindrome(const char *message);
int main() {
char message[MSG_LEN + 1];
printf("Enter the message: ");
fgets(message, sizeof(message), stdin);
if (is_palindrome(message))
printf("Palindrome\n");
else
printf("Not a palindrome\n");
return 0;
}
bool is_palindrome(const char *message) {
const char *head = message, *tail = message + strlen(message) - 1;
bool equal = true;
while (head < tail) {
while (!isalpha(*head))
head++;
while (!isalpha(*tail))
tail--;
if (tolower(*head) != tolower(*tail)) {
equal = false;
break;
}
head++;
tail--;
}
return equal;
}
// test: He lived as a devil, eh!
// test: madam, I am Adam. |
the_stack_data/179829919.c | #include <string.h>
#include <stdint.h>
#include <limits.h>
#define SS (sizeof(size_t))
#define ALIGN (sizeof(size_t)-1)
#define ONES ((size_t)-1/UCHAR_MAX)
#define HIGHS (ONES * (UCHAR_MAX/2+1))
#define HASZERO(x) ((x)-ONES & ~(x) & HIGHS)
void *memchr(const void *src, int c, size_t n)
{
const unsigned char *s = src;
c = (unsigned char)c;
for (; n && *s != c; s++, n--);
return n ? (void *)s : (void *)0;
}
|
the_stack_data/37636601.c | /* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0df /* constant vector a */
#define UPPER_MASK 0x80000000 /* most significant w-r bits */
#define LOWER_MASK 0x7fffffff /* least significant r bits */
/* Tempering parameters */
#define TEMPERING_MASK_B 0x9d2c5680
#define TEMPERING_MASK_C 0xefc60000
#define TEMPERING_SHIFT_U(y) (y >> 11)
#define TEMPERING_SHIFT_S(y) (y << 7)
#define TEMPERING_SHIFT_T(y) (y << 15)
#define TEMPERING_SHIFT_L(y) (y >> 18)
#define RAND_MAX 0x7fffffff
static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
/* initializing the array with a NONZERO seed */
void
sgenrand(unsigned long seed)
{
/* setting initial seeds to mt[N] using */
/* the generator Line 25 of Table 1 in */
/* [KNUTH 1981, The Art of Computer Programming */
/* Vol. 2 (2nd Ed.), pp102] */
mt[0]= seed & 0xffffffff;
for (mti=1; mti<N; mti++)
mt[mti] = (69069 * mt[mti-1]) & 0xffffffff;
}
long /* for integer generation */
genrand()
{
unsigned long y;
static unsigned long mag01[2]={0x0, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
int kk;
if (mti == N+1) /* if sgenrand() has not been called, */
sgenrand(4357); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
mti = 0;
}
y = mt[mti++];
y ^= TEMPERING_SHIFT_U(y);
y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
y ^= TEMPERING_SHIFT_L(y);
// Strip off uppermost bit because we want a long,
// not an unsigned long
return y & RAND_MAX;
}
// Assumes 0 <= max <= RAND_MAX
// Returns in the half-open interval [0, max]
long random_at_most(long max) {
unsigned long
// max <= RAND_MAX < ULONG_MAX, so this is okay.
num_bins = (unsigned long) max + 1,
num_rand = (unsigned long) RAND_MAX + 1,
bin_size = num_rand / num_bins,
defect = num_rand % num_bins;
long x;
do {
x = genrand();
}
// This is carefully written not to overflow
while (num_rand - defect <= (unsigned long)x);
// Truncated division is intentional
return x/bin_size;
}
int randomrange(int low, int high){
if(high<low){
int temp=high;
high=low;
low=temp;
}
int val = random_at_most(high-low) + low;
return val;
}
|
the_stack_data/182952364.c | /***********************************************************************
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
* Copyright (C) 2001 by New Riders Publishing *
* See COPYRIGHT for license information. *
***********************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
/* Write COUNT copies of MESSAGE to STREAM, pausing for a second
between each. */
void writer (const char* message, int count, FILE* stream)
{
for (; count > 0; --count) {
/* Write the message to the stream, and send it off immediately. */
fprintf (stream, "%s\n", message);
fflush (stream);
/* Snooze a while. */
sleep (1);
}
}
/* Read random strings from the stream as long as possible. */
void reader (FILE* stream)
{
char buffer[1024];
/* Read until we hit the end of the stream. fgets reads until
either a newline or the end-of-file. */
while (!feof (stream)
&& !ferror (stream)
&& fgets (buffer, sizeof (buffer), stream) != NULL)
fputs (buffer, stdout);
}
int main ()
{
int fds[2];
pid_t pid;
/* Create a pipe. File descriptors for the two ends of the pipe are
placed in fds. */
pipe (fds);
/* Fork a child process. */
pid = fork ();
if (pid == (pid_t) 0) {
FILE* stream;
/* This is the child process. Close our copy of the write end of
the file descriptor. */
close (fds[1]);
/* Convert the read file descriptor to a FILE object, and read
from it. */
stream = fdopen (fds[0], "r");
reader (stream);
close (fds[0]);
}
else {
/* This is the parent process. */
FILE* stream;
/* Close our copy of the read end of the file descriptor. */
close (fds[0]);
/* Convert the write file descriptor to a FILE object, and write
to it. */
stream = fdopen (fds[1], "w");
writer ("Hello, world.", 5, stream);
close (fds[1]);
}
return 0;
}
|
the_stack_data/15762878.c | /*****************************
* @Createdby likelove
* @contact [email protected]
* @date 2021/5/22
* @desc ${desc}
******************************/
#include <stdio.h>
int main() {
int arr[] = {
1, 2, 3, 5, 6, 7
};
for (int i = 1; i <= 100; i++) {
printf("%d\n", i);
}
} |
the_stack_data/22012281.c | #include <stdio.h>
void print_elements(int*, int);
int main() {
int n;
scanf("%d", &n);
int arr[n];
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
print_elements(arr, n - 1);
return 0;
}
void print_elements(int* arr, int len) {
for(int i = len; i >= 0; i--) {
printf("%d\n", arr[i]);
}
}
|
the_stack_data/141470.c | //
// Created by zhang on 2017/1/1.
//
//union [union tag]
//{
// member definition;
// member definition;
// ...
// member definition;
//} [one or more union variables];
#include <memory.h>
#include <stdio.h>
//共用体
int union_main(){
union Data{
int i;
float f;
char c[20];
}datas;
union Data data;
data.i = 1;
printf("%d\n",data.i);
data.f = 10L;
printf("%lf\n",data.f);
strcpy(data.c,"zing");
printf("%s\n",data.c);
datas.i = 11;
printf("%d\n",datas.i);
datas.f = 12L;
printf("%f\n",datas.f);
strcpy(datas.c,"Hello World");
printf("%s\n",datas.c);
} |
the_stack_data/166336.c | /*
*File name:
*Source file name:
*Author: Tamkien Cao
*Last modified: Tue, Feb 26th, 2019
*Version: 2.0
*Changelog:
- Used function.
*Other info:
-This is the 20th exercise from the workshop.
-[README] The idea had been hacked from http://bit.do/eGvJu
**/
#include<stdio.h>
#include<stdlib.h>
int LCM(int a, int b)
{
int x;
while (1)//always true
{
x = a % b;
if (x == 0)
{
break;//see the reason in the link.
}
else
{
a = b;
b = x;
}
}
return b;
}
main()
{
int a, b;
printf("This program can find out the largest common multiplier (LCM) of two numbers.\n");
do
{
printf("Insert the greater number here, enter 0 to exit:\n");
scanf_s("%d", &a);
if (a == 0)
{
break;
}
else
{
printf("Insert the smaller number here:\n");
scanf_s("%d", &b);
if (b > a)
{
printf("Hey, enter the greater number first.\n");
}
else
{
printf("The LCM of your numbers is %d.\n", LCM(a, b));
}
}
} while (1);
printf("\n=================================\n");
printf("Written by Tamkien Cao. Thank you for using my application!\n");
//credit line, neu xoa dong nay ctrinh se ko chay duoc;
system("pause");
}
|
the_stack_data/93888507.c | /* Checks for a bug where static data with a section attribute within a
function would stop the function being partitioned into hot and cold
blocks. */
/* { dg-require-effective-target freorder } */
/* { dg-options "-O2 -fno-profile-reorder-functions -freorder-blocks-and-partition -save-temps" } */
#define SIZE 10000
#define NOINLINE __attribute__((noinline)) __attribute__ ((noclone))
const char *sarr[SIZE];
const char *buf_hot;
const char *buf_cold;
void foo (int path);
int
main (int argc, char *argv[])
{
int i;
buf_hot = "hello";
buf_cold = "world";
for (i = 0; i < 1000000; i++)
foo (argc);
return 0;
}
void NOINLINE
foo (int path)
{
static int i __attribute__((section(".data")));
if (path)
{
for (i = 0; i < SIZE; i++)
sarr[i] = buf_hot;
}
else
{
for (i = 0; i < SIZE; i++)
sarr[i] = buf_cold;
}
}
/* { dg-final-use { scan-assembler "\.section\[\t \]*\.text\.unlikely\[\\n\\r\]+\[\t \]*\.size\[\t \]*foo\.cold\.0" { target *-*-linux* *-*-gnu* } } } */
|
the_stack_data/175144082.c | /*-
* Copyright (c)1999 Citrus 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* citrus Id: wcspbrk.c,v 1.2 2000/12/21 05:07:25 itojun Exp
* $FreeBSD: head/lib/libc/string/wcspbrk.c 188080 2009-02-03 17:58:20Z danger $
*/
#include <wchar.h>
wchar_t *
wcspbrk(const wchar_t *s, const wchar_t *set)
{
const wchar_t *p;
const wchar_t *q;
p = s;
while (*p) {
q = set;
while (*q) {
if (*p == *q) {
/* LINTED interface specification */
return (wchar_t *)p;
}
q++;
}
p++;
}
return NULL;
}
|
the_stack_data/237644085.c | #include <stdio.h>
#include <stdlib.h>
void LerArray(int numElementos , float * elemArray) {
for (int i = 0; i < numElementos; i++) {
float num;
printf("Digite um numero para seu array: ");
scanf("%f", &num);
*(elemArray + i) = num;
printf("\n\n");
}
}
int main() {
int numElementos;
printf("Oi !!! Quantos elementos vc quer armazenar: ");
scanf("%d", &numElementos);
system("clear");
float * vetorNum;
vetorNum = malloc(numElementos * sizeof(float));
if (vetorNum == NULL) {
printf("Erro na alocação, talvez funcione um um número de elementos menor ");
return 1;
}
LerArray(numElementos, vetorNum);
free(vetorNum);
}
//https://pt.stackoverflow.com/q/55328/101
|
the_stack_data/22013109.c | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define QSIZE 10
#define LOOP 50
typedef struct{
int data[QSIZE];
int index;
int count;
pthread_mutex_t lock;
pthread_cond_t notfull;
pthread_cond_t notempty;
} queue_t;
queue_t *qinit();
void qdelete(queue_t *q);
void *produce(void *args);
void *consume (void *args);
void put_data(queue_t *q, int d);
int get_data(queue_t *q);
int seed;
int main()
{
queue_t *q;
pthread_t producer, consumer;
seed = time(NULL);
q = qinit();
pthread_create(&consumer, NULL, consume, (void *)q);
pthread_create(&producer, NULL, produce, (void *)q);
pthread_join(producer, NULL);
pthread_join(consumer, NULL);
qdelete(q);
}
queue_t *qinit()
{
queue_t *q;
q = (queue_t *)malloc(sizeof(queue_t));
q->index = q->count = 0;
//Dynamic mutex initialization(lock, full, empty)
//OK
pthread_mutex_init (&q->lock, (pthread_mutexattr_t *)NULL);
pthread_cond_init (&q->notempty, (pthread_condattr_t *)NULL);
pthread_cond_init (&q->notfull, (pthread_condattr_t *)NULL);
return q;
}
void qdelete(queue_t *q)
{
//destroy mutex & condition
//OK
printf("qdelete!\n");
pthread_mutex_destroy (&(q->lock));
pthread_cond_destroy(&(q->notempty));
pthread_cond_destroy(&(q->notfull));
//free queue
//OK
free(q);
}
void *produce(void *args)
{
int i, d;
queue_t *q = (queue_t *)args;
for(i=0;i<LOOP;i++)
{
d = rand_r(&seed) % 10;
printf("put data %d to queue\n", d);
put_data(q, d);
printf("put data %d to queue\n", d);
}
pthread_exit(NULL);
}
void *consume(void *args)
{
int i, d;
queue_t *q = (queue_t *)args;
for(i=0;i<LOOP;i++)
{
d = get_data(q);
printf("got data %d from queue\n", d);
}
pthread_exit(NULL);
}
void put_data(queue_t *q, int d)
{
//lock
//OK
pthread_mutex_lock(&q->lock);
printf("put : mutex is locked!\n");
//conditional wait (when q is full)
//pthread_cond_wait() : to block on a condition variable
//atomically release mutex and cause the calling thread to block on the condition variable
//access by another thread to the mutex and then the condition variable
//acqure the mutex after the about-to-block thread has released it
//OK...?
printf("%d is q size\n", q->count);
if(q->count==QSIZE){
/*q가 가득 차 있을때*/
pthread_cond_wait(&q->notfull,&q->lock);
}
q->data[(q->index + q->count) % QSIZE] = d;
q->count++;
//signal
pthread_cond_signal (&q->notempty);
//unlock
//OK
printf("put : mutex is unlocked!\n");
pthread_mutex_unlock(&q->lock);
}
int get_data(queue_t *q)
{
int d;
//lock
pthread_mutex_lock(&q->lock);
printf("got : mutex is locked!\n");
//condition wait (when q is empty)
if(q->count==0)
//wait를 하면 lock이 풀림!
pthread_cond_wait(&q->notempty,&q->lock);
d = q->data[q->index];
q->index = (q->index + 1) % QSIZE;
q->count--;
//signal
pthread_cond_signal(&q->notfull);
//unlock
pthread_mutex_unlock(&q->lock);
printf("got : mutex is unlocked!\n");
return d;
}
|
the_stack_data/48249.c | #include <string.h>
extern char *getenv(const char *name);
extern int foo();
extern int bar();
int
main()
{
char *tainted = getenv("hi");
char t[3];
memcpy(t, tainted, 3);
char *also_tainted = t;
return 0;
}
|
the_stack_data/20449539.c | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL,"");
int tamanho = 0, repeat = 0, palavra = 0; wchar_t word[266];
scanf("%ls", (word));
while (word[repeat] != '\0')
{
palavra ++;
word[repeat] = tolower(word[repeat]);
repeat ++;
}
for (repeat = 0; repeat < palavra / 2; repeat ++)
{
if (word[repeat] != word[palavra - (repeat + 1)])
{
printf("NAO\n");
return(0);
}
else
{
tamanho ++;
}
}
printf("SIM\n%d\n", tamanho);
return(0);
}
|
the_stack_data/206392343.c | #include <stdio.h>
int main(){
void function1(int * val){
int b = 0;
val = &b; //ERLAUBT
*val = 8;//ERLAUBT
}
//Die Adresse des übergebenen Pointers darf nicht verändert werden
//Der Wert an der Adresse darf wohl verändert werden
void function2(const int * val){
int b = 0;
val = &b; //ERLAUBT
//*val = 8;//NICHT ERLAUBT
}
//Die Adresse des übergebenen Pointers darf nicht verändert werden
//Der Wert an der Adresse darf ebenfalls nicht verändert werden
void function(const int * const val){
int b = 0;
//val = &b; //NICHT ERLAUBT
//*val = 8;//NICHT ERLAUBT
}
return 0;
}
|
the_stack_data/247016870.c | // autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <dirent.h>
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <setjmp.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/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <sched.h>
#include <linux/genetlink.h>
#include <linux/if_addr.h>
#include <linux/if_link.h>
#include <linux/in6.h>
#include <linux/neighbour.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/veth.h>
static __thread int skip_segv;
static __thread jmp_buf segv_env;
static void segv_handler(int sig, siginfo_t* info, void* ctx)
{
uintptr_t addr = (uintptr_t)info->si_addr;
const uintptr_t prog_start = 1 << 20;
const uintptr_t prog_end = 100 << 20;
if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) &&
(addr < prog_start || addr > prog_end)) {
_longjmp(segv_env, 1);
}
exit(sig);
}
static void install_segv_handler(void)
{
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = SIG_IGN;
syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8);
syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8);
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = segv_handler;
sa.sa_flags = SA_NODEFER | SA_SIGINFO;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGBUS, &sa, NULL);
}
#define NONFAILING(...) \
{ \
__atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \
if (_setjmp(segv_env) == 0) { \
__VA_ARGS__; \
} \
__atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \
}
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;
}
struct nlmsg {
char* pos;
int nesting;
struct nlattr* nested[8];
char buf[1024];
};
static struct nlmsg nlmsg;
static void netlink_init(struct nlmsg* nlmsg, 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(struct nlmsg* nlmsg, 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 int netlink_send_ext(struct nlmsg* nlmsg, int sock, uint16_t reply_type,
int* reply_len)
{
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 (hdr->nlmsg_type == NLMSG_DONE) {
*reply_len = 0;
return 0;
}
if (n < sizeof(struct nlmsghdr))
exit(1);
if (reply_len && hdr->nlmsg_type == reply_type) {
*reply_len = n;
return 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 int netlink_send(struct nlmsg* nlmsg, int sock)
{
return netlink_send_ext(nlmsg, sock, 0, NULL);
}
static int netlink_next_msg(struct nlmsg* nlmsg, unsigned int offset,
unsigned int total_len)
{
struct nlmsghdr* hdr = (struct nlmsghdr*)(nlmsg->buf + offset);
if (offset == total_len || offset + hdr->nlmsg_len > total_len)
return -1;
return hdr->nlmsg_len;
}
static void netlink_device_change(struct nlmsg* nlmsg, int sock,
const char* name, bool up, const char* master,
const void* mac, int macsize,
const char* new_name)
{
struct ifinfomsg hdr;
memset(&hdr, 0, sizeof(hdr));
if (up)
hdr.ifi_flags = hdr.ifi_change = IFF_UP;
hdr.ifi_index = if_nametoindex(name);
netlink_init(nlmsg, RTM_NEWLINK, 0, &hdr, sizeof(hdr));
if (new_name)
netlink_attr(nlmsg, IFLA_IFNAME, new_name, strlen(new_name));
if (master) {
int ifindex = if_nametoindex(master);
netlink_attr(nlmsg, IFLA_MASTER, &ifindex, sizeof(ifindex));
}
if (macsize)
netlink_attr(nlmsg, IFLA_ADDRESS, mac, macsize);
int err = netlink_send(nlmsg, sock);
(void)err;
}
const int kInitNetNsFd = 239;
#define DEVLINK_FAMILY_NAME "devlink"
#define DEVLINK_CMD_PORT_GET 5
#define DEVLINK_CMD_RELOAD 37
#define DEVLINK_ATTR_BUS_NAME 1
#define DEVLINK_ATTR_DEV_NAME 2
#define DEVLINK_ATTR_NETDEV_NAME 7
#define DEVLINK_ATTR_NETNS_FD 138
static int netlink_devlink_id_get(struct nlmsg* nlmsg, int sock)
{
struct genlmsghdr genlhdr;
struct nlattr* attr;
int err, n;
uint16_t id = 0;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = CTRL_CMD_GETFAMILY;
netlink_init(nlmsg, GENL_ID_CTRL, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(nlmsg, CTRL_ATTR_FAMILY_NAME, DEVLINK_FAMILY_NAME,
strlen(DEVLINK_FAMILY_NAME) + 1);
err = netlink_send_ext(nlmsg, sock, GENL_ID_CTRL, &n);
if (err) {
return -1;
}
attr = (struct nlattr*)(nlmsg->buf + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg->buf + n;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == CTRL_ATTR_FAMILY_ID) {
id = *(uint16_t*)(attr + 1);
break;
}
}
if (!id) {
return -1;
}
recv(sock, nlmsg->buf, sizeof(nlmsg->buf), 0); /* recv ack */
return id;
}
static void netlink_devlink_netns_move(const char* bus_name,
const char* dev_name, int netns_fd)
{
struct genlmsghdr genlhdr;
int sock;
int id, err;
sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_RELOAD;
netlink_init(&nlmsg, id, 0, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_NETNS_FD, &netns_fd, sizeof(netns_fd));
err = netlink_send(&nlmsg, sock);
if (err) {
}
error:
close(sock);
}
static struct nlmsg nlmsg2;
static void initialize_devlink_ports(const char* bus_name, const char* dev_name,
const char* netdev_prefix)
{
struct genlmsghdr genlhdr;
int len, total_len, id, err, offset;
uint16_t netdev_index;
int sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_GENERIC);
if (sock == -1)
exit(1);
int rtsock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (rtsock == -1)
exit(1);
id = netlink_devlink_id_get(&nlmsg, sock);
if (id == -1)
goto error;
memset(&genlhdr, 0, sizeof(genlhdr));
genlhdr.cmd = DEVLINK_CMD_PORT_GET;
netlink_init(&nlmsg, id, NLM_F_DUMP, &genlhdr, sizeof(genlhdr));
netlink_attr(&nlmsg, DEVLINK_ATTR_BUS_NAME, bus_name, strlen(bus_name) + 1);
netlink_attr(&nlmsg, DEVLINK_ATTR_DEV_NAME, dev_name, strlen(dev_name) + 1);
err = netlink_send_ext(&nlmsg, sock, id, &total_len);
if (err) {
goto error;
}
offset = 0;
netdev_index = 0;
while ((len = netlink_next_msg(&nlmsg, offset, total_len)) != -1) {
struct nlattr* attr = (struct nlattr*)(nlmsg.buf + offset + NLMSG_HDRLEN +
NLMSG_ALIGN(sizeof(genlhdr)));
for (; (char*)attr < nlmsg.buf + offset + len;
attr = (struct nlattr*)((char*)attr + NLMSG_ALIGN(attr->nla_len))) {
if (attr->nla_type == DEVLINK_ATTR_NETDEV_NAME) {
char* port_name;
char netdev_name[IFNAMSIZ];
port_name = (char*)(attr + 1);
snprintf(netdev_name, sizeof(netdev_name), "%s%d", netdev_prefix,
netdev_index);
netlink_device_change(&nlmsg2, rtsock, port_name, true, 0, 0, 0,
netdev_name);
break;
}
}
offset += len;
netdev_index++;
}
error:
close(rtsock);
close(sock);
}
static void initialize_devlink_pci(void)
{
int netns = open("/proc/self/ns/net", O_RDONLY);
if (netns == -1)
exit(1);
int ret = setns(kInitNetNsFd, 0);
if (ret == -1)
exit(1);
netlink_devlink_netns_move("pci", "0000:00:10.0", netns);
ret = setns(netns, 0);
if (ret == -1)
exit(1);
close(netns);
initialize_devlink_ports("pci", "0000:00:10.0", "netpci");
}
static long syz_open_dev(volatile long a0, volatile long a1, volatile long a2)
{
if (a0 == 0xc || a0 == 0xb) {
char buf[128];
sprintf(buf, "/dev/%s/%d:%d", a0 == 0xc ? "char" : "block", (uint8_t)a1,
(uint8_t)a2);
return open(buf, O_RDWR, 0);
} else {
char buf[1024];
char* hash;
NONFAILING(strncpy(buf, (char*)a0, sizeof(buf) - 1));
buf[sizeof(buf) - 1] = 0;
while ((hash = strchr(buf, '#'))) {
*hash = '0' + (char)(a1 % 10);
a1 /= 10;
}
return open(buf, a2, 0);
}
}
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);
int i;
for (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;
for (iter = 0;; 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[3] = {0x0, 0xffffffffffffffff, 0xffffffffffffffff};
void execute_one(void)
{
intptr_t res = 0;
syscall(__NR_creat, 0ul, 0ul);
syscall(__NR_write, -1, 0ul, 0xb18ffbffc48ec12ul);
syscall(__NR_setsockopt, -1, 1ul, 0x11ul, 0ul, 0ul);
syscall(__NR_keyctl, 0x16ul, 0, 0, 0, 0);
syscall(__NR_getgid);
syscall(__NR_ioctl, -1, 0x5423ul, 0ul);
syscall(__NR_splice, -1, 0ul, -1, 0ul, 0ul, 8ul);
syscall(__NR_gettid);
res = syscall(__NR_getgid);
if (res != -1)
r[0] = res;
syscall(__NR_setfsgid, r[0]);
syscall(__NR_sendto, -1, 0ul, 0ul, 0ul, 0ul, 0ul);
syz_open_dev(0, 0xfffffffffffffeff, 0);
syscall(__NR_sendto, -1, 0ul, 0ul, 0x200007fful, 0ul, 0ul);
syscall(__NR_splice, -1, 0ul, -1, 0ul, 0ul, 8ul);
syscall(__NR_openat, 0xffffffffffffff9cul, 0ul, 0ul, 0ul);
res = syscall(__NR_openat, 0xffffffffffffff9cul, 0ul, 0ul, 0ul);
if (res != -1)
r[1] = res;
syscall(__NR_ioctl, r[1], 0x5423ul, 0ul);
syscall(__NR_openat, 0xffffffffffffff9cul, 0ul, 0ul, 0ul);
syscall(__NR_gettid);
syscall(__NR_setsockopt, -1, 1ul, 0x11ul, 0ul, 0ul);
syscall(__NR_socket, 2ul, 0ul, 0);
syscall(__NR_sendto, -1, 0ul, 0ul, 0ul, 0ul, 0ul);
syscall(__NR_fstat, -1, 0ul);
syscall(__NR_add_key, 0ul, 0ul, 0ul, 0ul, 0);
syscall(__NR_splice, -1, 0ul, -1, 0ul, 0ul, 0ul);
syscall(__NR_perf_event_open, 0ul, 0, 0ul, -1, 0ul);
syscall(__NR_openat, 0xffffffffffffff9cul, 0ul, 2ul, 0ul);
NONFAILING(memcpy((void*)0x20000040, "/dev/ptmx\000", 10));
res = syscall(__NR_openat, 0xffffffffffffff9cul, 0x20000040ul, 0ul, 0ul);
if (res != -1)
r[2] = res;
NONFAILING(*(uint32_t*)0x200001c0 = 0x11);
inject_fault(6);
syscall(__NR_ioctl, r[2], 0x5423ul, 0x200001c0ul);
}
int main(void)
{
syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0);
setup_fault();
install_segv_handler();
loop();
return 0;
}
|
the_stack_data/90105.c | #include <stdio.h>
struct sty {
int f;
};
struct sty s;
int foo(struct sty *p) {
p->f ++;
return 0;
}
int bar(struct sty *u) {
bar(u);
return 0;
}
int see(struct sty *x) {
foo(x);
return 0;
}
int main(int argc, char** argv) {
if (argc < 2) return 0;
s.f = 0;
FILE *f = fopen(argv[1], "r");
struct sty *p[2];
p[0] = &s;
p[1] = &s;
if (f == NULL) return 0;
int x;
fscanf(f, "%d", &x);
fclose(f);
for (int i = 0; i < x; i++)
see(p[0]);
for (int i = 0; i < x; i++)
bar(p[1]);
printf("%d\n", s.f);
return 0;
}
|
the_stack_data/98574904.c | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 邓俊兴 (Deng Junxing)
* Email : [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#define CLIENTSIZE 50
#define BUFFERSIZE 512
char ch_char(char c) {
if(c >= 'a' && c <= 'z')
return c - 32;
return c;
}
int main(int argc, char **argv){
if(argc != 2){
fprintf(stderr, " usage :%s port !\n", argv[0]);
exit(1);
}
int server_listen, sockfd, max_fd;
int client[CLIENTSIZE] = {0};
memset(client, -1, sizeof(client));
if ((server_listen = socket_create(argv[1])) < 0)
{
perror("socket_create");
exit(1);
}
make_nonblock(server_listen);//转换为非阻塞状态
fd_set rfds, wfds, efds;
max_fd = server_listen;
int i = 0;
while (1) {
FD_ZERO(&rfds);
FD_ZERO(&wfds);
FD_ZERO(&efds);
FD_SET(server_listen, &rfds);
for(i = 0 ; i < CLIENTSIZE; i++){
if(client[i] == server_listen){
continue;
}
if(client[i] > 0) {//有效的文件描述符
if(max_fd < client[i]) max_fd = client[i];
FD_SET(client[i], &rfds);
}
}
if(select(max_fd + 1, &rfds, NULL, NULL, NULL) < 0){
perror("select");
return 1;
}
if(FD_ISSET(server_listen, &rfds)) {
printf("connect ready on server_listen!\n");
if((sockfd = accept(server_listen, NULL, NULL)) < 0){
perror("accept");
return 1;
}
if(sockfd > CLIENTSIZE){
printf("too many clients!\n");
close(sockfd);
}else{
make_nonblock(sockfd);
if(client[sockfd] == -1)
client[sockfd] = sockfd;
}
}
for(i = 0; i < CLIENTSIZE; i++) {
if(i == server_listen) continue;
if(FD_ISSET(i, &rfds)) {
char buffer[BUFFERSIZE] = {0};
int retval = recv(i ,buffer, BUFFERSIZE, 0);
if(retval <= 0){
printf("logout!\n");
client[i] = -1;
close(1);
continue;
}
printf("recev : %s", buffer);
int j = 0;
for(j = 0; j < strlen(buffer); j++) {
buffer[j] = ch_char(buffer[j]);
}
send(i, buffer, strlen(buffer), 0);
}
}
}
return 0;
}
|
the_stack_data/28262933.c | #include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
if (c == '\t')
printf("\\t");
if (c == '\\')
printf("\\\\");
if (c != '\t' && c != '\\')
putchar(c);
}
}
|
the_stack_data/535.c | #include <stdio.h>
int main() {
char ac[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,};
char *p = ac;
char *p1 = &ac[5];
printf("p =%p\n", p);
printf("p+1=%p\n", p + 1);
printf("p1=%p\n", p1);
printf("p1-p=%d\n", p1 - p);
int ai[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,};
int *q = ai;
int *q1 = &ai[6];
printf("q =%p\n", q);
printf("q+1=%p\n", q + 1);
printf("q1=%p\n", q1);
printf("q1-q=%d\n", q1 - q);
return 0;
} |
the_stack_data/111838.c |
float A[1024][1024];
float B[1024][1024];
float C[1024][1024];
float AA[1024][1024];
float BB[1024][1024];
float CC[1024][1024];
float alpha = 1.1;
float beta = 1.1;
int main(void) {
#pragma scop
for (int i = 0; i < 1024; i++)
for (int j = 0; j < 1024; j++)
{
C[i][j] *= beta;
for (int k = 0; k < 1024; ++k)
C[i][j] += alpha * A[i][k] * B[k][j];
}
#pragma endscop
/*
#pragma scop
for (int i = 0; i < 1024; i++)
for (int j = 0; j < 1024; j++)
{
for (int k = 0; k < 1024; ++k)
C[i][j] += alpha * A[i][k] * B[k][j];
}
#pragma endscop
*/
/*
#pragma scop
for (int i = 0; i < 1024; i++)
for (int j = 0; j < 1024; j++)
C[i][j] *= beta;
for (int i = 0; i < 1024; ++i)
for (int k = 0; k < 1024; k++)
for (int j = 0; j < 1024; j++)
C[i][j] += alpha * A[i][k] * B[k][j];
for (int i = 0; i < 1024; i++)
for (int j = 0; j < 1024; j++)
CC[i][j] *= beta;
for (int i = 0; i < 1024; ++i)
for (int k = 0; k < 1024; k++)
for (int j = 0; j < 1024; j++)
CC[i][j] += alpha * AA[i][k] * BB[k][j];
#pragma endscop
*/
return 0;
}
|
the_stack_data/57305.c | #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;
#ifdef _MSC_VER
static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;}
static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;}
static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;}
static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;}
#else
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;}
#endif
#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)); }
#ifdef _MSC_VER
#define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);}
#define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);}
#else
#define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);}
#define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);}
#endif
#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) = conjf(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) (cimagf(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;
}
#ifdef _MSC_VER
static _Fcomplex cpow_ui(complex x, integer n) {
complex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i;
for(u = n; ; ) {
if(u & 01) pow.r *= x.r, pow.i *= x.i;
if(u >>= 1) x.r *= x.r, x.i *= x.i;
else break;
}
}
_Fcomplex p={pow.r, pow.i};
return p;
}
#else
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;
}
#endif
#ifdef _MSC_VER
static _Dcomplex zpow_ui(_Dcomplex x, integer n) {
_Dcomplex pow={1.0,0.0}; unsigned long int u;
if(n != 0) {
if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1];
for(u = n; ; ) {
if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1];
if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1];
else break;
}
}
_Dcomplex p = {pow._Val[0], pow._Val[1]};
return p;
}
#else
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;
}
#endif
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;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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;
}
#endif
static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Fcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0];
zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0];
zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1];
}
}
pCf(z) = zdotc;
}
#else
_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;
}
#endif
static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) {
integer n = *n_, incx = *incx_, incy = *incy_, i;
#ifdef _MSC_VER
_Dcomplex zdotc = {0.0, 0.0};
if (incx == 1 && incy == 1) {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0];
zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1];
}
} else {
for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */
zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0];
zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1];
}
}
pCd(z) = zdotc;
}
#else
_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 DLA_SYRPVGRW computes the reciprocal pivot growth factor norm(A)/norm(U) for a symmetric indefi
nite matrix. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download DLA_SYRPVGRW + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dla_syr
pvgrw.f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dla_syr
pvgrw.f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dla_syr
pvgrw.f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* DOUBLE PRECISION FUNCTION DLA_SYRPVGRW( UPLO, N, INFO, A, LDA, AF, */
/* LDAF, IPIV, WORK ) */
/* CHARACTER*1 UPLO */
/* INTEGER N, INFO, LDA, LDAF */
/* INTEGER IPIV( * ) */
/* DOUBLE PRECISION A( LDA, * ), AF( LDAF, * ), WORK( * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > */
/* > DLA_SYRPVGRW computes the reciprocal pivot growth factor */
/* > norm(A)/norm(U). The "f2cmax absolute element" norm is used. If this is */
/* > much less than 1, the stability of the LU factorization of the */
/* > (equilibrated) matrix A could be poor. This also means that the */
/* > solution X, estimated condition numbers, and error bounds could be */
/* > unreliable. */
/* > \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 number of linear equations, i.e., the order of the */
/* > matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] INFO */
/* > \verbatim */
/* > INFO is INTEGER */
/* > The value of INFO returned from DSYTRF, .i.e., the pivot in */
/* > column INFO is exactly 0. */
/* > \endverbatim */
/* > */
/* > \param[in] A */
/* > \verbatim */
/* > A is DOUBLE PRECISION array, dimension (LDA,N) */
/* > On entry, the N-by-N matrix A. */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] AF */
/* > \verbatim */
/* > AF is DOUBLE PRECISION array, dimension (LDAF,N) */
/* > The block diagonal matrix D and the multipliers used to */
/* > obtain the factor U or L as computed by DSYTRF. */
/* > \endverbatim */
/* > */
/* > \param[in] LDAF */
/* > \verbatim */
/* > LDAF is INTEGER */
/* > The leading dimension of the array AF. LDAF >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > Details of the interchanges and the block structure of D */
/* > as determined by DSYTRF. */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is DOUBLE PRECISION array, dimension (2*N) */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date December 2016 */
/* > \ingroup doubleSYcomputational */
/* ===================================================================== */
doublereal dla_syrpvgrw_(char *uplo, integer *n, integer *info, doublereal *
a, integer *lda, doublereal *af, integer *ldaf, integer *ipiv,
doublereal *work)
{
/* System generated locals */
integer a_dim1, a_offset, af_dim1, af_offset, i__1, i__2;
doublereal ret_val, d__1, d__2, d__3;
/* Local variables */
doublereal amax, umax;
integer i__, j, k;
extern logical lsame_(char *, char *);
integer ncols;
logical upper;
integer kp;
doublereal rpvgrw, tmp;
/* -- 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 */
/* ===================================================================== */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
af_dim1 = *ldaf;
af_offset = 1 + af_dim1 * 1;
af -= af_offset;
--ipiv;
--work;
/* Function Body */
upper = lsame_("Upper", uplo);
if (*info == 0) {
if (upper) {
ncols = 1;
} else {
ncols = *n;
}
} else {
ncols = *info;
}
rpvgrw = 1.;
i__1 = *n << 1;
for (i__ = 1; i__ <= i__1; ++i__) {
work[i__] = 0.;
}
/* Find the f2cmax magnitude entry of each column of A. Compute the f2cmax */
/* for all N columns so we can apply the pivot permutation while */
/* looping below. Assume a full factorization is the common case. */
if (upper) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = j;
for (i__ = 1; i__ <= i__2; ++i__) {
/* Computing MAX */
d__2 = (d__1 = a[i__ + j * a_dim1], abs(d__1)), d__3 = work[*
n + i__];
work[*n + i__] = f2cmax(d__2,d__3);
/* Computing MAX */
d__2 = (d__1 = a[i__ + j * a_dim1], abs(d__1)), d__3 = work[*
n + j];
work[*n + j] = f2cmax(d__2,d__3);
}
}
} else {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
i__2 = *n;
for (i__ = j; i__ <= i__2; ++i__) {
/* Computing MAX */
d__2 = (d__1 = a[i__ + j * a_dim1], abs(d__1)), d__3 = work[*
n + i__];
work[*n + i__] = f2cmax(d__2,d__3);
/* Computing MAX */
d__2 = (d__1 = a[i__ + j * a_dim1], abs(d__1)), d__3 = work[*
n + j];
work[*n + j] = f2cmax(d__2,d__3);
}
}
}
/* Now find the f2cmax magnitude entry of each column of U or L. Also */
/* permute the magnitudes of A above so they're in the same order as */
/* the factor. */
/* The iteration orders and permutations were copied from dsytrs. */
/* Calls to SSWAP would be severe overkill. */
if (upper) {
k = *n;
while(k < ncols && k > 0) {
if (ipiv[k] > 0) {
/* 1x1 pivot */
kp = ipiv[k];
if (kp != k) {
tmp = work[*n + k];
work[*n + k] = work[*n + kp];
work[*n + kp] = tmp;
}
i__1 = k;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Computing MAX */
d__2 = (d__1 = af[i__ + k * af_dim1], abs(d__1)), d__3 =
work[k];
work[k] = f2cmax(d__2,d__3);
}
--k;
} else {
/* 2x2 pivot */
kp = -ipiv[k];
tmp = work[*n + k - 1];
work[*n + k - 1] = work[*n + kp];
work[*n + kp] = tmp;
i__1 = k - 1;
for (i__ = 1; i__ <= i__1; ++i__) {
/* Computing MAX */
d__2 = (d__1 = af[i__ + k * af_dim1], abs(d__1)), d__3 =
work[k];
work[k] = f2cmax(d__2,d__3);
/* Computing MAX */
d__2 = (d__1 = af[i__ + (k - 1) * af_dim1], abs(d__1)),
d__3 = work[k - 1];
work[k - 1] = f2cmax(d__2,d__3);
}
/* Computing MAX */
d__2 = (d__1 = af[k + k * af_dim1], abs(d__1)), d__3 = work[k]
;
work[k] = f2cmax(d__2,d__3);
k += -2;
}
}
k = ncols;
while(k <= *n) {
if (ipiv[k] > 0) {
kp = ipiv[k];
if (kp != k) {
tmp = work[*n + k];
work[*n + k] = work[*n + kp];
work[*n + kp] = tmp;
}
++k;
} else {
kp = -ipiv[k];
tmp = work[*n + k];
work[*n + k] = work[*n + kp];
work[*n + kp] = tmp;
k += 2;
}
}
} else {
k = 1;
while(k <= ncols) {
if (ipiv[k] > 0) {
/* 1x1 pivot */
kp = ipiv[k];
if (kp != k) {
tmp = work[*n + k];
work[*n + k] = work[*n + kp];
work[*n + kp] = tmp;
}
i__1 = *n;
for (i__ = k; i__ <= i__1; ++i__) {
/* Computing MAX */
d__2 = (d__1 = af[i__ + k * af_dim1], abs(d__1)), d__3 =
work[k];
work[k] = f2cmax(d__2,d__3);
}
++k;
} else {
/* 2x2 pivot */
kp = -ipiv[k];
tmp = work[*n + k + 1];
work[*n + k + 1] = work[*n + kp];
work[*n + kp] = tmp;
i__1 = *n;
for (i__ = k + 1; i__ <= i__1; ++i__) {
/* Computing MAX */
d__2 = (d__1 = af[i__ + k * af_dim1], abs(d__1)), d__3 =
work[k];
work[k] = f2cmax(d__2,d__3);
/* Computing MAX */
d__2 = (d__1 = af[i__ + (k + 1) * af_dim1], abs(d__1)),
d__3 = work[k + 1];
work[k + 1] = f2cmax(d__2,d__3);
}
/* Computing MAX */
d__2 = (d__1 = af[k + k * af_dim1], abs(d__1)), d__3 = work[k]
;
work[k] = f2cmax(d__2,d__3);
k += 2;
}
}
k = ncols;
while(k >= 1) {
if (ipiv[k] > 0) {
kp = ipiv[k];
if (kp != k) {
tmp = work[*n + k];
work[*n + k] = work[*n + kp];
work[*n + kp] = tmp;
}
--k;
} else {
kp = -ipiv[k];
tmp = work[*n + k];
work[*n + k] = work[*n + kp];
work[*n + kp] = tmp;
k += -2;
}
}
}
/* Compute the *inverse* of the f2cmax element growth factor. Dividing */
/* by zero would imply the largest entry of the factor's column is */
/* zero. Than can happen when either the column of A is zero or */
/* massive pivots made the factor underflow to zero. Neither counts */
/* as growth in itself, so simply ignore terms with zero */
/* denominators. */
if (upper) {
i__1 = *n;
for (i__ = ncols; i__ <= i__1; ++i__) {
umax = work[i__];
amax = work[*n + i__];
if (umax != 0.) {
/* Computing MIN */
d__1 = amax / umax;
rpvgrw = f2cmin(d__1,rpvgrw);
}
}
} else {
i__1 = ncols;
for (i__ = 1; i__ <= i__1; ++i__) {
umax = work[i__];
amax = work[*n + i__];
if (umax != 0.) {
/* Computing MIN */
d__1 = amax / umax;
rpvgrw = f2cmin(d__1,rpvgrw);
}
}
}
ret_val = rpvgrw;
return ret_val;
} /* dla_syrpvgrw__ */
|
the_stack_data/70443.c | #include <stdio.h>
#include <string.h>
#include <ctype.h>
int main (void)
{
printf("Enter Height: ");
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
for (int sp = 0; sp < n-1-i; sp++)
{
printf(" ");
}
for (int st = 0; st < 2*i+1; st++)
{
printf("*");
}
printf("\n");
}
}
|
the_stack_data/702183.c | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int getRandomInt(int min, int max);
int gcd(int a, int b);
double calculate(int coPrime, int total);
double estimateNumberPI(void);
int main(void)
{
srand(time(0));
double piE = estimateNumberPI();
printf("PIE estimate = %.15f\n", piE);
return 0;
}
int getRandomInt(int min, int max)
{
return (rand() % 90000) + 10000;
}
int gcd(int a, int b)
{
if (b > a)
{
int temp = a;
a = b;
b = temp;
}
int m = a % b;
if (m == 0)
{
return b;
}
else
{
return gcd(b, m);
}
}
double calculate(int coPrime, int total)
{
const double ratio = coPrime / (double)total;
return sqrt(6 / ratio);
}
double estimateNumberPI()
{
int coPrime = 0, total = 0, i;
for (i = 0; i < 1000000000; i++)
{
const int first = getRandomInt(10000, 100000);
const int second = getRandomInt(10000, 100000);
if(gcd(first, second) == 1)
{
coPrime++;
}
total++;
}
return calculate(coPrime, total);
}
|
the_stack_data/1055197.c | /*
-----------------------------------------------------------------------
IPMPAR PROVIDES THE INTEGER MACHINE CONSTANTS FOR THE COMPUTER
THAT IS USED. IT IS ASSUMED THAT THE ARGUMENT I IS AN INTEGER
HAVING ONE OF THE VALUES 1-10. IPMPAR(I) HAS THE VALUE ...
INTEGERS.
ASSUME INTEGERS ARE REPRESENTED IN THE N-DIGIT, BASE-A FORM
SIGN ( X(N-1)*A**(N-1) + ... + X(1)*A + X(0) )
WHERE 0 .LE. X(I) .LT. A FOR I=0,...,N-1.
IPMPAR(1) = A, THE BASE.
IPMPAR(2) = N, THE NUMBER OF BASE-A DIGITS.
IPMPAR(3) = A**N - 1, THE LARGEST MAGNITUDE.
FLOATING-POINT NUMBERS.
IT IS ASSUMED THAT THE SINGLE AND DOUBLE PRECISION FLOATING
POINT ARITHMETICS HAVE THE SAME BASE, SAY B, AND THAT THE
NONZERO NUMBERS ARE REPRESENTED IN THE FORM
SIGN (B**E) * (X(1)/B + ... + X(M)/B**M)
WHERE X(I) = 0,1,...,B-1 FOR I=1,...,M,
X(1) .GE. 1, AND EMIN .LE. E .LE. EMAX.
IPMPAR(4) = B, THE BASE.
SINGLE-PRECISION
IPMPAR(5) = M, THE NUMBER OF BASE-B DIGITS.
IPMPAR(6) = EMIN, THE SMALLEST EXPONENT E.
IPMPAR(7) = EMAX, THE LARGEST EXPONENT E.
DOUBLE-PRECISION
IPMPAR(8) = M, THE NUMBER OF BASE-B DIGITS.
IPMPAR(9) = EMIN, THE SMALLEST EXPONENT E.
IPMPAR(10) = EMAX, THE LARGEST EXPONENT E.
-----------------------------------------------------------------------
TO DEFINE THIS FUNCTION FOR THE COMPUTER BEING USED REMOVE
THE COMMENT DELIMITORS FROM THE DEFINITIONS DIRECTLY BELOW THE NAME
OF THE MACHINE
-----------------------------------------------------------------------
IPMPAR IS AN ADAPTATION OF THE FUNCTION I1MACH, WRITTEN BY
P.A. FOX, A.D. HALL, AND N.L. SCHRYER (BELL LABORATORIES).
IPMPAR WAS FORMED BY A.H. MORRIS (NSWC). THE CONSTANTS ARE
FROM BELL LABORATORIES, NSWC, AND OTHER SOURCES.
-----------------------------------------------------------------------
.. Scalar Arguments ..
*/
int ipmpar(int *i)
{
static int imach[11];
static int ipmpar;
/* MACHINE CONSTANTS FOR AMDAHL MACHINES. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 16;
imach[5] = 6;
imach[6] = -64;
imach[7] = 63;
imach[8] = 14;
imach[9] = -64;
imach[10] = 63;
*/
/* MACHINE CONSTANTS FOR THE AT&T 3B SERIES, AT&T
PC 7300, AND AT&T 6300. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -125;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
*/
/* MACHINE CONSTANTS FOR THE BURROUGHS 1700 SYSTEM. */
/*
imach[1] = 2;
imach[2] = 33;
imach[3] = 8589934591;
imach[4] = 2;
imach[5] = 24;
imach[6] = -256;
imach[7] = 255;
imach[8] = 60;
imach[9] = -256;
imach[10] = 255;
*/
/* MACHINE CONSTANTS FOR THE BURROUGHS 5700 SYSTEM. */
/*
imach[1] = 2;
imach[2] = 39;
imach[3] = 549755813887;
imach[4] = 8;
imach[5] = 13;
imach[6] = -50;
imach[7] = 76;
imach[8] = 26;
imach[9] = -50;
imach[10] = 76;
*/
/* MACHINE CONSTANTS FOR THE BURROUGHS 6700/7700 SYSTEMS. */
/*
imach[1] = 2;
imach[2] = 39;
imach[3] = 549755813887;
imach[4] = 8;
imach[5] = 13;
imach[6] = -50;
imach[7] = 76;
imach[8] = 26;
imach[9] = -32754;
imach[10] = 32780;
*/
/* MACHINE CONSTANTS FOR THE CDC 6000/7000 SERIES
60 BIT ARITHMETIC, AND THE CDC CYBER 995 64 BIT
ARITHMETIC (NOS OPERATING SYSTEM). */
/*
imach[1] = 2;
imach[2] = 48;
imach[3] = 281474976710655;
imach[4] = 2;
imach[5] = 48;
imach[6] = -974;
imach[7] = 1070;
imach[8] = 95;
imach[9] = -926;
imach[10] = 1070;
*/
/* MACHINE CONSTANTS FOR THE CDC CYBER 995 64 BIT
ARITHMETIC (NOS/VE OPERATING SYSTEM). */
/*
imach[1] = 2;
imach[2] = 63;
imach[3] = 9223372036854775807;
imach[4] = 2;
imach[5] = 48;
imach[6] = -4096;
imach[7] = 4095;
imach[8] = 96;
imach[9] = -4096;
imach[10] = 4095;
*/
/* MACHINE CONSTANTS FOR THE CRAY 1, XMP, 2, AND 3. */
/*
imach[1] = 2;
imach[2] = 63;
imach[3] = 9223372036854775807;
imach[4] = 2;
imach[5] = 47;
imach[6] = -8189;
imach[7] = 8190;
imach[8] = 94;
imach[9] = -8099;
imach[10] = 8190;
*/
/* MACHINE CONSTANTS FOR THE DATA GENERAL ECLIPSE S/200. */
/*
imach[1] = 2;
imach[2] = 15;
imach[3] = 32767;
imach[4] = 16;
imach[5] = 6;
imach[6] = -64;
imach[7] = 63;
imach[8] = 14;
imach[9] = -64;
imach[10] = 63;
*/
/* MACHINE CONSTANTS FOR THE HARRIS 220. */
/*
imach[1] = 2;
imach[2] = 23;
imach[3] = 8388607;
imach[4] = 2;
imach[5] = 23;
imach[6] = -127;
imach[7] = 127;
imach[8] = 38;
imach[9] = -127;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE HONEYWELL 600/6000
AND DPS 8/70 SERIES. */
/*
imach[1] = 2;
imach[2] = 35;
imach[3] = 34359738367;
imach[4] = 2;
imach[5] = 27;
imach[6] = -127;
imach[7] = 127;
imach[8] = 63;
imach[9] = -127;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE HP 2100
3 WORD DOUBLE PRECISION OPTION WITH FTN4 */
/*
imach[1] = 2;
imach[2] = 15;
imach[3] = 32767;
imach[4] = 2;
imach[5] = 23;
imach[6] = -128;
imach[7] = 127;
imach[8] = 39;
imach[9] = -128;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE HP 2100
4 WORD DOUBLE PRECISION OPTION WITH FTN4 */
/*
imach[1] = 2;
imach[2] = 15;
imach[3] = 32767;
imach[4] = 2;
imach[5] = 23;
imach[6] = -128;
imach[7] = 127;
imach[8] = 55;
imach[9] = -128;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE HP 9000. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -126;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
*/
/* MACHINE CONSTANTS FOR THE IBM 360/370 SERIES,
THE ICL 2900, THE ITEL AS/6, THE XEROX SIGMA
5/7/9 AND THE SEL SYSTEMS 85/86. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 16;
imach[5] = 6;
imach[6] = -64;
imach[7] = 63;
imach[8] = 14;
imach[9] = -64;
imach[10] = 63;
*/
/* MACHINE CONSTANTS FOR THE IBM PC. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -125;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
*/
/* MACHINE CONSTANTS FOR THE MACINTOSH II - ABSOFT
MACFORTRAN II. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -125;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
*/
/* MACHINE CONSTANTS FOR THE MICROVAX - VMS FORTRAN. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -127;
imach[7] = 127;
imach[8] = 56;
imach[9] = -127;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE PDP-10 (KA PROCESSOR). */
/*
imach[1] = 2;
imach[2] = 35;
imach[3] = 34359738367;
imach[4] = 2;
imach[5] = 27;
imach[6] = -128;
imach[7] = 127;
imach[8] = 54;
imach[9] = -101;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE PDP-10 (KI PROCESSOR). */
/*
imach[1] = 2;
imach[2] = 35;
imach[3] = 34359738367;
imach[4] = 2;
imach[5] = 27;
imach[6] = -128;
imach[7] = 127;
imach[8] = 62;
imach[9] = -128;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE PDP-11 FORTRAN SUPPORTING
32-BIT INTEGER ARITHMETIC. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -127;
imach[7] = 127;
imach[8] = 56;
imach[9] = -127;
imach[10] = 127;
*/
/* MACHINE CONSTANTS FOR THE SEQUENT BALANCE 8000. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -125;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
*/
/* MACHINE CONSTANTS FOR THE SILICON GRAPHICS IRIS-4D
SERIES (MIPS R3000 PROCESSOR). */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -125;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
*/
/* MACHINE CONSTANTS FOR IEEE ARITHMETIC MACHINES, SUCH AS THE AT&T
3B SERIES, MOTOROLA 68000 BASED MACHINES (E.G. SUN 3 AND AT&T
PC 7300), AND 8087 BASED MICROS (E.G. IBM PC AND AT&T 6300). */
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -125;
imach[7] = 128;
imach[8] = 53;
imach[9] = -1021;
imach[10] = 1024;
/* MACHINE CONSTANTS FOR THE UNIVAC 1100 SERIES. */
/*
imach[1] = 2;
imach[2] = 35;
imach[3] = 34359738367;
imach[4] = 2;
imach[5] = 27;
imach[6] = -128;
imach[7] = 127;
imach[8] = 60;
imach[9] = -1024;
imach[10] = 1023;
*/
/* MACHINE CONSTANTS FOR THE VAX 11/780. */
/*
imach[1] = 2;
imach[2] = 31;
imach[3] = 2147483647;
imach[4] = 2;
imach[5] = 24;
imach[6] = -127;
imach[7] = 127;
imach[8] = 56;
imach[9] = -127;
imach[10] = 127;
*/
ipmpar = imach[*i];
return ipmpar;
}
|
the_stack_data/122233.c | #include <stdio.h>
main() { hello(); } |
the_stack_data/162644233.c | /*
* Program from Fig.2 of
* 2011TACAS - Podelski,Rybalchenko - Transition Invariants and Transition Predicate Abstraction for Program Termination
*
* Date: 2014
* Author: Caterina Urban
*/
typedef enum {false, true} bool;
extern int __VERIFIER_nondet_int(void);
int main() {
int x, y;
x = __VERIFIER_nondet_int();
y = __VERIFIER_nondet_int();
while (x >= 0) {
y = 1;
while (y < x) {
y = y + 1;
}
x = x - 1;
}
return 0;
}
|
the_stack_data/105575.c | #include <stdio.h>
void main () {
/*
1) Intruções/função
2) identação
3) Comentário C
*/
printf(" ");
return 0;
} |
the_stack_data/231392765.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> ZGESVX computes the solution to system of linear equations A * X = B for GE matrices</b> */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download ZGESVX + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zgesvx.
f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zgesvx.
f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zgesvx.
f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE ZGESVX( FACT, TRANS, N, NRHS, A, LDA, AF, LDAF, IPIV, */
/* EQUED, R, C, B, LDB, X, LDX, RCOND, FERR, BERR, */
/* WORK, RWORK, INFO ) */
/* CHARACTER EQUED, FACT, TRANS */
/* INTEGER INFO, LDA, LDAF, LDB, LDX, N, NRHS */
/* DOUBLE PRECISION RCOND */
/* INTEGER IPIV( * ) */
/* DOUBLE PRECISION BERR( * ), C( * ), FERR( * ), R( * ), */
/* $ RWORK( * ) */
/* COMPLEX*16 A( LDA, * ), AF( LDAF, * ), B( LDB, * ), */
/* $ WORK( * ), X( LDX, * ) */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > ZGESVX uses the LU factorization to compute the solution to a complex */
/* > system of linear equations */
/* > A * X = B, */
/* > where A is an N-by-N matrix and X and B are N-by-NRHS matrices. */
/* > */
/* > Error bounds on the solution and a condition estimate are also */
/* > provided. */
/* > \endverbatim */
/* > \par Description: */
/* ================= */
/* > */
/* > \verbatim */
/* > */
/* > The following steps are performed: */
/* > */
/* > 1. If FACT = 'E', real scaling factors are computed to equilibrate */
/* > the system: */
/* > TRANS = 'N': diag(R)*A*diag(C) *inv(diag(C))*X = diag(R)*B */
/* > TRANS = 'T': (diag(R)*A*diag(C))**T *inv(diag(R))*X = diag(C)*B */
/* > TRANS = 'C': (diag(R)*A*diag(C))**H *inv(diag(R))*X = diag(C)*B */
/* > Whether or not the system will be equilibrated depends on the */
/* > scaling of the matrix A, but if equilibration is used, A is */
/* > overwritten by diag(R)*A*diag(C) and B by diag(R)*B (if TRANS='N') */
/* > or diag(C)*B (if TRANS = 'T' or 'C'). */
/* > */
/* > 2. If FACT = 'N' or 'E', the LU decomposition is used to factor the */
/* > matrix A (after equilibration if FACT = 'E') as */
/* > A = P * L * U, */
/* > where P is a permutation matrix, L is a unit lower triangular */
/* > matrix, and U is upper triangular. */
/* > */
/* > 3. If some U(i,i)=0, so that U is exactly singular, then the routine */
/* > returns with INFO = i. Otherwise, the factored form of A is used */
/* > to estimate the condition number of the matrix A. If the */
/* > reciprocal of the condition number is less than machine precision, */
/* > INFO = N+1 is returned as a warning, but the routine still goes on */
/* > to solve for X and compute error bounds as described below. */
/* > */
/* > 4. The system of equations is solved for X using the factored form */
/* > of A. */
/* > */
/* > 5. Iterative refinement is applied to improve the computed solution */
/* > matrix and calculate error bounds and backward error estimates */
/* > for it. */
/* > */
/* > 6. If equilibration was used, the matrix X is premultiplied by */
/* > diag(C) (if TRANS = 'N') or diag(R) (if TRANS = 'T' or 'C') so */
/* > that it solves the original system before equilibration. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] FACT */
/* > \verbatim */
/* > FACT is CHARACTER*1 */
/* > Specifies whether or not the factored form of the matrix A is */
/* > supplied on entry, and if not, whether the matrix A should be */
/* > equilibrated before it is factored. */
/* > = 'F': On entry, AF and IPIV contain the factored form of A. */
/* > If EQUED is not 'N', the matrix A has been */
/* > equilibrated with scaling factors given by R and C. */
/* > A, AF, and IPIV are not modified. */
/* > = 'N': The matrix A will be copied to AF and factored. */
/* > = 'E': The matrix A will be equilibrated if necessary, then */
/* > copied to AF and factored. */
/* > \endverbatim */
/* > */
/* > \param[in] TRANS */
/* > \verbatim */
/* > TRANS is CHARACTER*1 */
/* > Specifies the form of the system of equations: */
/* > = 'N': A * X = B (No transpose) */
/* > = 'T': A**T * X = B (Transpose) */
/* > = 'C': A**H * X = B (Conjugate transpose) */
/* > \endverbatim */
/* > */
/* > \param[in] N */
/* > \verbatim */
/* > N is INTEGER */
/* > The number of linear equations, i.e., the order of the */
/* > matrix A. N >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in] NRHS */
/* > \verbatim */
/* > NRHS is INTEGER */
/* > The number of right hand sides, i.e., the number of columns */
/* > of the matrices B and X. NRHS >= 0. */
/* > \endverbatim */
/* > */
/* > \param[in,out] A */
/* > \verbatim */
/* > A is COMPLEX*16 array, dimension (LDA,N) */
/* > On entry, the N-by-N matrix A. If FACT = 'F' and EQUED is */
/* > not 'N', then A must have been equilibrated by the scaling */
/* > factors in R and/or C. A is not modified if FACT = 'F' or */
/* > 'N', or if FACT = 'E' and EQUED = 'N' on exit. */
/* > */
/* > On exit, if EQUED .ne. 'N', A is scaled as follows: */
/* > EQUED = 'R': A := diag(R) * A */
/* > EQUED = 'C': A := A * diag(C) */
/* > EQUED = 'B': A := diag(R) * A * diag(C). */
/* > \endverbatim */
/* > */
/* > \param[in] LDA */
/* > \verbatim */
/* > LDA is INTEGER */
/* > The leading dimension of the array A. LDA >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in,out] AF */
/* > \verbatim */
/* > AF is COMPLEX*16 array, dimension (LDAF,N) */
/* > If FACT = 'F', then AF is an input argument and on entry */
/* > contains the factors L and U from the factorization */
/* > A = P*L*U as computed by ZGETRF. If EQUED .ne. 'N', then */
/* > AF is the factored form of the equilibrated matrix A. */
/* > */
/* > If FACT = 'N', then AF is an output argument and on exit */
/* > returns the factors L and U from the factorization A = P*L*U */
/* > of the original matrix A. */
/* > */
/* > If FACT = 'E', then AF is an output argument and on exit */
/* > returns the factors L and U from the factorization A = P*L*U */
/* > of the equilibrated matrix A (see the description of A for */
/* > the form of the equilibrated matrix). */
/* > \endverbatim */
/* > */
/* > \param[in] LDAF */
/* > \verbatim */
/* > LDAF is INTEGER */
/* > The leading dimension of the array AF. LDAF >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[in,out] IPIV */
/* > \verbatim */
/* > IPIV is INTEGER array, dimension (N) */
/* > If FACT = 'F', then IPIV is an input argument and on entry */
/* > contains the pivot indices from the factorization A = P*L*U */
/* > as computed by ZGETRF; row i of the matrix was interchanged */
/* > with row IPIV(i). */
/* > */
/* > If FACT = 'N', then IPIV is an output argument and on exit */
/* > contains the pivot indices from the factorization A = P*L*U */
/* > of the original matrix A. */
/* > */
/* > If FACT = 'E', then IPIV is an output argument and on exit */
/* > contains the pivot indices from the factorization A = P*L*U */
/* > of the equilibrated matrix A. */
/* > \endverbatim */
/* > */
/* > \param[in,out] EQUED */
/* > \verbatim */
/* > EQUED is CHARACTER*1 */
/* > Specifies the form of equilibration that was done. */
/* > = 'N': No equilibration (always true if FACT = 'N'). */
/* > = 'R': Row equilibration, i.e., A has been premultiplied by */
/* > diag(R). */
/* > = 'C': Column equilibration, i.e., A has been postmultiplied */
/* > by diag(C). */
/* > = 'B': Both row and column equilibration, i.e., A has been */
/* > replaced by diag(R) * A * diag(C). */
/* > EQUED is an input argument if FACT = 'F'; otherwise, it is an */
/* > output argument. */
/* > \endverbatim */
/* > */
/* > \param[in,out] R */
/* > \verbatim */
/* > R is DOUBLE PRECISION array, dimension (N) */
/* > The row scale factors for A. If EQUED = 'R' or 'B', A is */
/* > multiplied on the left by diag(R); if EQUED = 'N' or 'C', R */
/* > is not accessed. R is an input argument if FACT = 'F'; */
/* > otherwise, R is an output argument. If FACT = 'F' and */
/* > EQUED = 'R' or 'B', each element of R must be positive. */
/* > \endverbatim */
/* > */
/* > \param[in,out] C */
/* > \verbatim */
/* > C is DOUBLE PRECISION array, dimension (N) */
/* > The column scale factors for A. If EQUED = 'C' or 'B', A is */
/* > multiplied on the right by diag(C); if EQUED = 'N' or 'R', C */
/* > is not accessed. C is an input argument if FACT = 'F'; */
/* > otherwise, C is an output argument. If FACT = 'F' and */
/* > EQUED = 'C' or 'B', each element of C must be positive. */
/* > \endverbatim */
/* > */
/* > \param[in,out] B */
/* > \verbatim */
/* > B is COMPLEX*16 array, dimension (LDB,NRHS) */
/* > On entry, the N-by-NRHS right hand side matrix B. */
/* > On exit, */
/* > if EQUED = 'N', B is not modified; */
/* > if TRANS = 'N' and EQUED = 'R' or 'B', B is overwritten by */
/* > diag(R)*B; */
/* > if TRANS = 'T' or 'C' and EQUED = 'C' or 'B', B is */
/* > overwritten by diag(C)*B. */
/* > \endverbatim */
/* > */
/* > \param[in] LDB */
/* > \verbatim */
/* > LDB is INTEGER */
/* > The leading dimension of the array B. LDB >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] X */
/* > \verbatim */
/* > X is COMPLEX*16 array, dimension (LDX,NRHS) */
/* > If INFO = 0 or INFO = N+1, the N-by-NRHS solution matrix X */
/* > to the original system of equations. Note that A and B are */
/* > modified on exit if EQUED .ne. 'N', and the solution to the */
/* > equilibrated system is inv(diag(C))*X if TRANS = 'N' and */
/* > EQUED = 'C' or 'B', or inv(diag(R))*X if TRANS = 'T' or 'C' */
/* > and EQUED = 'R' or 'B'. */
/* > \endverbatim */
/* > */
/* > \param[in] LDX */
/* > \verbatim */
/* > LDX is INTEGER */
/* > The leading dimension of the array X. LDX >= f2cmax(1,N). */
/* > \endverbatim */
/* > */
/* > \param[out] RCOND */
/* > \verbatim */
/* > RCOND is DOUBLE PRECISION */
/* > The estimate of the reciprocal condition number of the matrix */
/* > A after equilibration (if done). If RCOND is less than the */
/* > machine precision (in particular, if RCOND = 0), the matrix */
/* > is singular to working precision. This condition is */
/* > indicated by a return code of INFO > 0. */
/* > \endverbatim */
/* > */
/* > \param[out] FERR */
/* > \verbatim */
/* > FERR is DOUBLE PRECISION array, dimension (NRHS) */
/* > The estimated forward error bound for each solution vector */
/* > X(j) (the j-th column of the solution matrix X). */
/* > If XTRUE is the true solution corresponding to X(j), FERR(j) */
/* > is an estimated upper bound for the magnitude of the largest */
/* > element in (X(j) - XTRUE) divided by the magnitude of the */
/* > largest element in X(j). The estimate is as reliable as */
/* > the estimate for RCOND, and is almost always a slight */
/* > overestimate of the true error. */
/* > \endverbatim */
/* > */
/* > \param[out] BERR */
/* > \verbatim */
/* > BERR is DOUBLE PRECISION array, dimension (NRHS) */
/* > The componentwise relative backward error of each solution */
/* > vector X(j) (i.e., the smallest relative change in */
/* > any element of A or B that makes X(j) an exact solution). */
/* > \endverbatim */
/* > */
/* > \param[out] WORK */
/* > \verbatim */
/* > WORK is COMPLEX*16 array, dimension (2*N) */
/* > \endverbatim */
/* > */
/* > \param[out] RWORK */
/* > \verbatim */
/* > RWORK is DOUBLE PRECISION array, dimension (2*N) */
/* > On exit, RWORK(1) contains the reciprocal pivot growth */
/* > factor norm(A)/norm(U). The "f2cmax absolute element" norm is */
/* > used. If RWORK(1) is much less than 1, then the stability */
/* > of the LU factorization of the (equilibrated) matrix A */
/* > could be poor. This also means that the solution X, condition */
/* > estimator RCOND, and forward error bound FERR could be */
/* > unreliable. If factorization fails with 0<INFO<=N, then */
/* > RWORK(1) contains the reciprocal pivot growth factor for the */
/* > leading INFO columns of A. */
/* > \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, and i is */
/* > <= N: U(i,i) is exactly zero. The factorization has */
/* > been completed, but the factor U is exactly */
/* > singular, so the solution and error bounds */
/* > could not be computed. RCOND = 0 is returned. */
/* > = N+1: U is nonsingular, but RCOND is less than machine */
/* > precision, meaning that the matrix is singular */
/* > to working precision. Nevertheless, the */
/* > solution and error bounds are computed because */
/* > there are a number of situations where the */
/* > computed solution can be more accurate than the */
/* > value of RCOND would suggest. */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date April 2012 */
/* > \ingroup complex16GEsolve */
/* ===================================================================== */
/* Subroutine */ int zgesvx_(char *fact, char *trans, integer *n, integer *
nrhs, doublecomplex *a, integer *lda, doublecomplex *af, integer *
ldaf, integer *ipiv, char *equed, doublereal *r__, doublereal *c__,
doublecomplex *b, integer *ldb, doublecomplex *x, integer *ldx,
doublereal *rcond, doublereal *ferr, doublereal *berr, doublecomplex *
work, doublereal *rwork, integer *info)
{
/* System generated locals */
integer a_dim1, a_offset, af_dim1, af_offset, b_dim1, b_offset, x_dim1,
x_offset, i__1, i__2, i__3, i__4, i__5;
doublereal d__1, d__2;
doublecomplex z__1;
/* Local variables */
doublereal amax;
char norm[1];
integer i__, j;
extern logical lsame_(char *, char *);
doublereal rcmin, rcmax, anorm;
logical equil;
extern doublereal dlamch_(char *);
doublereal colcnd;
logical nofact;
extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen);
extern doublereal zlange_(char *, integer *, integer *, doublecomplex *,
integer *, doublereal *);
doublereal bignum;
extern /* Subroutine */ int zlaqge_(integer *, integer *, doublecomplex *,
integer *, doublereal *, doublereal *, doublereal *, doublereal *
, doublereal *, char *), zgecon_(char *, integer *,
doublecomplex *, integer *, doublereal *, doublereal *,
doublecomplex *, doublereal *, integer *);
integer infequ;
logical colequ;
doublereal rowcnd;
extern /* Subroutine */ int zgeequ_(integer *, integer *, doublecomplex *,
integer *, doublereal *, doublereal *, doublereal *, doublereal *
, doublereal *, integer *);
logical notran;
extern /* Subroutine */ int zgerfs_(char *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *, integer *,
doublecomplex *, integer *, doublecomplex *, integer *,
doublereal *, doublereal *, doublecomplex *, doublereal *,
integer *), zgetrf_(integer *, integer *, doublecomplex *,
integer *, integer *, integer *), zlacpy_(char *, integer *,
integer *, doublecomplex *, integer *, doublecomplex *, integer *);
extern doublereal zlantr_(char *, char *, char *, integer *, integer *,
doublecomplex *, integer *, doublereal *);
doublereal smlnum;
extern /* Subroutine */ int zgetrs_(char *, integer *, integer *,
doublecomplex *, integer *, integer *, doublecomplex *, integer *,
integer *);
logical rowequ;
doublereal rpvgrw;
/* -- LAPACK driver 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..-- */
/* April 2012 */
/* ===================================================================== */
/* Parameter adjustments */
a_dim1 = *lda;
a_offset = 1 + a_dim1 * 1;
a -= a_offset;
af_dim1 = *ldaf;
af_offset = 1 + af_dim1 * 1;
af -= af_offset;
--ipiv;
--r__;
--c__;
b_dim1 = *ldb;
b_offset = 1 + b_dim1 * 1;
b -= b_offset;
x_dim1 = *ldx;
x_offset = 1 + x_dim1 * 1;
x -= x_offset;
--ferr;
--berr;
--work;
--rwork;
/* Function Body */
*info = 0;
nofact = lsame_(fact, "N");
equil = lsame_(fact, "E");
notran = lsame_(trans, "N");
if (nofact || equil) {
*(unsigned char *)equed = 'N';
rowequ = FALSE_;
colequ = FALSE_;
} else {
rowequ = lsame_(equed, "R") || lsame_(equed,
"B");
colequ = lsame_(equed, "C") || lsame_(equed,
"B");
smlnum = dlamch_("Safe minimum");
bignum = 1. / smlnum;
}
/* Test the input parameters. */
if (! nofact && ! equil && ! lsame_(fact, "F")) {
*info = -1;
} else if (! notran && ! lsame_(trans, "T") && !
lsame_(trans, "C")) {
*info = -2;
} else if (*n < 0) {
*info = -3;
} else if (*nrhs < 0) {
*info = -4;
} else if (*lda < f2cmax(1,*n)) {
*info = -6;
} else if (*ldaf < f2cmax(1,*n)) {
*info = -8;
} else if (lsame_(fact, "F") && ! (rowequ || colequ
|| lsame_(equed, "N"))) {
*info = -10;
} else {
if (rowequ) {
rcmin = bignum;
rcmax = 0.;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/* Computing MIN */
d__1 = rcmin, d__2 = r__[j];
rcmin = f2cmin(d__1,d__2);
/* Computing MAX */
d__1 = rcmax, d__2 = r__[j];
rcmax = f2cmax(d__1,d__2);
/* L10: */
}
if (rcmin <= 0.) {
*info = -11;
} else if (*n > 0) {
rowcnd = f2cmax(rcmin,smlnum) / f2cmin(rcmax,bignum);
} else {
rowcnd = 1.;
}
}
if (colequ && *info == 0) {
rcmin = bignum;
rcmax = 0.;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
/* Computing MIN */
d__1 = rcmin, d__2 = c__[j];
rcmin = f2cmin(d__1,d__2);
/* Computing MAX */
d__1 = rcmax, d__2 = c__[j];
rcmax = f2cmax(d__1,d__2);
/* L20: */
}
if (rcmin <= 0.) {
*info = -12;
} else if (*n > 0) {
colcnd = f2cmax(rcmin,smlnum) / f2cmin(rcmax,bignum);
} else {
colcnd = 1.;
}
}
if (*info == 0) {
if (*ldb < f2cmax(1,*n)) {
*info = -14;
} else if (*ldx < f2cmax(1,*n)) {
*info = -16;
}
}
}
if (*info != 0) {
i__1 = -(*info);
xerbla_("ZGESVX", &i__1, (ftnlen)6);
return 0;
}
if (equil) {
/* Compute row and column scalings to equilibrate the matrix A. */
zgeequ_(n, n, &a[a_offset], lda, &r__[1], &c__[1], &rowcnd, &colcnd, &
amax, &infequ);
if (infequ == 0) {
/* Equilibrate the matrix. */
zlaqge_(n, n, &a[a_offset], lda, &r__[1], &c__[1], &rowcnd, &
colcnd, &amax, equed);
rowequ = lsame_(equed, "R") || lsame_(equed,
"B");
colequ = lsame_(equed, "C") || lsame_(equed,
"B");
}
}
/* Scale the right hand side. */
if (notran) {
if (rowequ) {
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * b_dim1;
i__4 = i__;
i__5 = i__ + j * b_dim1;
z__1.r = r__[i__4] * b[i__5].r, z__1.i = r__[i__4] * b[
i__5].i;
b[i__3].r = z__1.r, b[i__3].i = z__1.i;
/* L30: */
}
/* L40: */
}
}
} else if (colequ) {
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * b_dim1;
i__4 = i__;
i__5 = i__ + j * b_dim1;
z__1.r = c__[i__4] * b[i__5].r, z__1.i = c__[i__4] * b[i__5]
.i;
b[i__3].r = z__1.r, b[i__3].i = z__1.i;
/* L50: */
}
/* L60: */
}
}
if (nofact || equil) {
/* Compute the LU factorization of A. */
zlacpy_("Full", n, n, &a[a_offset], lda, &af[af_offset], ldaf);
zgetrf_(n, n, &af[af_offset], ldaf, &ipiv[1], info);
/* Return if INFO is non-zero. */
if (*info > 0) {
/* Compute the reciprocal pivot growth factor of the */
/* leading rank-deficient INFO columns of A. */
rpvgrw = zlantr_("M", "U", "N", info, info, &af[af_offset], ldaf,
&rwork[1]);
if (rpvgrw == 0.) {
rpvgrw = 1.;
} else {
rpvgrw = zlange_("M", n, info, &a[a_offset], lda, &rwork[1]) / rpvgrw;
}
rwork[1] = rpvgrw;
*rcond = 0.;
return 0;
}
}
/* Compute the norm of the matrix A and the */
/* reciprocal pivot growth factor RPVGRW. */
if (notran) {
*(unsigned char *)norm = '1';
} else {
*(unsigned char *)norm = 'I';
}
anorm = zlange_(norm, n, n, &a[a_offset], lda, &rwork[1]);
rpvgrw = zlantr_("M", "U", "N", n, n, &af[af_offset], ldaf, &rwork[1]);
if (rpvgrw == 0.) {
rpvgrw = 1.;
} else {
rpvgrw = zlange_("M", n, n, &a[a_offset], lda, &rwork[1]) /
rpvgrw;
}
/* Compute the reciprocal of the condition number of A. */
zgecon_(norm, n, &af[af_offset], ldaf, &anorm, rcond, &work[1], &rwork[1],
info);
/* Compute the solution matrix X. */
zlacpy_("Full", n, nrhs, &b[b_offset], ldb, &x[x_offset], ldx);
zgetrs_(trans, n, nrhs, &af[af_offset], ldaf, &ipiv[1], &x[x_offset], ldx,
info);
/* Use iterative refinement to improve the computed solution and */
/* compute error bounds and backward error estimates for it. */
zgerfs_(trans, n, nrhs, &a[a_offset], lda, &af[af_offset], ldaf, &ipiv[1],
&b[b_offset], ldb, &x[x_offset], ldx, &ferr[1], &berr[1], &work[
1], &rwork[1], info);
/* Transform the solution matrix X to a solution of the original */
/* system. */
if (notran) {
if (colequ) {
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * x_dim1;
i__4 = i__;
i__5 = i__ + j * x_dim1;
z__1.r = c__[i__4] * x[i__5].r, z__1.i = c__[i__4] * x[
i__5].i;
x[i__3].r = z__1.r, x[i__3].i = z__1.i;
/* L70: */
}
/* L80: */
}
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
ferr[j] /= colcnd;
/* L90: */
}
}
} else if (rowequ) {
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
i__2 = *n;
for (i__ = 1; i__ <= i__2; ++i__) {
i__3 = i__ + j * x_dim1;
i__4 = i__;
i__5 = i__ + j * x_dim1;
z__1.r = r__[i__4] * x[i__5].r, z__1.i = r__[i__4] * x[i__5]
.i;
x[i__3].r = z__1.r, x[i__3].i = z__1.i;
/* L100: */
}
/* L110: */
}
i__1 = *nrhs;
for (j = 1; j <= i__1; ++j) {
ferr[j] /= rowcnd;
/* L120: */
}
}
/* Set INFO = N+1 if the matrix is singular to working precision. */
if (*rcond < dlamch_("Epsilon")) {
*info = *n + 1;
}
rwork[1] = rpvgrw;
return 0;
/* End of ZGESVX */
} /* zgesvx_ */
|
the_stack_data/165766823.c | #include <stdio.h>
int main(int argc, char **argv)
{
return 0;
} |
the_stack_data/34546.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
#if defined(ARDUINO_ARCH_NRF5) && defined(NRF52_SERIES)
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include "nimble/porting/nimble/include/syscfg/syscfg.h"
#include "nimble/porting/nimble/include/os/os.h"
#include "../include/ble/xcvr.h"
#include "nimble/nimble/include/nimble/ble.h"
#include "nimble/nimble/include/nimble/nimble_opt.h"
#include "nimble/nimble/include/nimble/nimble_npl.h"
#include "nimble/nimble/controller/include/controller/ble_phy.h"
#include "nimble/nimble/controller/include/controller/ble_phy_trace.h"
#include "nimble/nimble/controller/include/controller/ble_ll.h"
#include "nrf.h"
#if MYNEWT
#include "mcu/nrf52_clock.h"
#include "mcu/cmsis_nvic.h"
#include "hal/hal_gpio.h"
#else
#include "core_cm4.h"
#endif
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_CODED_PHY)
#if !MYNEWT_VAL_CHOICE(MCU_TARGET, nRF52840) && !MYNEWT_VAL_CHOICE(MCU_TARGET, nRF52811)
#error LE Coded PHY can only be enabled on nRF52811 or nRF52840
#endif
#endif
/*
* NOTE: This code uses a couple of PPI channels so care should be taken when
* using PPI somewhere else.
*
* Pre-programmed channels: CH20, CH21, CH23, CH25, CH31
* Regular channels: CH4, CH5 and optionally CH17, CH18, CH19
* - CH4 = cancel wfr timer on address match
* - CH5 = disable radio on wfr timer expiry
* - CH17 = (optional) gpio debug for radio ramp-up
* - CH18 = (optional) gpio debug for wfr timer RX enabled
* - CH19 = (optional) gpio debug for wfr timer radio disabled
*
*/
/* XXX: 4) Make sure RF is higher priority interrupt than schedule */
/*
* XXX: Maximum possible transmit time is 1 msec for a 60ppm crystal
* and 16ms for a 30ppm crystal! We need to limit PDU size based on
* crystal accuracy. Look at this in the spec.
*/
/* XXX: private header file? */
extern uint8_t g_nrf_num_irks;
extern uint32_t g_nrf_irk_list[];
/* To disable all radio interrupts */
#define NRF_RADIO_IRQ_MASK_ALL (0x34FF)
/*
* We configure the nrf with a 1 byte S0 field, 8 bit length field, and
* zero bit S1 field. The preamble is 8 bits long.
*/
#define NRF_LFLEN_BITS (8)
#define NRF_S0LEN (1)
#define NRF_S1LEN_BITS (0)
#define NRF_CILEN_BITS (2)
#define NRF_TERMLEN_BITS (3)
/* Maximum length of frames */
#define NRF_MAXLEN (255)
#define NRF_BALEN (3) /* For base address of 3 bytes */
/* NRF_RADIO->PCNF0 configuration values */
#define NRF_PCNF0 (NRF_LFLEN_BITS << RADIO_PCNF0_LFLEN_Pos) | \
(RADIO_PCNF0_S1INCL_Msk) | \
(NRF_S0LEN << RADIO_PCNF0_S0LEN_Pos) | \
(NRF_S1LEN_BITS << RADIO_PCNF0_S1LEN_Pos)
#define NRF_PCNF0_1M (NRF_PCNF0) | \
(RADIO_PCNF0_PLEN_8bit << RADIO_PCNF0_PLEN_Pos)
#define NRF_PCNF0_2M (NRF_PCNF0) | \
(RADIO_PCNF0_PLEN_16bit << RADIO_PCNF0_PLEN_Pos)
#define NRF_PCNF0_CODED (NRF_PCNF0) | \
(RADIO_PCNF0_PLEN_LongRange << RADIO_PCNF0_PLEN_Pos) | \
(NRF_CILEN_BITS << RADIO_PCNF0_CILEN_Pos) | \
(NRF_TERMLEN_BITS << RADIO_PCNF0_TERMLEN_Pos)
/* BLE PHY data structure */
struct ble_phy_obj
{
uint8_t phy_stats_initialized;
int8_t phy_txpwr_dbm;
uint8_t phy_chan;
uint8_t phy_state;
uint8_t phy_transition;
uint8_t phy_transition_late;
uint8_t phy_rx_started;
uint8_t phy_encrypted;
uint8_t phy_privacy;
uint8_t phy_tx_pyld_len;
uint8_t phy_cur_phy_mode;
uint8_t phy_tx_phy_mode;
uint8_t phy_rx_phy_mode;
uint8_t phy_bcc_offset;
int8_t rx_pwr_compensation;
uint32_t phy_aar_scratch;
uint32_t phy_access_address;
struct ble_mbuf_hdr rxhdr;
void *txend_arg;
ble_phy_tx_end_func txend_cb;
uint32_t phy_start_cputime;
};
struct ble_phy_obj g_ble_phy_data;
/* XXX: if 27 byte packets desired we can make this smaller */
/* Global transmit/receive buffer */
static uint32_t g_ble_phy_tx_buf[(BLE_PHY_MAX_PDU_LEN + 3) / 4];
static uint32_t g_ble_phy_rx_buf[(BLE_PHY_MAX_PDU_LEN + 3) / 4];
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
/* Make sure word-aligned for faster copies */
static uint32_t g_ble_phy_enc_buf[(BLE_PHY_MAX_PDU_LEN + 3) / 4];
#endif
/* RF center frequency for each channel index (offset from 2400 MHz) */
static const uint8_t g_ble_phy_chan_freq[BLE_PHY_NUM_CHANS] = {
4, 6, 8, 10, 12, 14, 16, 18, 20, 22, /* 0-9 */
24, 28, 30, 32, 34, 36, 38, 40, 42, 44, /* 10-19 */
46, 48, 50, 52, 54, 56, 58, 60, 62, 64, /* 20-29 */
66, 68, 70, 72, 74, 76, 78, 2, 26, 80, /* 30-39 */
};
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
/* packet start offsets (in usecs) */
static const uint16_t g_ble_phy_mode_pkt_start_off[BLE_PHY_NUM_MODE] = {
[BLE_PHY_MODE_1M] = 40,
[BLE_PHY_MODE_2M] = 24,
[BLE_PHY_MODE_CODED_125KBPS] = 376,
[BLE_PHY_MODE_CODED_500KBPS] = 376
};
#endif
/* Various radio timings */
/* Radio ramp-up times in usecs (fast mode) */
#define BLE_PHY_T_TXENFAST (XCVR_TX_RADIO_RAMPUP_USECS)
#define BLE_PHY_T_RXENFAST (XCVR_RX_RADIO_RAMPUP_USECS)
/* delay between EVENTS_READY and start of tx */
static const uint8_t g_ble_phy_t_txdelay[BLE_PHY_NUM_MODE] = {
[BLE_PHY_MODE_1M] = 4,
[BLE_PHY_MODE_2M] = 3,
[BLE_PHY_MODE_CODED_125KBPS] = 5,
[BLE_PHY_MODE_CODED_500KBPS] = 5
};
/* delay between EVENTS_END and end of txd packet */
static const uint8_t g_ble_phy_t_txenddelay[BLE_PHY_NUM_MODE] = {
[BLE_PHY_MODE_1M] = 4,
[BLE_PHY_MODE_2M] = 3,
[BLE_PHY_MODE_CODED_125KBPS] = 9,
[BLE_PHY_MODE_CODED_500KBPS] = 3
};
/* delay between rxd access address (w/ TERM1 for coded) and EVENTS_ADDRESS */
static const uint8_t g_ble_phy_t_rxaddrdelay[BLE_PHY_NUM_MODE] = {
[BLE_PHY_MODE_1M] = 6,
[BLE_PHY_MODE_2M] = 2,
[BLE_PHY_MODE_CODED_125KBPS] = 17,
[BLE_PHY_MODE_CODED_500KBPS] = 17
};
/* delay between end of rxd packet and EVENTS_END */
static const uint8_t g_ble_phy_t_rxenddelay[BLE_PHY_NUM_MODE] = {
[BLE_PHY_MODE_1M] = 6,
[BLE_PHY_MODE_2M] = 2,
[BLE_PHY_MODE_CODED_125KBPS] = 27,
[BLE_PHY_MODE_CODED_500KBPS] = 22
};
/* Statistics */
STATS_SECT_START(ble_phy_stats)
STATS_SECT_ENTRY(phy_isrs)
STATS_SECT_ENTRY(tx_good)
STATS_SECT_ENTRY(tx_fail)
STATS_SECT_ENTRY(tx_late)
STATS_SECT_ENTRY(tx_bytes)
STATS_SECT_ENTRY(rx_starts)
STATS_SECT_ENTRY(rx_aborts)
STATS_SECT_ENTRY(rx_valid)
STATS_SECT_ENTRY(rx_crc_err)
STATS_SECT_ENTRY(rx_late)
STATS_SECT_ENTRY(radio_state_errs)
STATS_SECT_ENTRY(rx_hw_err)
STATS_SECT_ENTRY(tx_hw_err)
STATS_SECT_END
STATS_SECT_DECL(ble_phy_stats) ble_phy_stats;
STATS_NAME_START(ble_phy_stats)
STATS_NAME(ble_phy_stats, phy_isrs)
STATS_NAME(ble_phy_stats, tx_good)
STATS_NAME(ble_phy_stats, tx_fail)
STATS_NAME(ble_phy_stats, tx_late)
STATS_NAME(ble_phy_stats, tx_bytes)
STATS_NAME(ble_phy_stats, rx_starts)
STATS_NAME(ble_phy_stats, rx_aborts)
STATS_NAME(ble_phy_stats, rx_valid)
STATS_NAME(ble_phy_stats, rx_crc_err)
STATS_NAME(ble_phy_stats, rx_late)
STATS_NAME(ble_phy_stats, radio_state_errs)
STATS_NAME(ble_phy_stats, rx_hw_err)
STATS_NAME(ble_phy_stats, tx_hw_err)
STATS_NAME_END(ble_phy_stats)
/*
* NOTE:
* Tested the following to see what would happen:
* -> NVIC has radio irq enabled (interrupt # 1, mask 0x2).
* -> Set up nrf to receive. Clear ADDRESS event register.
* -> Enable ADDRESS interrupt on nrf5 by writing to INTENSET.
* -> Enable RX.
* -> Disable interrupts globally using OS_ENTER_CRITICAL().
* -> Wait until a packet is received and the ADDRESS event occurs.
* -> Call ble_phy_disable().
*
* At this point I wanted to see the state of the cortex NVIC. The IRQ
* pending bit was TRUE for the radio interrupt (as expected) as we never
* serviced the radio interrupt (interrupts were disabled).
*
* What was unexpected was this: without clearing the pending IRQ in the NVIC,
* when radio interrupts were re-enabled (address event bit in INTENSET set to
* 1) and the radio ADDRESS event register read 1 (it was never cleared after
* the first address event), the radio did not enter the ISR! I would have
* expected that if the following were true, an interrupt would occur:
* -> NVIC ISER bit set to TRUE
* -> NVIC ISPR bit reads TRUE, meaning interrupt is pending.
* -> Radio peripheral interrupts are enabled for some event (or events).
* -> Corresponding event register(s) in radio peripheral read 1.
*
* Not sure what the end result of all this is. We will clear the pending
* bit in the NVIC just to be sure when we disable the PHY.
*/
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
/*
* Per nordic, the number of bytes needed for scratch is 16 + MAX_PKT_SIZE.
* However, when I used a smaller size it still overwrote the scratchpad. Until
* I figure this out I am just going to allocate 67 words so we have enough
* space for 267 bytes of scratch. I used 268 bytes since not sure if this
* needs to be aligned and burning a byte is no big deal.
*/
//#define NRF_ENC_SCRATCH_WORDS (((MYNEWT_VAL(BLE_LL_MAX_PKT_SIZE) + 16) + 3) / 4)
#define NRF_ENC_SCRATCH_WORDS (67)
uint32_t g_nrf_encrypt_scratchpad[NRF_ENC_SCRATCH_WORDS];
struct nrf_ccm_data
{
uint8_t key[16];
uint64_t pkt_counter;
uint8_t dir_bit;
uint8_t iv[8];
} __attribute__((packed));
struct nrf_ccm_data g_nrf_ccm_data;
#endif
static void
ble_phy_apply_errata_102_106_107(void)
{
/* [102] RADIO: PAYLOAD/END events delayed or not triggered after ADDRESS
* [106] RADIO: Higher CRC error rates for some access addresses
* [107] RADIO: Immediate address match for access addresses containing MSBs 0x00
*/
*(volatile uint32_t *)0x40001774 = ((*(volatile uint32_t *)0x40001774) &
0xfffffffe) | 0x01000000;
}
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
/* Packet start offset (in usecs). This is the preamble plus access address.
* For LE Coded PHY this also includes CI and TERM1. */
uint32_t
ble_phy_mode_pdu_start_off(int phy_mode)
{
return g_ble_phy_mode_pkt_start_off[phy_mode];
}
#if NRF52840_XXAA
static inline bool
ble_phy_mode_is_coded(uint8_t phy_mode)
{
return (phy_mode == BLE_PHY_MODE_CODED_125KBPS) ||
(phy_mode == BLE_PHY_MODE_CODED_500KBPS);
}
static void
ble_phy_apply_nrf52840_errata(uint8_t new_phy_mode)
{
bool new_coded = ble_phy_mode_is_coded(new_phy_mode);
bool cur_coded = ble_phy_mode_is_coded(g_ble_phy_data.phy_cur_phy_mode);
/*
* Workarounds should be applied only when switching to/from LE Coded PHY
* so no need to apply them every time.
*
* nRF52840 Engineering A Errata v1.2
* [164] RADIO: Low sensitivity in long range mode
*
* nRF52840 Rev 1 Errata
* [191] RADIO: High packet error rate in BLE Long Range mode
*/
if (new_coded == cur_coded) {
return;
}
if (new_coded) {
#if MYNEWT_VAL(BLE_PHY_NRF52840_ERRATA_164)
/* [164] */
*(volatile uint32_t *)0x4000173C |= 0x80000000;
*(volatile uint32_t *)0x4000173C =
((*(volatile uint32_t *)0x4000173C & 0xFFFFFF00) | 0x5C);
#endif
#if MYNEWT_VAL(BLE_PHY_NRF52840_ERRATA_191)
/* [191] */
*(volatile uint32_t *) 0x40001740 =
((*((volatile uint32_t *) 0x40001740)) & 0x7FFF00FF) |
0x80000000 | (((uint32_t)(196)) << 8);
#endif
} else {
#if MYNEWT_VAL(BLE_PHY_NRF52840_ERRATA_164)
/* [164] */
*(volatile uint32_t *)0x4000173C &= ~0x80000000;
#endif
#if MYNEWT_VAL(BLE_PHY_NRF52840_ERRATA_191)
/* [191] */
*(volatile uint32_t *) 0x40001740 =
((*((volatile uint32_t *) 0x40001740)) & 0x7FFFFFFF);
#endif
}
}
#endif
static void
ble_phy_mode_apply(uint8_t phy_mode)
{
if (phy_mode == g_ble_phy_data.phy_cur_phy_mode) {
return;
}
#if NRF52840_XXAA
ble_phy_apply_nrf52840_errata(phy_mode);
#endif
switch (phy_mode) {
case BLE_PHY_MODE_1M:
NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_1Mbit;
NRF_RADIO->PCNF0 = NRF_PCNF0_1M;
break;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_2M_PHY)
case BLE_PHY_MODE_2M:
NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_2Mbit;
NRF_RADIO->PCNF0 = NRF_PCNF0_2M;
break;
#endif
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_CODED_PHY)
case BLE_PHY_MODE_CODED_125KBPS:
NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_LR125Kbit;
NRF_RADIO->PCNF0 = NRF_PCNF0_CODED;
break;
case BLE_PHY_MODE_CODED_500KBPS:
NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_LR500Kbit;
NRF_RADIO->PCNF0 = NRF_PCNF0_CODED;
break;
#endif
default:
assert(0);
}
g_ble_phy_data.phy_cur_phy_mode = phy_mode;
}
void
ble_phy_mode_set(uint8_t tx_phy_mode, uint8_t rx_phy_mode)
{
g_ble_phy_data.phy_tx_phy_mode = tx_phy_mode;
g_ble_phy_data.phy_rx_phy_mode = rx_phy_mode;
}
#endif
int
ble_phy_get_cur_phy(void)
{
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
switch (g_ble_phy_data.phy_cur_phy_mode) {
case BLE_PHY_MODE_1M:
return BLE_PHY_1M;
case BLE_PHY_MODE_2M:
return BLE_PHY_2M;
case BLE_PHY_MODE_CODED_125KBPS:
case BLE_PHY_MODE_CODED_500KBPS:
return BLE_PHY_CODED;
default:
assert(0);
return -1;
}
#else
return BLE_PHY_1M;
#endif
}
/**
* Copies the data from the phy receive buffer into a mbuf chain.
*
* @param dptr Pointer to receive buffer
* @param rxpdu Pointer to already allocated mbuf chain
*
* NOTE: the packet header already has the total mbuf length in it. The
* lengths of the individual mbufs are not set prior to calling.
*
*/
void
ble_phy_rxpdu_copy(uint8_t *dptr, struct os_mbuf *rxpdu)
{
uint32_t rem_len;
uint32_t copy_len;
uint32_t block_len;
uint32_t block_rem_len;
void *dst;
void *src;
struct os_mbuf * om;
/* Better be aligned */
assert(((uint32_t)dptr & 3) == 0);
block_len = rxpdu->om_omp->omp_databuf_len;
rem_len = OS_MBUF_PKTHDR(rxpdu)->omp_len;
src = dptr;
/*
* Setup for copying from first mbuf which is shorter due to packet header
* and extra leading space
*/
copy_len = block_len - rxpdu->om_pkthdr_len - 4;
om = rxpdu;
dst = om->om_data;
while (true) {
/*
* Always copy blocks of length aligned to word size, only last mbuf
* will have remaining non-word size bytes appended.
*/
block_rem_len = copy_len;
copy_len = min(copy_len, rem_len);
copy_len &= ~3;
dst = om->om_data;
om->om_len = copy_len;
rem_len -= copy_len;
block_rem_len -= copy_len;
__asm__ volatile (".syntax unified \n"
" mov r4, %[len] \n"
" b 2f \n"
"1: ldr r3, [%[src], %[len]] \n"
" str r3, [%[dst], %[len]] \n"
"2: subs %[len], #4 \n"
" bpl 1b \n"
" adds %[src], %[src], r4 \n"
" adds %[dst], %[dst], r4 \n"
: [dst] "+r" (dst), [src] "+r" (src),
[len] "+r" (copy_len)
:
: "r3", "r4", "memory"
);
if ((rem_len < 4) && (block_rem_len >= rem_len)) {
break;
}
/* Move to next mbuf */
om = SLIST_NEXT(om, om_next);
copy_len = block_len;
}
/* Copy remaining bytes, if any, to last mbuf */
om->om_len += rem_len;
__asm__ volatile (".syntax unified \n"
" b 2f \n"
"1: ldrb r3, [%[src], %[len]] \n"
" strb r3, [%[dst], %[len]] \n"
"2: subs %[len], #1 \n"
" bpl 1b \n"
: [len] "+r" (rem_len)
: [dst] "r" (dst), [src] "r" (src)
: "r3", "memory"
);
/* Copy header */
memcpy(BLE_MBUF_HDR_PTR(rxpdu), &g_ble_phy_data.rxhdr,
sizeof(struct ble_mbuf_hdr));
}
/**
* Called when we want to wait if the radio is in either the rx or tx
* disable states. We want to wait until that state is over before doing
* anything to the radio
*/
static void
nrf_wait_disabled(void)
{
uint32_t state;
state = NRF_RADIO->STATE;
if (state != RADIO_STATE_STATE_Disabled) {
if ((state == RADIO_STATE_STATE_RxDisable) ||
(state == RADIO_STATE_STATE_TxDisable)) {
/* This will end within a short time (6 usecs). Just poll */
while (NRF_RADIO->STATE == state) {
/* If this fails, something is really wrong. Should last
* no more than 6 usecs */
}
}
}
}
/**
*
*
*/
static int
ble_phy_set_start_time(uint32_t cputime, uint8_t rem_usecs, bool tx)
{
uint32_t next_cc;
uint32_t cur_cc;
uint32_t cntr;
uint32_t delta;
/*
* We need to adjust start time to include radio ramp-up and TX pipeline
* delay (the latter only if applicable, so only for TX).
*
* Radio ramp-up time is 40 usecs and TX delay is 3 or 5 usecs depending on
* phy, thus we'll offset RTC by 2 full ticks (61 usecs) and then compensate
* using TIMER0 with 1 usec precision.
*/
cputime -= 2;
rem_usecs += 61;
if (tx) {
rem_usecs -= BLE_PHY_T_TXENFAST;
rem_usecs -= g_ble_phy_t_txdelay[g_ble_phy_data.phy_cur_phy_mode];
} else {
rem_usecs -= BLE_PHY_T_RXENFAST;
}
/*
* rem_usecs will be no more than 2 ticks, but if it is more than single
* tick then we should better count one more low-power tick rather than
* 30 high-power usecs. Also make sure we don't set TIMER0 CC to 0 as the
* compare won't occur.
*/
if (rem_usecs > 30) {
cputime++;
rem_usecs -= 30;
}
/*
* Can we set the RTC compare to start TIMER0? We can do it if:
* a) Current compare value is not N+1 or N+2 ticks from current
* counter.
* b) The value we want to set is not at least N+2 from current
* counter.
*
* NOTE: since the counter can tick 1 while we do these calculations we
* need to account for it.
*/
next_cc = cputime & 0xffffff;
cur_cc = NRF_RTC0->CC[0];
cntr = NRF_RTC0->COUNTER;
delta = (cur_cc - cntr) & 0xffffff;
if ((delta <= 3) && (delta != 0)) {
return -1;
}
delta = (next_cc - cntr) & 0xffffff;
if ((delta & 0x800000) || (delta < 3)) {
return -1;
}
/* Clear and set TIMER0 to fire off at proper time */
NRF_TIMER0->TASKS_CLEAR = 1;
NRF_TIMER0->CC[0] = rem_usecs;
NRF_TIMER0->EVENTS_COMPARE[0] = 0;
/* Set RTC compare to start TIMER0 */
NRF_RTC0->EVENTS_COMPARE[0] = 0;
NRF_RTC0->CC[0] = next_cc;
NRF_RTC0->EVTENSET = RTC_EVTENSET_COMPARE0_Msk;
/* Enable PPI */
NRF_PPI->CHENSET = PPI_CHEN_CH31_Msk;
/* Store the cputime at which we set the RTC */
g_ble_phy_data.phy_start_cputime = cputime;
return 0;
}
static int
ble_phy_set_start_now(void)
{
os_sr_t sr;
uint32_t now;
OS_ENTER_CRITICAL(sr);
/*
* Set TIMER0 to fire immediately. We can't set CC to 0 as compare will not
* occur in such case.
*/
NRF_TIMER0->TASKS_CLEAR = 1;
NRF_TIMER0->CC[0] = 1;
NRF_TIMER0->EVENTS_COMPARE[0] = 0;
/*
* Set RTC compare to start TIMER0. We need to set it to at least N+2 ticks
* from current value to guarantee triggering compare event, but let's set
* it to N+3 to account for possible extra tick on RTC0 during these
* operations.
*/
now = os_cputime_get32();
NRF_RTC0->EVENTS_COMPARE[0] = 0;
NRF_RTC0->CC[0] = now + 3;
NRF_RTC0->EVTENSET = RTC_EVTENSET_COMPARE0_Msk;
/* Enable PPI */
NRF_PPI->CHENSET = PPI_CHEN_CH31_Msk;
/*
* Store the cputime at which we set the RTC
*
* XXX Compare event may be triggered on previous CC value (if it was set to
* less than N+2) so in rare cases actual start time may be 2 ticks earlier
* than what we expect. Since this is only used on RX, it may cause AUX scan
* to be scheduled 1 or 2 ticks too late so we'll miss it - it's acceptable
* for now.
*/
g_ble_phy_data.phy_start_cputime = now + 3;
OS_EXIT_CRITICAL(sr);
return 0;
}
/**
* Function is used to set PPI so that we can time out waiting for a reception
* to occur. This happens for two reasons: we have sent a packet and we are
* waiting for a respons (txrx should be set to ENABLE_TXRX) or we are
* starting a connection event and we are a slave and we are waiting for the
* master to send us a packet (txrx should be set to ENABLE_RX).
*
* NOTE: when waiting for a txrx turn-around, wfr_usecs is not used as there
* is no additional time to wait; we know when we should receive the address of
* the received frame.
*
* @param txrx Flag denoting if this wfr is a txrx turn-around or not.
* @param tx_phy_mode phy mode for last TX (only valid for TX->RX)
* @param wfr_usecs Amount of usecs to wait.
*/
void
ble_phy_wfr_enable(int txrx, uint8_t tx_phy_mode, uint32_t wfr_usecs)
{
uint32_t end_time;
uint8_t phy;
phy = g_ble_phy_data.phy_cur_phy_mode;
if (txrx == BLE_PHY_WFR_ENABLE_TXRX) {
/* RX shall start exactly T_IFS after TX end captured in CC[2] */
end_time = NRF_TIMER0->CC[2] + BLE_LL_IFS;
/* Adjust for delay between EVENT_END and actual TX end time */
end_time += g_ble_phy_t_txenddelay[tx_phy_mode];
/* Wait a bit longer due to allowed active clock accuracy */
end_time += 2;
/*
* It's possible that we'll capture PDU start time at the end of timer
* cycle and since wfr expires at the beginning of calculated timer
* cycle it can be almost 1 usec too early. Let's compensate for this
* by waiting 1 usec more.
*/
end_time += 1;
#if MYNEWT_VAL(BLE_PHY_CODED_RX_IFS_EXTRA_MARGIN) > 0
if ((phy == BLE_PHY_MODE_CODED_125KBPS) ||
(phy == BLE_PHY_MODE_CODED_500KBPS)) {
/*
* Some controllers exceed T_IFS when transmitting on coded phy
* so let's wait a bit longer to be able to talk to them if this
* workaround is enabled.
*/
end_time += MYNEWT_VAL(BLE_PHY_CODED_RX_IFS_EXTRA_MARGIN);
}
#endif
} else {
/*
* RX shall start no later than wfr_usecs after RX enabled.
* CC[0] is the time of RXEN so adjust for radio ram-up.
* Do not add jitter since this is already covered by LL.
*/
end_time = NRF_TIMER0->CC[0] + BLE_PHY_T_RXENFAST + wfr_usecs;
}
/*
* Note: on LE Coded EVENT_ADDRESS is fired after TERM1 is received, so
* we are actually calculating relative to start of packet payload
* which is fine.
*/
/* Adjust for receiving access address since this triggers EVENT_ADDRESS */
end_time += ble_phy_mode_pdu_start_off(phy);
/* Adjust for delay between actual access address RX and EVENT_ADDRESS */
end_time += g_ble_phy_t_rxaddrdelay[phy];
/* wfr_secs is the time from rxen until timeout */
NRF_TIMER0->CC[3] = end_time;
NRF_TIMER0->EVENTS_COMPARE[3] = 0;
/* Enable wait for response PPI */
NRF_PPI->CHENSET = (PPI_CHEN_CH4_Msk | PPI_CHEN_CH5_Msk);
/* Enable the disabled interrupt so we time out on events compare */
NRF_RADIO->INTENSET = RADIO_INTENSET_DISABLED_Msk;
/*
* It may happen that if CPU is halted for a brief moment (e.g. during flash
* erase or write), TIMER0 already counted past CC[3] and thus wfr will not
* fire as expected. In case this happened, let's just disable PPIs for wfr
* and trigger wfr manually (i.e. disable radio).
*
* Note that the same applies to RX start time set in CC[0] but since it
* should fire earlier than wfr, fixing wfr is enough.
*
* CC[1] is only used as a reference on RX start, we do not need it here so
* it can be used to read TIMER0 counter.
*/
NRF_TIMER0->TASKS_CAPTURE[1] = 1;
if (NRF_TIMER0->CC[1] > NRF_TIMER0->CC[3]) {
NRF_PPI->CHENCLR = PPI_CHEN_CH4_Msk | PPI_CHEN_CH5_Msk;
NRF_RADIO->TASKS_DISABLE = 1;
}
}
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
static uint32_t
ble_phy_get_ccm_datarate(void)
{
#if BLE_LL_BT5_PHY_SUPPORTED
switch (g_ble_phy_data.phy_cur_phy_mode) {
case BLE_PHY_MODE_1M:
return CCM_MODE_DATARATE_1Mbit << CCM_MODE_DATARATE_Pos;
case BLE_PHY_MODE_2M:
return CCM_MODE_DATARATE_2Mbit << CCM_MODE_DATARATE_Pos;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_CODED_PHY)
case BLE_PHY_MODE_CODED_125KBPS:
return CCM_MODE_DATARATE_125Kbps << CCM_MODE_DATARATE_Pos;
case BLE_PHY_MODE_CODED_500KBPS:
return CCM_MODE_DATARATE_500Kbps << CCM_MODE_DATARATE_Pos;
#endif
}
assert(0);
return 0;
#else
return CCM_MODE_DATARATE_1Mbit << CCM_MODE_DATARATE_Pos;
#endif
}
#endif
/**
* Setup transceiver for receive.
*/
static void
ble_phy_rx_xcvr_setup(void)
{
uint8_t *dptr;
dptr = (uint8_t *)&g_ble_phy_rx_buf[0];
dptr += 3;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
if (g_ble_phy_data.phy_encrypted) {
NRF_RADIO->PACKETPTR = (uint32_t)&g_ble_phy_enc_buf[0];
NRF_CCM->INPTR = (uint32_t)&g_ble_phy_enc_buf[0];
NRF_CCM->OUTPTR = (uint32_t)dptr;
NRF_CCM->SCRATCHPTR = (uint32_t)&g_nrf_encrypt_scratchpad[0];
NRF_CCM->MODE = CCM_MODE_LENGTH_Msk | CCM_MODE_MODE_Decryption |
ble_phy_get_ccm_datarate();
NRF_CCM->CNFPTR = (uint32_t)&g_nrf_ccm_data;
NRF_CCM->SHORTS = 0;
NRF_CCM->EVENTS_ERROR = 0;
NRF_CCM->EVENTS_ENDCRYPT = 0;
NRF_CCM->TASKS_KSGEN = 1;
NRF_PPI->CHENSET = PPI_CHEN_CH25_Msk;
} else {
NRF_RADIO->PACKETPTR = (uint32_t)dptr;
}
#else
NRF_RADIO->PACKETPTR = (uint32_t)dptr;
#endif
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
if (g_ble_phy_data.phy_privacy) {
NRF_AAR->ENABLE = AAR_ENABLE_ENABLE_Enabled;
NRF_AAR->IRKPTR = (uint32_t)&g_nrf_irk_list[0];
NRF_AAR->SCRATCHPTR = (uint32_t)&g_ble_phy_data.phy_aar_scratch;
NRF_AAR->EVENTS_END = 0;
NRF_AAR->EVENTS_RESOLVED = 0;
NRF_AAR->EVENTS_NOTRESOLVED = 0;
} else {
if (g_ble_phy_data.phy_encrypted == 0) {
NRF_AAR->ENABLE = AAR_ENABLE_ENABLE_Disabled;
}
}
#endif
/* Turn off trigger TXEN on output compare match and AAR on bcmatch */
NRF_PPI->CHENCLR = PPI_CHEN_CH20_Msk | PPI_CHEN_CH23_Msk;
/* Reset the rx started flag. Used for the wait for response */
g_ble_phy_data.phy_rx_started = 0;
g_ble_phy_data.phy_state = BLE_PHY_STATE_RX;
#if BLE_LL_BT5_PHY_SUPPORTED
/*
* On Coded PHY there are CI and TERM1 fields before PDU starts so we need
* to take this into account when setting up BCC.
*/
if (g_ble_phy_data.phy_cur_phy_mode == BLE_PHY_MODE_CODED_125KBPS ||
g_ble_phy_data.phy_cur_phy_mode == BLE_PHY_MODE_CODED_500KBPS) {
g_ble_phy_data.phy_bcc_offset = 5;
} else {
g_ble_phy_data.phy_bcc_offset = 0;
}
#else
g_ble_phy_data.phy_bcc_offset = 0;
#endif
/* I want to know when 1st byte received (after address) */
NRF_RADIO->BCC = 8 + g_ble_phy_data.phy_bcc_offset; /* in bits */
NRF_RADIO->EVENTS_ADDRESS = 0;
NRF_RADIO->EVENTS_DEVMATCH = 0;
NRF_RADIO->EVENTS_BCMATCH = 0;
NRF_RADIO->EVENTS_RSSIEND = 0;
NRF_RADIO->EVENTS_CRCOK = 0;
NRF_RADIO->SHORTS = RADIO_SHORTS_END_DISABLE_Msk |
RADIO_SHORTS_READY_START_Msk |
RADIO_SHORTS_ADDRESS_BCSTART_Msk |
RADIO_SHORTS_ADDRESS_RSSISTART_Msk |
RADIO_SHORTS_DISABLED_RSSISTOP_Msk;
NRF_RADIO->INTENSET = RADIO_INTENSET_ADDRESS_Msk;
}
/**
* Called from interrupt context when the transmit ends
*
*/
static void
ble_phy_tx_end_isr(void)
{
uint8_t tx_phy_mode;
uint8_t was_encrypted;
uint8_t transition;
uint32_t rx_time;
uint32_t wfr_time;
/* Store PHY on which we've just transmitted smth */
tx_phy_mode = g_ble_phy_data.phy_cur_phy_mode;
/* If this transmission was encrypted we need to remember it */
was_encrypted = g_ble_phy_data.phy_encrypted;
(void)was_encrypted;
/* Better be in TX state! */
assert(g_ble_phy_data.phy_state == BLE_PHY_STATE_TX);
/* Clear events and clear interrupt on disabled event */
NRF_RADIO->EVENTS_DISABLED = 0;
NRF_RADIO->INTENCLR = RADIO_INTENCLR_DISABLED_Msk;
NRF_RADIO->EVENTS_END = 0;
wfr_time = NRF_RADIO->SHORTS;
(void)wfr_time;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
/*
* XXX: not sure what to do. We had a HW error during transmission.
* For now I just count a stat but continue on like all is good.
*/
if (was_encrypted) {
if (NRF_CCM->EVENTS_ERROR) {
STATS_INC(ble_phy_stats, tx_hw_err);
NRF_CCM->EVENTS_ERROR = 0;
}
}
#endif
/* Call transmit end callback */
if (g_ble_phy_data.txend_cb) {
g_ble_phy_data.txend_cb(g_ble_phy_data.txend_arg);
}
transition = g_ble_phy_data.phy_transition;
if (transition == BLE_PHY_TRANSITION_TX_RX) {
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
ble_phy_mode_apply(g_ble_phy_data.phy_rx_phy_mode);
#endif
/* Packet pointer needs to be reset. */
ble_phy_rx_xcvr_setup();
ble_phy_wfr_enable(BLE_PHY_WFR_ENABLE_TXRX, tx_phy_mode, 0);
/* Schedule RX exactly T_IFS after TX end captured in CC[2] */
rx_time = NRF_TIMER0->CC[2] + BLE_LL_IFS;
/* Adjust for delay between EVENT_END and actual TX end time */
rx_time += g_ble_phy_t_txenddelay[tx_phy_mode];
/* Adjust for radio ramp-up */
rx_time -= BLE_PHY_T_RXENFAST;
/* Start listening a bit earlier due to allowed active clock accuracy */
rx_time -= 2;
NRF_TIMER0->CC[0] = rx_time;
NRF_TIMER0->EVENTS_COMPARE[0] = 0;
NRF_PPI->CHENSET = PPI_CHEN_CH21_Msk;
} else {
/*
* XXX: not sure we need to stop the timer here all the time. Or that
* it should be stopped here.
*/
NRF_TIMER0->TASKS_STOP = 1;
NRF_TIMER0->TASKS_SHUTDOWN = 1;
NRF_PPI->CHENCLR = PPI_CHEN_CH4_Msk | PPI_CHEN_CH5_Msk |
PPI_CHEN_CH20_Msk | PPI_CHEN_CH31_Msk;
assert(transition == BLE_PHY_TRANSITION_NONE);
}
}
static inline uint8_t
ble_phy_get_cur_rx_phy_mode(void)
{
uint8_t phy;
phy = g_ble_phy_data.phy_cur_phy_mode;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_CODED_PHY)
/*
* For Coded PHY mode can be set to either codings since actual coding is
* set in packet header. However, here we need actual coding of received
* packet as this determines pipeline delays so need to figure this out
* using CI field.
*/
if ((phy == BLE_PHY_MODE_CODED_125KBPS) ||
(phy == BLE_PHY_MODE_CODED_500KBPS)) {
phy = NRF_RADIO->PDUSTAT & RADIO_PDUSTAT_CISTAT_Msk ?
BLE_PHY_MODE_CODED_500KBPS :
BLE_PHY_MODE_CODED_125KBPS;
}
#endif
return phy;
}
static void
ble_phy_rx_end_isr(void)
{
int rc;
uint8_t *dptr;
uint8_t crcok;
uint32_t tx_time;
struct ble_mbuf_hdr *ble_hdr;
/* Clear events and clear interrupt */
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->INTENCLR = RADIO_INTENCLR_END_Msk;
/* Disable automatic RXEN */
NRF_PPI->CHENCLR = PPI_CHEN_CH21_Msk;
/* Set RSSI and CRC status flag in header */
ble_hdr = &g_ble_phy_data.rxhdr;
assert(NRF_RADIO->EVENTS_RSSIEND != 0);
ble_hdr->rxinfo.rssi = (-1 * NRF_RADIO->RSSISAMPLE) +
g_ble_phy_data.rx_pwr_compensation;
dptr = (uint8_t *)&g_ble_phy_rx_buf[0];
dptr += 3;
/* Count PHY crc errors and valid packets */
crcok = NRF_RADIO->EVENTS_CRCOK;
if (!crcok) {
STATS_INC(ble_phy_stats, rx_crc_err);
} else {
STATS_INC(ble_phy_stats, rx_valid);
ble_hdr->rxinfo.flags |= BLE_MBUF_HDR_F_CRC_OK;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
if (g_ble_phy_data.phy_encrypted) {
/* Only set MIC failure flag if frame is not zero length */
if ((dptr[1] != 0) && (NRF_CCM->MICSTATUS == 0)) {
ble_hdr->rxinfo.flags |= BLE_MBUF_HDR_F_MIC_FAILURE;
}
/*
* XXX: not sure how to deal with this. This should not
* be a MIC failure but we should not hand it up. I guess
* this is just some form of rx error and that is how we
* handle it? For now, just set CRC error flags
*/
if (NRF_CCM->EVENTS_ERROR) {
STATS_INC(ble_phy_stats, rx_hw_err);
ble_hdr->rxinfo.flags &= ~BLE_MBUF_HDR_F_CRC_OK;
}
/*
* XXX: This is a total hack work-around for now but I dont
* know what else to do. If ENDCRYPT is not set and we are
* encrypted we need to not trust this frame and drop it.
*/
if (NRF_CCM->EVENTS_ENDCRYPT == 0) {
STATS_INC(ble_phy_stats, rx_hw_err);
ble_hdr->rxinfo.flags &= ~BLE_MBUF_HDR_F_CRC_OK;
}
}
#endif
}
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
ble_phy_mode_apply(g_ble_phy_data.phy_tx_phy_mode);
#endif
/*
* Let's schedule TX now and we will just cancel it after processing RXed
* packet if we don't need TX.
*
* We need this to initiate connection in case AUX_CONNECT_REQ was sent on
* LE Coded S8. In this case the time we process RXed packet is roughly the
* same as the limit when we need to have TX scheduled (i.e. TIMER0 and PPI
* armed) so we may simply miss the slot and set the timer in the past.
*
* When TX is scheduled in advance, we may event process packet a bit longer
* during radio ramp-up - this gives us extra 40 usecs which is more than
* enough.
*/
/* Schedule TX exactly T_IFS after RX end captured in CC[2] */
tx_time = NRF_TIMER0->CC[2] + BLE_LL_IFS;
/* Adjust for delay between actual RX end time and EVENT_END */
tx_time -= g_ble_phy_t_rxenddelay[ble_hdr->rxinfo.phy_mode];
/* Adjust for radio ramp-up */
tx_time -= BLE_PHY_T_TXENFAST;
/* Adjust for delay between EVENT_READY and actual TX start time */
tx_time -= g_ble_phy_t_txdelay[g_ble_phy_data.phy_cur_phy_mode];
NRF_TIMER0->CC[0] = tx_time;
NRF_TIMER0->EVENTS_COMPARE[0] = 0;
NRF_PPI->CHENSET = PPI_CHEN_CH20_Msk;
/*
* XXX: Hack warning!
*
* It may happen (during flash erase) that CPU is stopped for a moment and
* TIMER0 already counted past CC[0]. In such case we will be stuck waiting
* for TX to start since EVENTS_COMPARE[0] will not happen any time soon.
* For now let's set a flag denoting that we are late in RX-TX transition so
* ble_phy_tx() will fail - this allows everything to cleanup nicely without
* the need for extra handling in many places.
*
* Note: CC[3] is used only for wfr which we do not need here.
*/
NRF_TIMER0->TASKS_CAPTURE[3] = 1;
if (NRF_TIMER0->CC[3] > NRF_TIMER0->CC[0]) {
NRF_PPI->CHENCLR = PPI_CHEN_CH20_Msk;
g_ble_phy_data.phy_transition_late = 1;
}
/*
* XXX: This is a horrible ugly hack to deal with the RAM S1 byte
* that is not sent over the air but is present here. Simply move the
* data pointer to deal with it. Fix this later.
*/
dptr[2] = dptr[1];
dptr[1] = dptr[0];
rc = ble_ll_rx_end(dptr + 1, ble_hdr);
if (rc < 0) {
ble_phy_disable();
}
}
static bool
ble_phy_rx_start_isr(void)
{
int rc;
uint32_t state;
uint32_t usecs;
uint32_t pdu_usecs;
uint32_t ticks;
struct ble_mbuf_hdr *ble_hdr;
uint8_t *dptr;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
int adva_offset;
#endif
dptr = (uint8_t *)&g_ble_phy_rx_buf[0];
/* Clear events and clear interrupt */
NRF_RADIO->EVENTS_ADDRESS = 0;
/* Clear wfr timer channels and DISABLED interrupt */
NRF_RADIO->INTENCLR = RADIO_INTENCLR_DISABLED_Msk | RADIO_INTENCLR_ADDRESS_Msk;
NRF_PPI->CHENCLR = PPI_CHEN_CH4_Msk | PPI_CHEN_CH5_Msk;
/* Initialize the ble mbuf header */
ble_hdr = &g_ble_phy_data.rxhdr;
ble_hdr->rxinfo.flags = ble_ll_state_get();
ble_hdr->rxinfo.channel = g_ble_phy_data.phy_chan;
ble_hdr->rxinfo.handle = 0;
ble_hdr->rxinfo.phy = ble_phy_get_cur_phy();
ble_hdr->rxinfo.phy_mode = ble_phy_get_cur_rx_phy_mode();
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_EXT_ADV)
ble_hdr->rxinfo.user_data = NULL;
#endif
/*
* Calculate accurate packets start time (with remainder)
*
* We may start receiving packet somewhere during preamble in which case
* it is possible that actual transmission started before TIMER0 was
* running - need to take this into account.
*/
ble_hdr->beg_cputime = g_ble_phy_data.phy_start_cputime;
usecs = NRF_TIMER0->CC[1];
pdu_usecs = ble_phy_mode_pdu_start_off(ble_hdr->rxinfo.phy_mode) +
g_ble_phy_t_rxaddrdelay[ble_hdr->rxinfo.phy_mode];
if (usecs < pdu_usecs) {
g_ble_phy_data.phy_start_cputime--;
usecs += 30;
}
usecs -= pdu_usecs;
ticks = os_cputime_usecs_to_ticks(usecs);
usecs -= os_cputime_ticks_to_usecs(ticks);
if (usecs == 31) {
usecs = 0;
++ticks;
}
ble_hdr->beg_cputime += ticks;
ble_hdr->rem_usecs = usecs;
/* XXX: I wonder if we always have the 1st byte. If we need to wait for
* rx chain delay, it could be 18 usecs from address interrupt. The
nrf52 may be able to get here early. */
/* Wait to get 1st byte of frame */
while (1) {
state = NRF_RADIO->STATE;
if (NRF_RADIO->EVENTS_BCMATCH != 0) {
break;
}
/*
* If state is disabled, we should have the BCMATCH. If not,
* something is wrong!
*/
if (state == RADIO_STATE_STATE_Disabled) {
NRF_RADIO->INTENCLR = NRF_RADIO_IRQ_MASK_ALL;
NRF_RADIO->SHORTS = 0;
return false;
}
}
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
/*
* If privacy is enabled and received PDU has TxAdd bit set (i.e. random
* address) we try to resolve address using AAR.
*/
if (g_ble_phy_data.phy_privacy && (dptr[3] & 0x40)) {
/*
* AdvA is located at 4th octet in RX buffer (after S0, length an S1
* fields). In case of extended advertising PDU we need to add 2 more
* octets for extended header.
*/
adva_offset = (dptr[3] & 0x0f) == 0x07 ? 2 : 0;
NRF_AAR->ADDRPTR = (uint32_t)(dptr + 3 + adva_offset);
/* Trigger AAR after last bit of AdvA is received */
NRF_RADIO->EVENTS_BCMATCH = 0;
NRF_PPI->CHENSET = PPI_CHEN_CH23_Msk;
NRF_RADIO->BCC = (BLE_LL_PDU_HDR_LEN + adva_offset + BLE_DEV_ADDR_LEN) * 8 +
g_ble_phy_data.phy_bcc_offset;
}
#endif
/* Call Link Layer receive start function */
rc = ble_ll_rx_start(dptr + 3,
g_ble_phy_data.phy_chan,
&g_ble_phy_data.rxhdr);
if (rc >= 0) {
/* Set rx started flag and enable rx end ISR */
g_ble_phy_data.phy_rx_started = 1;
NRF_RADIO->INTENSET = RADIO_INTENSET_END_Msk;
} else {
/* Disable PHY */
ble_phy_disable();
STATS_INC(ble_phy_stats, rx_aborts);
}
/* Count rx starts */
STATS_INC(ble_phy_stats, rx_starts);
return true;
}
static void
ble_phy_isr(void)
{
uint32_t irq_en;
os_trace_isr_enter();
/* Read irq register to determine which interrupts are enabled */
irq_en = NRF_RADIO->INTENCLR;
/*
* NOTE: order of checking is important! Possible, if things get delayed,
* we have both an ADDRESS and DISABLED interrupt in rx state. If we get
* an address, we disable the DISABLED interrupt.
*/
/* We get this if we have started to receive a frame */
if ((irq_en & RADIO_INTENCLR_ADDRESS_Msk) && NRF_RADIO->EVENTS_ADDRESS) {
/*
* wfr timer is calculated to expire at the exact time we should start
* receiving a packet (with 1 usec precision) so it is possible it will
* fire at the same time as EVENT_ADDRESS. If this happens, radio will
* be disabled while we are waiting for EVENT_BCCMATCH after 1st byte
* of payload is received and ble_phy_rx_start_isr() will fail. In this
* case we should not clear DISABLED irq mask so it will be handled as
* regular radio disabled event below. In other case radio was disabled
* on purpose and there's nothing more to handle so we can clear mask.
*/
if (ble_phy_rx_start_isr()) {
irq_en &= ~RADIO_INTENCLR_DISABLED_Msk;
}
}
/* Check for disabled event. This only happens for transmits now */
if ((irq_en & RADIO_INTENCLR_DISABLED_Msk) && NRF_RADIO->EVENTS_DISABLED) {
if (g_ble_phy_data.phy_state == BLE_PHY_STATE_RX) {
NRF_RADIO->EVENTS_DISABLED = 0;
ble_ll_wfr_timer_exp(NULL);
} else if (g_ble_phy_data.phy_state == BLE_PHY_STATE_IDLE) {
assert(0);
} else {
ble_phy_tx_end_isr();
}
}
/* Receive packet end (we dont enable this for transmit) */
if ((irq_en & RADIO_INTENCLR_END_Msk) && NRF_RADIO->EVENTS_END) {
ble_phy_rx_end_isr();
}
g_ble_phy_data.phy_transition_late = 0;
/* Ensures IRQ is cleared */
irq_en = NRF_RADIO->SHORTS;
/* Count # of interrupts */
STATS_INC(ble_phy_stats, phy_isrs);
os_trace_isr_exit();
}
#if MYNEWT_VAL(BLE_PHY_DBG_TIME_TXRXEN_READY_PIN) >= 0 || \
MYNEWT_VAL(BLE_PHY_DBG_TIME_ADDRESS_END_PIN) >= 0 || \
MYNEWT_VAL(BLE_PHY_DBG_TIME_WFR_PIN) >= 0
static inline void
ble_phy_dbg_time_setup_gpiote(int index, int pin)
{
NRF_GPIO_Type *port;
#if NRF52840_XXAA
port = pin > 31 ? NRF_P1 : NRF_P0;
pin &= 0x1f;
#else
port = NRF_P0;
#endif
/* Configure GPIO directly to avoid dependency to hal_gpio (for porting) */
port->DIRSET = (1 << pin);
port->OUTCLR = (1 << pin);
NRF_GPIOTE->CONFIG[index] =
(GPIOTE_CONFIG_MODE_Task << GPIOTE_CONFIG_MODE_Pos) |
((pin & 0x1F) << GPIOTE_CONFIG_PSEL_Pos) |
#if NRF52840_XXAA
((port == NRF_P1) << GPIOTE_CONFIG_PORT_Pos);
#else
0;
#endif
}
#endif
static void
ble_phy_dbg_time_setup(void)
{
int gpiote_idx __attribute__((unused)) = 8;
/*
* We setup GPIOTE starting from last configuration index to minimize risk
* of conflict with GPIO setup via hal. It's not great solution, but since
* this is just debugging code we can live with this.
*/
#if MYNEWT_VAL(BLE_PHY_DBG_TIME_TXRXEN_READY_PIN) >= 0
ble_phy_dbg_time_setup_gpiote(--gpiote_idx,
MYNEWT_VAL(BLE_PHY_DBG_TIME_TXRXEN_READY_PIN));
NRF_PPI->CH[17].EEP = (uint32_t)&(NRF_RADIO->EVENTS_READY);
NRF_PPI->CH[17].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_CLR[gpiote_idx]);
NRF_PPI->CHENSET = PPI_CHEN_CH17_Msk;
/* CH[20] and PPI CH[21] are on to trigger TASKS_TXEN or TASKS_RXEN */
NRF_PPI->FORK[20].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_SET[gpiote_idx]);
NRF_PPI->FORK[21].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_SET[gpiote_idx]);
#endif
#if MYNEWT_VAL(BLE_PHY_DBG_TIME_ADDRESS_END_PIN) >= 0
ble_phy_dbg_time_setup_gpiote(--gpiote_idx,
MYNEWT_VAL(BLE_PHY_DBG_TIME_ADDRESS_END_PIN));
/* CH[26] and CH[27] are always on for EVENT_ADDRESS and EVENT_END */
NRF_PPI->FORK[26].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_SET[gpiote_idx]);
NRF_PPI->FORK[27].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_CLR[gpiote_idx]);
#endif
#if MYNEWT_VAL(BLE_PHY_DBG_TIME_WFR_PIN) >= 0
ble_phy_dbg_time_setup_gpiote(--gpiote_idx,
MYNEWT_VAL(BLE_PHY_DBG_TIME_WFR_PIN));
#if NRF52840_XXAA
NRF_PPI->CH[18].EEP = (uint32_t)&(NRF_RADIO->EVENTS_RXREADY);
#else
NRF_PPI->CH[18].EEP = (uint32_t)&(NRF_RADIO->EVENTS_READY);
#endif
NRF_PPI->CH[18].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_SET[gpiote_idx]);
NRF_PPI->CH[19].EEP = (uint32_t)&(NRF_RADIO->EVENTS_DISABLED);
NRF_PPI->CH[19].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_CLR[gpiote_idx]);
NRF_PPI->CHENSET = PPI_CHEN_CH18_Msk | PPI_CHEN_CH19_Msk;
/* CH[4] and CH[5] are always on for wfr */
NRF_PPI->FORK[4].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_CLR[gpiote_idx]);
NRF_PPI->FORK[5].TEP = (uint32_t)&(NRF_GPIOTE->TASKS_CLR[gpiote_idx]);
#endif
}
/**
* ble phy init
*
* Initialize the PHY.
*
* @return int 0: success; PHY error code otherwise
*/
int
ble_phy_init(void)
{
int rc;
/* Default phy to use is 1M */
g_ble_phy_data.phy_cur_phy_mode = BLE_PHY_MODE_1M;
g_ble_phy_data.phy_tx_phy_mode = BLE_PHY_MODE_1M;
g_ble_phy_data.phy_rx_phy_mode = BLE_PHY_MODE_1M;
g_ble_phy_data.rx_pwr_compensation = 0;
/* Set phy channel to an invalid channel so first set channel works */
g_ble_phy_data.phy_chan = BLE_PHY_NUM_CHANS;
/* Toggle peripheral power to reset (just in case) */
NRF_RADIO->POWER = 0;
NRF_RADIO->POWER = 1;
/* Disable all interrupts */
NRF_RADIO->INTENCLR = NRF_RADIO_IRQ_MASK_ALL;
/* Set configuration registers */
NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_1Mbit;
NRF_RADIO->PCNF0 = NRF_PCNF0;
/* XXX: should maxlen be 251 for encryption? */
NRF_RADIO->PCNF1 = NRF_MAXLEN |
(RADIO_PCNF1_ENDIAN_Little << RADIO_PCNF1_ENDIAN_Pos) |
(NRF_BALEN << RADIO_PCNF1_BALEN_Pos) |
RADIO_PCNF1_WHITEEN_Msk;
/* Enable radio fast ramp-up */
NRF_RADIO->MODECNF0 |= (RADIO_MODECNF0_RU_Fast << RADIO_MODECNF0_RU_Pos) &
RADIO_MODECNF0_RU_Msk;
/* Set logical address 1 for TX and RX */
NRF_RADIO->TXADDRESS = 0;
NRF_RADIO->RXADDRESSES = (1 << 0);
/* Configure the CRC registers */
NRF_RADIO->CRCCNF = (RADIO_CRCCNF_SKIPADDR_Skip << RADIO_CRCCNF_SKIPADDR_Pos) | RADIO_CRCCNF_LEN_Three;
/* Configure BLE poly */
NRF_RADIO->CRCPOLY = 0x0000065B;
/* Configure IFS */
NRF_RADIO->TIFS = BLE_LL_IFS;
/* Captures tx/rx start in timer0 cc 1 and tx/rx end in timer0 cc 2 */
NRF_PPI->CHENSET = PPI_CHEN_CH26_Msk | PPI_CHEN_CH27_Msk;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
NRF_CCM->INTENCLR = 0xffffffff;
NRF_CCM->SHORTS = CCM_SHORTS_ENDKSGEN_CRYPT_Msk;
NRF_CCM->EVENTS_ERROR = 0;
memset(g_nrf_encrypt_scratchpad, 0, sizeof(g_nrf_encrypt_scratchpad));
#endif
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
g_ble_phy_data.phy_aar_scratch = 0;
NRF_AAR->IRKPTR = (uint32_t)&g_nrf_irk_list[0];
NRF_AAR->INTENCLR = 0xffffffff;
NRF_AAR->EVENTS_END = 0;
NRF_AAR->EVENTS_RESOLVED = 0;
NRF_AAR->EVENTS_NOTRESOLVED = 0;
NRF_AAR->NIRK = 0;
#endif
/* TIMER0 setup for PHY when using RTC */
NRF_TIMER0->TASKS_STOP = 1;
NRF_TIMER0->TASKS_SHUTDOWN = 1;
NRF_TIMER0->BITMODE = 3; /* 32-bit timer */
NRF_TIMER0->MODE = 0; /* Timer mode */
NRF_TIMER0->PRESCALER = 4; /* gives us 1 MHz */
/*
* PPI setup.
* Channel 4: Captures TIMER0 in CC[3] when EVENTS_ADDRESS occurs. Used
* to cancel the wait for response timer.
* Channel 5: TIMER0 CC[3] to TASKS_DISABLE on radio. This is the wait
* for response timer.
*/
NRF_PPI->CH[4].EEP = (uint32_t)&(NRF_RADIO->EVENTS_ADDRESS);
NRF_PPI->CH[4].TEP = (uint32_t)&(NRF_TIMER0->TASKS_CAPTURE[3]);
NRF_PPI->CH[5].EEP = (uint32_t)&(NRF_TIMER0->EVENTS_COMPARE[3]);
NRF_PPI->CH[5].TEP = (uint32_t)&(NRF_RADIO->TASKS_DISABLE);
/* Set isr in vector table and enable interrupt */
#ifndef RIOT_VERSION
NVIC_SetPriority(RADIO_IRQn, 0);
#endif
#if MYNEWT
NVIC_SetVector(RADIO_IRQn, (uint32_t)ble_phy_isr);
#else
ble_npl_hw_set_isr(RADIO_IRQn, ble_phy_isr);
#endif
NVIC_EnableIRQ(RADIO_IRQn);
/* Register phy statistics */
if (!g_ble_phy_data.phy_stats_initialized) {
rc = stats_init_and_reg(STATS_HDR(ble_phy_stats),
STATS_SIZE_INIT_PARMS(ble_phy_stats,
STATS_SIZE_32),
STATS_NAME_INIT_PARMS(ble_phy_stats),
"ble_phy");
assert(rc == 0);
g_ble_phy_data.phy_stats_initialized = 1;
}
ble_phy_dbg_time_setup();
return 0;
}
/**
* Puts the phy into receive mode.
*
* @return int 0: success; BLE Phy error code otherwise
*/
int
ble_phy_rx(void)
{
/*
* Check radio state.
*
* In case radio is now disabling we'll wait for it to finish, but if for
* any reason it's just in idle state we proceed with RX as usual since
* nRF52 radio can ramp-up from idle state as well.
*
* Note that TX and RX states values are the same except for 3rd bit so we
* can make a shortcut here when checking for idle state.
*/
nrf_wait_disabled();
if ((NRF_RADIO->STATE != RADIO_STATE_STATE_Disabled) &&
((NRF_RADIO->STATE & 0x07) != RADIO_STATE_STATE_RxIdle)) {
ble_phy_disable();
STATS_INC(ble_phy_stats, radio_state_errs);
return BLE_PHY_ERR_RADIO_STATE;
}
/* Make sure all interrupts are disabled */
NRF_RADIO->INTENCLR = NRF_RADIO_IRQ_MASK_ALL;
/* Clear events prior to enabling receive */
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->EVENTS_DISABLED = 0;
/* Setup for rx */
ble_phy_rx_xcvr_setup();
/* PPI to start radio automatically shall be set here */
assert(NRF_PPI->CHEN & PPI_CHEN_CH21_Msk);
return 0;
}
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
/**
* Called to enable encryption at the PHY. Note that this state will persist
* in the PHY; in other words, if you call this function you have to call
* disable so that future PHY transmits/receives will not be encrypted.
*
* @param pkt_counter
* @param iv
* @param key
* @param is_master
*/
void
ble_phy_encrypt_enable(uint64_t pkt_counter, uint8_t *iv, uint8_t *key,
uint8_t is_master)
{
memcpy(g_nrf_ccm_data.key, key, 16);
g_nrf_ccm_data.pkt_counter = pkt_counter;
memcpy(g_nrf_ccm_data.iv, iv, 8);
g_nrf_ccm_data.dir_bit = is_master;
g_ble_phy_data.phy_encrypted = 1;
/* Enable the module (AAR cannot be on while CCM on) */
NRF_AAR->ENABLE = AAR_ENABLE_ENABLE_Disabled;
NRF_CCM->ENABLE = CCM_ENABLE_ENABLE_Enabled;
}
void
ble_phy_encrypt_set_pkt_cntr(uint64_t pkt_counter, int dir)
{
g_nrf_ccm_data.pkt_counter = pkt_counter;
g_nrf_ccm_data.dir_bit = dir;
}
void
ble_phy_encrypt_disable(void)
{
NRF_PPI->CHENCLR = PPI_CHEN_CH25_Msk;
NRF_CCM->TASKS_STOP = 1;
NRF_CCM->EVENTS_ERROR = 0;
NRF_CCM->ENABLE = CCM_ENABLE_ENABLE_Disabled;
g_ble_phy_data.phy_encrypted = 0;
}
#endif
void
ble_phy_set_txend_cb(ble_phy_tx_end_func txend_cb, void *arg)
{
/* Set transmit end callback and arg */
g_ble_phy_data.txend_cb = txend_cb;
g_ble_phy_data.txend_arg = arg;
}
/**
* Called to set the start time of a transmission.
*
* This function is called to set the start time when we are not going from
* rx to tx automatically.
*
* NOTE: care must be taken when calling this function. The channel should
* already be set.
*
* @param cputime This is the tick at which the 1st bit of the preamble
* should be transmitted
* @param rem_usecs This is used only when the underlying timing uses a 32.768
* kHz crystal. It is the # of usecs from the cputime tick
* at which the first bit of the preamble should be
* transmitted.
* @return int
*/
int
ble_phy_tx_set_start_time(uint32_t cputime, uint8_t rem_usecs)
{
int rc;
ble_phy_trace_u32x2(BLE_PHY_TRACE_ID_START_TX, cputime, rem_usecs);
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
ble_phy_mode_apply(g_ble_phy_data.phy_tx_phy_mode);
#endif
/* XXX: This should not be necessary, but paranoia is good! */
/* Clear timer0 compare to RXEN since we are transmitting */
NRF_PPI->CHENCLR = PPI_CHEN_CH21_Msk;
if (ble_phy_set_start_time(cputime, rem_usecs, true) != 0) {
STATS_INC(ble_phy_stats, tx_late);
ble_phy_disable();
rc = BLE_PHY_ERR_TX_LATE;
} else {
/* Enable PPI to automatically start TXEN */
NRF_PPI->CHENSET = PPI_CHEN_CH20_Msk;
rc = 0;
}
return rc;
}
/**
* Called to set the start time of a reception
*
* This function acts a bit differently than transmit. If we are late getting
* here we will still attempt to receive.
*
* NOTE: care must be taken when calling this function. The channel should
* already be set.
*
* @param cputime
*
* @return int
*/
int
ble_phy_rx_set_start_time(uint32_t cputime, uint8_t rem_usecs)
{
bool late = false;
int rc = 0;
ble_phy_trace_u32x2(BLE_PHY_TRACE_ID_START_RX, cputime, rem_usecs);
#if (BLE_LL_BT5_PHY_SUPPORTED == 1)
ble_phy_mode_apply(g_ble_phy_data.phy_rx_phy_mode);
#endif
/* XXX: This should not be necessary, but paranoia is good! */
/* Clear timer0 compare to TXEN since we are transmitting */
NRF_PPI->CHENCLR = PPI_CHEN_CH20_Msk;
if (ble_phy_set_start_time(cputime, rem_usecs, false) != 0) {
STATS_INC(ble_phy_stats, rx_late);
/* We're late so let's just try to start RX as soon as possible */
ble_phy_set_start_now();
late = true;
}
/* Enable PPI to automatically start RXEN */
NRF_PPI->CHENSET = PPI_CHEN_CH21_Msk;
/* Start rx */
rc = ble_phy_rx();
/*
* If we enabled receiver but were late, let's return proper error code so
* caller can handle this.
*/
if (!rc && late) {
rc = BLE_PHY_ERR_RX_LATE;
}
return rc;
}
int
ble_phy_tx(ble_phy_tx_pducb_t pducb, void *pducb_arg, uint8_t end_trans)
{
int rc;
uint8_t *dptr;
uint8_t *pktptr;
uint8_t payload_len;
uint8_t hdr_byte;
uint32_t state;
uint32_t shortcuts;
if (g_ble_phy_data.phy_transition_late) {
ble_phy_disable();
STATS_INC(ble_phy_stats, tx_late);
return BLE_PHY_ERR_TX_LATE;
}
/*
* This check is to make sure that the radio is not in a state where
* it is moving to disabled state. If so, let it get there.
*/
nrf_wait_disabled();
/*
* XXX: Although we may not have to do this here, I clear all the PPI
* that should not be used when transmitting. Some of them are only enabled
* if encryption and/or privacy is on, but I dont care. Better to be
* paranoid, and if you are going to clear one, might as well clear them
* all.
*/
NRF_PPI->CHENCLR = PPI_CHEN_CH4_Msk | PPI_CHEN_CH5_Msk | PPI_CHEN_CH23_Msk |
PPI_CHEN_CH25_Msk;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
if (g_ble_phy_data.phy_encrypted) {
dptr = (uint8_t *)&g_ble_phy_enc_buf[0];
pktptr = (uint8_t *)&g_ble_phy_tx_buf[0];
NRF_CCM->SHORTS = CCM_SHORTS_ENDKSGEN_CRYPT_Msk;
NRF_CCM->INPTR = (uint32_t)dptr;
NRF_CCM->OUTPTR = (uint32_t)pktptr;
NRF_CCM->SCRATCHPTR = (uint32_t)&g_nrf_encrypt_scratchpad[0];
NRF_CCM->EVENTS_ERROR = 0;
NRF_CCM->MODE = CCM_MODE_LENGTH_Msk | ble_phy_get_ccm_datarate();
NRF_CCM->CNFPTR = (uint32_t)&g_nrf_ccm_data;
} else {
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
NRF_AAR->IRKPTR = (uint32_t)&g_nrf_irk_list[0];
#endif
dptr = (uint8_t *)&g_ble_phy_tx_buf[0];
pktptr = dptr;
}
#else
dptr = (uint8_t *)&g_ble_phy_tx_buf[0];
pktptr = dptr;
#endif
/* Set PDU payload */
payload_len = pducb(&dptr[3], pducb_arg, &hdr_byte);
/* RAM representation has S0, LENGTH and S1 fields. (3 bytes) */
dptr[0] = hdr_byte;
dptr[1] = payload_len;
dptr[2] = 0;
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LE_ENCRYPTION)
/* Start key-stream generation and encryption (via short) */
if (g_ble_phy_data.phy_encrypted) {
NRF_CCM->TASKS_KSGEN = 1;
}
#endif
NRF_RADIO->PACKETPTR = (uint32_t)pktptr;
/* Clear the ready, end and disabled events */
NRF_RADIO->EVENTS_READY = 0;
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->EVENTS_DISABLED = 0;
/* Enable shortcuts for transmit start/end. */
shortcuts = RADIO_SHORTS_END_DISABLE_Msk | RADIO_SHORTS_READY_START_Msk;
NRF_RADIO->SHORTS = shortcuts;
NRF_RADIO->INTENSET = RADIO_INTENSET_DISABLED_Msk;
/* Set the PHY transition */
g_ble_phy_data.phy_transition = end_trans;
/* Set transmitted payload length */
g_ble_phy_data.phy_tx_pyld_len = payload_len;
/* If we already started transmitting, abort it! */
state = NRF_RADIO->STATE;
if (state != RADIO_STATE_STATE_Tx) {
/* Set phy state to transmitting and count packet statistics */
g_ble_phy_data.phy_state = BLE_PHY_STATE_TX;
STATS_INC(ble_phy_stats, tx_good);
STATS_INCN(ble_phy_stats, tx_bytes, payload_len + BLE_LL_PDU_HDR_LEN);
rc = BLE_ERR_SUCCESS;
} else {
ble_phy_disable();
STATS_INC(ble_phy_stats, tx_late);
rc = BLE_PHY_ERR_RADIO_STATE;
}
return rc;
}
/**
* ble phy txpwr set
*
* Set the transmit output power (in dBm).
*
* NOTE: If the output power specified is within the BLE limits but outside
* the chip limits, we "rail" the power level so we dont exceed the min/max
* chip values.
*
* @param dbm Power output in dBm.
*
* @return int 0: success; anything else is an error
*/
int
ble_phy_txpwr_set(int dbm)
{
/* "Rail" power level if outside supported range */
dbm = ble_phy_txpower_round(dbm);
NRF_RADIO->TXPOWER = dbm;
g_ble_phy_data.phy_txpwr_dbm = dbm;
return 0;
}
/**
* ble phy txpwr round
*
* Get the rounded transmit output power (in dBm).
*
* @param dbm Power output in dBm.
*
* @return int Rounded power in dBm
*/
int ble_phy_txpower_round(int dbm)
{
/* TODO this should be per nRF52XXX */
/* "Rail" power level if outside supported range */
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_Pos4dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_Pos4dBm;
}
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_Pos3dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_Pos3dBm;
}
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_0dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_0dBm;
}
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_Neg4dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_Neg4dBm;
}
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_Neg8dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_Neg8dBm;
}
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_Neg12dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_Neg12dBm;
}
if (dbm >= (int8_t)RADIO_TXPOWER_TXPOWER_Neg20dBm) {
return (int8_t)RADIO_TXPOWER_TXPOWER_Neg20dBm;
}
return (int8_t)RADIO_TXPOWER_TXPOWER_Neg40dBm;
}
/**
* ble phy set access addr
*
* Set access address.
*
* @param access_addr Access address
*
* @return int 0: success; PHY error code otherwise
*/
static int
ble_phy_set_access_addr(uint32_t access_addr)
{
NRF_RADIO->BASE0 = (access_addr << 8);
NRF_RADIO->PREFIX0 = (NRF_RADIO->PREFIX0 & 0xFFFFFF00) | (access_addr >> 24);
g_ble_phy_data.phy_access_address = access_addr;
ble_phy_apply_errata_102_106_107();
return 0;
}
/**
* ble phy txpwr get
*
* Get the transmit power.
*
* @return int The current PHY transmit power, in dBm
*/
int
ble_phy_txpwr_get(void)
{
return g_ble_phy_data.phy_txpwr_dbm;
}
void
ble_phy_set_rx_pwr_compensation(int8_t compensation)
{
g_ble_phy_data.rx_pwr_compensation = compensation;
}
/**
* ble phy setchan
*
* Sets the logical frequency of the transceiver. The input parameter is the
* BLE channel index (0 to 39, inclusive). The NRF frequency register works like
* this: logical frequency = 2400 + FREQ (MHz).
*
* Thus, to get a logical frequency of 2402 MHz, you would program the
* FREQUENCY register to 2.
*
* @param chan This is the Data Channel Index or Advertising Channel index
*
* @return int 0: success; PHY error code otherwise
*/
int
ble_phy_setchan(uint8_t chan, uint32_t access_addr, uint32_t crcinit)
{
assert(chan < BLE_PHY_NUM_CHANS);
/* Check for valid channel range */
if (chan >= BLE_PHY_NUM_CHANS) {
return BLE_PHY_ERR_INV_PARAM;
}
/* Set current access address */
ble_phy_set_access_addr(access_addr);
/* Configure crcinit */
NRF_RADIO->CRCINIT = crcinit;
/* Set the frequency and the data whitening initial value */
g_ble_phy_data.phy_chan = chan;
NRF_RADIO->FREQUENCY = g_ble_phy_chan_freq[chan];
NRF_RADIO->DATAWHITEIV = chan;
return 0;
}
/**
* Stop the timer used to count microseconds when using RTC for cputime
*/
static void
ble_phy_stop_usec_timer(void)
{
NRF_TIMER0->TASKS_STOP = 1;
NRF_TIMER0->TASKS_SHUTDOWN = 1;
NRF_RTC0->EVTENCLR = RTC_EVTENSET_COMPARE0_Msk;
}
/**
* ble phy disable irq and ppi
*
* This routine is to be called when reception was stopped due to either a
* wait for response timeout or a packet being received and the phy is to be
* restarted in receive mode. Generally, the disable routine is called to stop
* the phy.
*/
static void
ble_phy_disable_irq_and_ppi(void)
{
NRF_RADIO->INTENCLR = NRF_RADIO_IRQ_MASK_ALL;
NRF_RADIO->SHORTS = 0;
NRF_RADIO->TASKS_DISABLE = 1;
NRF_PPI->CHENCLR = PPI_CHEN_CH4_Msk | PPI_CHEN_CH5_Msk | PPI_CHEN_CH20_Msk |
PPI_CHEN_CH21_Msk | PPI_CHEN_CH23_Msk |
PPI_CHEN_CH25_Msk | PPI_CHEN_CH31_Msk;
NVIC_ClearPendingIRQ(RADIO_IRQn);
g_ble_phy_data.phy_state = BLE_PHY_STATE_IDLE;
}
void
ble_phy_restart_rx(void)
{
ble_phy_stop_usec_timer();
ble_phy_disable_irq_and_ppi();
ble_phy_set_start_now();
/* Enable PPI to automatically start RXEN */
NRF_PPI->CHENSET = PPI_CHEN_CH21_Msk;
ble_phy_rx();
}
/**
* ble phy disable
*
* Disables the PHY. This should be called when an event is over. It stops
* the usec timer (if used), disables interrupts, disables the RADIO, disables
* PPI and sets state to idle.
*/
void
ble_phy_disable(void)
{
ble_phy_trace_void(BLE_PHY_TRACE_ID_DISABLE);
ble_phy_stop_usec_timer();
ble_phy_disable_irq_and_ppi();
}
/* Gets the current access address */
uint32_t ble_phy_access_addr_get(void)
{
return g_ble_phy_data.phy_access_address;
}
/**
* Return the phy state
*
* @return int The current PHY state.
*/
int
ble_phy_state_get(void)
{
return g_ble_phy_data.phy_state;
}
/**
* Called to see if a reception has started
*
* @return int
*/
int
ble_phy_rx_started(void)
{
return g_ble_phy_data.phy_rx_started;
}
/**
* Return the transceiver state
*
* @return int transceiver state.
*/
uint8_t
ble_phy_xcvr_state_get(void)
{
uint32_t state;
state = NRF_RADIO->STATE;
return (uint8_t)state;
}
/**
* Called to return the maximum data pdu payload length supported by the
* phy. For this chip, if encryption is enabled, the maximum payload is 27
* bytes.
*
* @return uint8_t Maximum data channel PDU payload size supported
*/
uint8_t
ble_phy_max_data_pdu_pyld(void)
{
return BLE_LL_DATA_PDU_MAX_PYLD;
}
#if MYNEWT_VAL(BLE_LL_CFG_FEAT_LL_PRIVACY)
void
ble_phy_resolv_list_enable(void)
{
NRF_AAR->NIRK = (uint32_t)g_nrf_num_irks;
g_ble_phy_data.phy_privacy = 1;
}
void
ble_phy_resolv_list_disable(void)
{
g_ble_phy_data.phy_privacy = 0;
}
#endif
#if MYNEWT_VAL(BLE_LL_DTM)
void ble_phy_enable_dtm(void)
{
/* When DTM is enabled we need to disable whitening as per
* Bluetooth v5.0 Vol 6. Part F. 4.1.1
*/
NRF_RADIO->PCNF1 &= ~RADIO_PCNF1_WHITEEN_Msk;
}
void ble_phy_disable_dtm(void)
{
/* Enable whitening */
NRF_RADIO->PCNF1 |= RADIO_PCNF1_WHITEEN_Msk;
}
#endif
void
ble_phy_rfclk_enable(void)
{
#if MYNEWT
nrf52_clock_hfxo_request();
#else
NRF_CLOCK->TASKS_HFCLKSTART = 1;
#endif
}
void
ble_phy_rfclk_disable(void)
{
#if MYNEWT
nrf52_clock_hfxo_release();
#else
NRF_CLOCK->TASKS_HFCLKSTOP = 1;
#endif
}
#endif
|
the_stack_data/13200.c | #include <stdio.h>
#include <string.h>
char aLine[256];
int lineNumber = 0;
int lineLength;
int maxLineLength = 0;
int loopCounter;
int main() {
// read lines from stdin
while ( fgets(aLine, 256, stdin) ) {
// repeat as long as fgets() returns a non-NULL (i.e., non-zero) result
// obtain the length of the string received
lineLength = strlen(aLine);
// update the max-length if new one is longer
if (lineLength > maxLineLength) {
maxLineLength = lineLength;
}
// replace the newline character, that fgets() obtains,
// with a null byte
if (lineLength > 0) {
aLine[lineLength-1] = '\0';
}
// format the string as a code statement
// and send it out through stdout
printf("const char ct%.4d[] PROGMEM = \"%s\";\n", lineNumber, aLine);
// increment the line number
lineNumber++;
}
// output some housekeeping statistics
printf("\nMaximum line length: %d\n", maxLineLength);
printf("Number of lines: %d\n", lineNumber);
// prepare and output the array declaration
printf("\nconst char * string_table[] PROGMEM = { ");
for (loopCounter = 0; loopCounter < lineNumber; loopCounter++) {
printf("ct%.4d, ", loopCounter);
// insert a newline at 10-item intervals
if (loopCounter % 9 == 0) { printf("\n"); }
}
printf("}\n");
return 0;
}
|
the_stack_data/1023911.c | /**
*
* Exercise 5-4: Write the function strend(s, t), which returns 1 if the string
* t occurs at the end of the string s, and zero otherwise.
*
* */
#include <stdio.h>
#include <string.h>
int strend(char *s, char *t)
{
// locations for first elements of strings
char *s_first = s;
char *t_first = t;
// go to end of strings
while (*s)
s++;
while (*t)
t++;
// compare each character working backwards
while ((*s-- == *t--) && s != s_first && t != t_first)
;
if (t == t_first)
return 1;
else
return 0;
}
int main()
{
char *str1 = "goodbye";
char *str2 = "bye";
char *str3 = "hello";
char *str4 = "bye";
printf("%d\n", strend(str1, str2)); // returns 1
printf("%d\n", strend(str3, str4)); // returns 0
return 0;
} |
the_stack_data/68886800.c | /* { dg-do compile } */
/* { dg-options "-Os -m8bit-idiv" } */
extern void abort (void);
void
test (int x, int y, int q, int r)
{
if ((x / y) != q || (x % y) != r)
abort ();
}
/* { dg-final { scan-assembler-not "divb" } } */
/* { dg-final { scan-assembler-times "idivl" 1 } } */
|
the_stack_data/12188.c | /* Missing warning for falling off the end of a non-void function.
egcs-1.1.2 passes, egcs-ss-19990428 fails.
http://gcc.gnu.org/ml/gcc-bugs/1999-03n/msg00221.html */
/* { dg-do compile } */
/* { dg-options "-O -Wreturn-type" } */
int
foo(void)
{
} /* { dg-warning "control reaches end of non-void function" "warning for falling off end of non-void function" } */
|
the_stack_data/87639123.c | #include <stdio.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>
#include <time.h>
//Create space to hold the file path
#define BUFFER_SIZE (256)
//char newPath[1024];
void listFiles(char *path) {
//Initialise variable for dir
DIR *dir;
//Initialise buffer for snprintf
char buffer[BUFFER_SIZE];
//Create new dirent structure
struct dirent *entry;
//If path exists
if ((dir = opendir(path)) != NULL) {
//While files exists in path
while ((entry = readdir(dir)) != NULL) {
//Skip '.' and '..' entries to avoid recursion issues
if((strcmp(entry->d_name,"..") != 0) && (strcmp(entry->d_name,".") != 0)) {
////Creating variables to store attributes
//Create stat structure 'sb'
struct stat sb;
//Direct output of printf (file path) to buffer
snprintf(buffer, BUFFER_SIZE, "%s/%s", path, entry->d_name);
//System call to return attributes of an inode (returns 0 or -1 if error, errno is set)
stat(buffer, &sb);
//Type mode_t stores st_mode, mode of the file
mode_t mode;
//Type uid_t stores st_uid, ID of owner
uid_t owner;
//Type gid_t stores st_gid, group ID of owner
gid_t group;
//Type off_t stores st_size, filesize of the file in bytes
off_t size;
//Type time_t stores st_mtime, time of last modification
time_t time;
////Storing attributes to created variables
//Mode stored
mode = sb.st_mode;
//Owner stored
owner = sb.st_uid;
//Group stored
group = sb.st_gid;
//File size stored
size = sb.st_size;
//Time of last modification stored
time = sb.st_mtime;
////Print attributes
//Print file mode (permissions). Code snippet here that parses the stat macro outputs from https://bit.ly/2StYoxZ
printf( (S_ISDIR(mode)) ? "d" : "-");
printf( (mode & S_IRUSR) ? "r" : "-");
printf( (mode & S_IWUSR) ? "w" : "-");
printf( (mode & S_IXUSR) ? "x" : "-");
printf( (mode & S_IRGRP) ? "r" : "-");
printf( (mode & S_IWGRP) ? "w" : "-");
printf( (mode & S_IXGRP) ? "x" : "-");
printf( (mode & S_IROTH) ? "r" : "-");
printf( (mode & S_IWOTH) ? "w" : "-");
printf( (mode & S_IXOTH) ? "x" : "-");
printf(" ");
//Create new struct for user info
struct passwd *pwd;
//Return user account info for id
pwd = getpwuid(owner);
//Print username formatted as string
printf("%s ", pwd->pw_name);
//Create new struct for group info
struct group *grp;
//Return group info for id
grp = getgrgid(group);
//Print group name formatted as string
printf("%s ", grp->gr_name);
//Print file size
printf("%d ", size);
//Create new time struct
struct tm lt;
//Convert st_mtime to localtime
localtime_r(&time, <);
//Initialise variable to store formatted time
char formatted_time[30];
//Format the date and time
strftime(formatted_time, sizeof formatted_time, "%b %d %H:%M", <);
//Print date and time
printf("%s ", formatted_time);
//Print file name
printf("%s\n", entry->d_name);
//S_ISREG() macro from sys/stat.h returns 0 if dir, 1 if regular file
if (S_ISREG(sb.st_mode) == 0) {
//New variable to store 'new path' to call listFiles recursively
char newPath[1024];
//Direct printf output to generate correct 'new path', using previous path and current entry name
snprintf(newPath, sizeof(newPath), "%s/%s", path, entry->d_name);
//Recursively call function
listFiles(newPath);
}
}
}
}
//Close open directory
closedir (dir);
}
int main() {
listFiles("/nfs/pihome/eddiewastaken/test");
return 0;
}
|
the_stack_data/159514665.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, L. Sekanina, Z. Vasicek "Libraries of Approximate Circuits: Automated Design and Application in CNN Accelerators" IEEE Journal on Emerging and Selected Topics in Circuits and Systems, Vol 10, No 4, 2020
* This file contains a circuit from a sub-set of pareto optimal circuits with respect to the pwr and mse parameters
***/
// MAE% = 14.37 %
// MAE = 74
// WCE% = 49.61 %
// WCE = 254
// WCRE% = 7000.00 %
// EP% = 99.53 %
// MRE% = 69.54 %
// MSE = 8574
// PDK45_PWR = 0.0046 mW
// PDK45_AREA = 14.1 um2
// PDK45_DELAY = 0.13 ns
#include <stdint.h>
#include <stdlib.h>
uint64_t add9se_0DV(const uint64_t B,const uint64_t A)
{
uint64_t dout_33, dout_34, dout_36, dout_43, dout_46, dout_48, dout_69, dout_75, dout_76;
uint64_t O;
dout_33=((A >> 7)&1)|((B >> 7)&1);
dout_34=((A >> 8)&1)&((B >> 8)&1);
dout_36=((A >> 8)&1)^((B >> 8)&1);
dout_43=((B >> 8)&1)^((A >> 8)&1);
dout_46=dout_43&((A >> 7)&1);
dout_48=dout_34|dout_46;
dout_69=dout_33^((A >> 7)&1);
dout_75=dout_36^((A >> 7)&1);
dout_76=dout_36^dout_48;
O = 0;
O |= (dout_69&1) << 0;
O |= (dout_76&1) << 1;
O |= (dout_69&1) << 2;
O |= (0&1) << 3;
O |= (dout_76&1) << 4;
O |= (dout_76&1) << 5;
O |= (dout_76&1) << 6;
O |= (dout_69&1) << 7;
O |= (dout_75&1) << 8;
O |= (dout_76&1) << 9;
return O;
}
|
the_stack_data/1246156.c | #include<stdio.h>
#define MAX_SIZE 10
int even_elements();
int second();
int palindrome();
void print_pa();
int sort();
void array();
int main()
{
int size_array , res, i, arr[MAX_SIZE];
printf("How many number you want to enter ?\n");
res=scanf("%d", &size_array);
if( size_array == 0 || size_array == 1 || size_array > 10 || res!=1 || size_array<0 )
{
printf("Not right size of array! ");
}
else
{
printf("Enter %d Numbers :", size_array);
for (i = 0; i < size_array; i++)
scanf("%d", &arr[i]);
printf("\nSum of even elements: %d",even_elements(size_array, i, arr));
printf("\n\nNew array is: %d ",second(size_array, i, arr));
int ret = palindrome(size_array, i, arr);
for (i = 0; i < size_array; i++)
{
if(ret == 0)
printf("\n%d is a palindrome number.\n", arr[i]);
else
printf("\n%d is not a palindrome number.\n", arr[i]);
}
sort(size_array, i, arr);
}
return 0;
}
int even_elements(int size_array, int i, int arr[MAX_SIZE])
{
int e=0;
if(size_array<11)
{
for(i=0; i<size_array; i++)
{
if(arr[i]%2==0)
e = e +arr[i];
}
}
return e;
}
int second(int size_array, int i, int arr[MAX_SIZE])
{
int sum = 0, size=0, b[11];
for (i = 0; i < size_array; i++)
sum = sum + arr[i];
int average = sum / size_array;
for (i = 0; i < size_array; i++)
{
if (arr[i] > average)
{
b[size] = arr[i];
size++;
}
}
return b[0];
}
int palindrome(int size_array, int i, int arr[MAX_SIZE])
{
int temp, ret = 0;
for (i = 0; i < size_array; i++)
{
int reverse = 0;
temp = arr[i];
while( temp != 0 )
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
if ( arr[i] == reverse )
ret = 0;//printf("\n%d is a palindrome number.\n", arr[i]);
else
ret = 1;//printf("\n%d is not a palindrome number.\n", arr[i]);
}
return ret;
}
int sort(int size_array, int i, int arr[MAX_SIZE])
{
int j, temp = 0;
for (i = 0; i < size_array; i++)
{
for (j = i + 1; j < size_array; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\nThe sorted array using Buble sort is:\n");
array(size_array, i, arr);
return 0;
}
void array(int size_array, int i, int arr[MAX_SIZE])
{
for (i = 0; i < size_array; i++)
{
printf("%d ", arr[i]);
}
} |
the_stack_data/797298.c | #include/**/<time.h>
#include <ncurses.h>
# include <stdlib.h>
/** */#define O()for(y-= !!\
y;y<H&& /*semi-automatic----*/y< p/W+2;\
y++)for(x=p% W,x-=!!/*-----minesweeper*/x;x<W&& x<p%W+2;x++)
#define _(x)COLOR_##x/*IOCCC2019IOCCC2019IOCCC2019IOCCC2019IOCCC20*/
#define Y(n)attrset(COLOR_PAIR(n)),mvprintw/*IOCCC2019IOCCC2019IOCCC20*/
int*M,W,H,S,C,E,X,T,c,p,q,i,j,k;char G[]=" x",U[256];int F(int p){int r=0,x,
y=p/W,q;O()q=y*W+x,r+=M[q]^=p-q?(M[q]&16)<<8:0;return r;}int K( int p,
int f,int g){int x=(g+f/256)%16-(f+g/256)%16,y=p/W,c=0,n=
g/4096,m=x==n ?0:x==g/16%16-f/16%16-n?256:-1;if(m+
1)O()if((M[n= y*W+x]&4368)==4112)M[n]=(M[n]&~16)|m
,c++;return c; }void D(){int p,k,o=0,n=C;if(LINES-1<
H||COLS/2<W)/*| */clear(),Y(4)(LINES/2,COLS/2-16,"Mak\
e the terminal window " "bigger!");else{for(p=0;p<S;o+=k==3,Y(k)(p/W+1
,p%W*2,G),p++)G[1]="_*!.." "12345678"[k=E?M[p]&256?n--,2:E-2||M[p]%2<1?M[p]&
16?3:4+F(p)%16:1:3];k=T+time(0);T=o||T>=0||E-1?T:k;k=T<0?k:T;Y(7)(0,0,"%03d%*s%03\
d",n>999?999:n,W*2-6,"",k>999?999:k);Y(9)(0,W-1,E>1?"X-(":E-1||o?":-)":"[-)");}re\
fresh();}int main(int A,char**V){short B[]={_(RED),_(BLACK),_(WHITE),_(BLUE),_(GR\
EEN),_(RED),_(MAGENTA),_(YELLOW),_(CYAN)};MEVENT e;FILE*f;srand(time(0));initscr()
;for(start_color();X<12;X++)init_pair(X+1,B[X&&X<10?X-1:2],B[X?X<3?2:1:0]);noecho(
);cbreak();timeout(9);curs_set(0);keypad(stdscr,TRUE);for(mousemask(BUTTON1_CLICK\
ED|BUTTON1_RELEASED,0);;){if(A-->1){f=fopen(V[A],"r");fscanf(f,"%d %d %d",&W,&H,&C
);}else{f=0;W=COLS/2;H=LINES-1;C=W*H/5;}S=W*H;M=realloc(M,S*2*sizeof
(int));for(i=0;i<S;i++)!f?M[i]=i:fscanf(f,"%d",M+i);for(i=0;!f&&i<
S;i++)k=M[j=i+rand()%(S-i)],M[j]=M[i],M[i]=k;if(f)fclose(f);T=E=
X=0;for(clear();D(),c=getch(),c-'r'&&(c-KEY_RESIZE||E);){if (c
=='q')return(endwin(),0);if(c==KEY_MOUSE&&getmouse(&e)==OK&&e.x/
2<W&&e.y<=H){if(!e.y&&(W-2<e.x&&e.x<W+2))break;p=e.x/2+e.y*W-W;if(p>=0
){if(!E){for(i=0;i<S;i++)M[S+M[i]]=i,M[i]=16+(M[i]<C);C-=M[p]&1;M[p]=16;E=1;
T=-time(0);}if(E<2)M[p]&=(M[p]&257)==1?T+=time(0),E=2,273:257;}}for(p=0;
p<S&&E==1;)M[p++]&=273;for(i=(X+S-1)%S;E==1&&i!=X;X=(X+1)%S){if(!(M[
p=M[X+S]]&272 )){if(K(p,c=F(p),0))goto N;for(k =p/W-2,k=k<0?
0:k;k<H &&k<p/W+3;k++)for(j=p%W-2 ,j=j<0?
0:j ;j<W&&j<p%W+3;j++)if (!(
M[q=j+k*W]&272)){if(
K(p,c,F(q)))goto N;F
(q);}F(p);}}N:;}}}
|
the_stack_data/36815.c | /*
* sh2d
* Bart Trzynadlowski, July 24, 2000
* Public domain
*
* Some changes by Björn Stenberg <[email protected]>
* $Id$
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define VERSION "0.2"
#define ZERO_F 0 /* 0 format */
#define N_F 1 /* n format */
#define M_F 2 /* m format */
#define NM_F 3 /* nm format */
#define MD_F 4 /* md format */
#define ND4_F 5 /* nd4 format */
#define NMD_F 6 /* nmd format */
#define D_F 7 /* d format */
#define D12_F 8 /* d12 format */
#define ND8_F 9 /* nd8 format */
#define I_F 10 /* i format */
#define NI_F 11 /* ni format */
typedef struct
{
int format;
const char *mnem;
unsigned short mask; /* mask used to obtain opcode bits */
unsigned short bits; /* opcode bits */
int dat; /* specific data for situation */
int sh2; /* SH-2 specific */
} i_descr;
/* register name lookup added by [email protected] 2001-12-09 */
char* regname[] =
{
/* 0 1 2 3 4 5 6 7 8 9 a b c d e f */
"","","","","","","","","","","","","","","","", /* 0 */
"","","","","","","","","","","","","","","","", /* 10 */
"","","","","","","","","","","","","","","","", /* 20 */
"","","","","","","","","","","","","","","","", /* 30 */
"","","","","","","","","","","","","","","","", /* 40 */
"","","","","","","","","","","","","","","","", /* 50 */
"","","","","","","","","","","","","","","","", /* 60 */
"","","","","","","","","","","","","","","","", /* 70 */
"","","","","","","","","","","","","","","","", /* 80 */
"","","","","","","","","","","","","","","","", /* 90 */
"","","","","","","","","","","","","","","","", /* a0 */
"","","","","","","","","","","","","","","","", /* b0 */
"SMR0","BRR0","SCR0","TDR0","SSR0","RDR0","","", /* c0 */
"SMR1","BRR1","SCR1","TDR1","SSR1","RDR1","","", /* c8 */
"","","","","","","","","","","","","","","","", /* d0 */
"ADDRAH","ADDRAL","ADDRBH","ADDRBL", /* e0 */
"ADDRCH","ADDRCL","ADDRDH","ADDRDL", /* e4 */
"ADCSR","ADCR","","","","","","", /* e8 */
"","","","","","","","","","","","","","","","", /* f0 */
"TSTR","TSNC","TMDR","TFCR","TCR0","TIOR0","TIER0","TSR0", /* 100 */
"TCNT0","!","GRA0","!","GRB0","!","TCR1","TIORL", /* 108 */
"TIERI","TSR1","TCNT1","!","GRA1","!","GRB1","!", /* 110 */
"TCR2","TIOR2","TIER2","TSR2","TCNT2","!","GRA2","!", /* 118 */
"GRB2","!","TCR3","TIOR3","TIER3","TSR3","TCNT3","!", /* 120 */
"GRA3","!","GRB3","!","BRA3","!","BRB3","!", /* 128 */
"","TOCR","TCR4","TIOR4","TIER4","TSR4","TCNT4","!", /* 130 */
"GRA4","!","GRB4","!","BRA4","!","BRB4","!", /* 138 */
"SAR0","!","!","!","DAR0","!","!","!", /* 140 */
"DMAOR","!","TCR0","!","","","CHCR0","!", /* 148 */
"SAR1","!","!","!","DAR1","!","!","!", /* 150 */
"","","TCR1","!","","","CHCR1","!", /* 158 */
"SAR2","!","!","!","DAR2","!","!","!", /* 160 */
"","","TCR2","!","","","CHCR2","!", /* 168 */
"SAR3","!","!","!","DAR3","!","!","!", /* 170 */
"","","TCR3","!","","","CHCR3","!", /* 178 */
"","","","","IPRA","!","IPRB","!", /* 180 */
"IPRC","!","IPRD","!","IPRE","!","ICR","!", /* 188 */
"BARH","!","BARL","!","BAMRH","!","BAMRL","!", /* 190 */
"BBR","!","","","","","","", /* 198 */
"BCR","!","WCR1","!","WCR2","!","WCR3","!", /* 1a0 */
"DCR","!","PCR","!","RCR","!","RTCSR","!", /* 1a8 */
"RTCNT","!","RTCOR","!","","","","", /* 1b0 */
"TCSR","TCNT","","RSTCSR","SBYCR","","","", /* 1b8 */
"PADR","!","PBDR","!","PAIOR","!","PBIOR","!", /* 1c0 */
"PACR1","!","PACR2","!","PBCR1","!","PBCR2","!", /* 1c8 */
"PCDR","!","","","","","","","","","","","","","","", /* 1d0 */
"","","","","","","","","","","","","","","CASCR","!", /* 1e0 */
"TPMR","TPCR","NDERB","NDERA","NDRB","NDRA","NDRB","NDRA", /* 1f0 */
"","","","","","","",""
};
i_descr tab[] =
{
{ ZERO_F, "clrt", 0xffff, 0x8, 0, 0 },
{ ZERO_F, "clrmac", 0xffff, 0x28, 0, 0 },
{ ZERO_F, "div0u", 0xffff, 0x19, 0, 0 },
{ ZERO_F, "nop", 0xffff, 0x9, 0, 0 },
{ ZERO_F, "rte", 0xffff, 0x2b, 0, 0 },
{ ZERO_F, "rts", 0xffff, 0xb, 0, 0 },
{ ZERO_F, "sett", 0xffff, 0x18, 0, 0 },
{ ZERO_F, "sleep", 0xffff, 0x1b, 0, 0 },
{ N_F, "cmp/pl\tr%d", 0xf0ff, 0x4015, 0, 0 },
{ N_F, "cmp/pz\tr%d", 0xf0ff, 0x4011, 0, 0 },
{ N_F, "dt\tr%d", 0xf0ff, 0x4010, 0, 1 },
{ N_F, "movt\tr%d", 0xf0ff, 0x0029, 0, 0 },
{ N_F, "rotl\tr%d", 0xf0ff, 0x4004, 0, 0 },
{ N_F, "rotr\tr%d", 0xf0ff, 0x4005, 0, 0 },
{ N_F, "rotcl\tr%d", 0xf0ff, 0x4024, 0, 0 },
{ N_F, "rotcr\tr%d", 0xf0ff, 0x4025, 0, 0 },
{ N_F, "shal\tr%d", 0xf0ff, 0x4020, 0, 0 },
{ N_F, "shar\tr%d", 0xf0ff, 0x4021, 0, 0 },
{ N_F, "shll\tr%d", 0xf0ff, 0x4000, 0, 0 },
{ N_F, "shlr\tr%d", 0xf0ff, 0x4001, 0, 0 },
{ N_F, "shll2\tr%d", 0xf0ff, 0x4008, 0, 0 },
{ N_F, "shlr2\tr%d", 0xf0ff, 0x4009, 0, 0 },
{ N_F, "shll8\tr%d", 0xf0ff, 0x4018, 0, 0 },
{ N_F, "shlr8\tr%d", 0xf0ff, 0x4019, 0, 0 },
{ N_F, "shll16\tr%d", 0xf0ff, 0x4028, 0, 0 },
{ N_F, "shlr16\tr%d", 0xf0ff, 0x4029, 0, 0 },
{ N_F, "stc\tsr,r%d", 0xf0ff, 0x0002, 0, 0 },
{ N_F, "stc\tgbr,r%d", 0xf0ff, 0x0012, 0, 0 },
{ N_F, "stc\tvbr,r%d", 0xf0ff, 0x0022, 0, 0 },
{ N_F, "sts\tmach,r%d", 0xf0ff, 0x000a, 0, 0 },
{ N_F, "sts\tmacl,r%d", 0xf0ff, 0x001a, 0, 0 },
{ N_F, "sts\tpr,r%d", 0xf0ff, 0x002a, 0, 0 },
{ N_F, "tas.b\t@r%d", 0xf0ff, 0x401b, 0, 0 },
{ N_F, "stc.l\tsr,@-r%d", 0xf0ff, 0x4003, 0, 0 },
{ N_F, "stc.l\tgbr,@-r%d", 0xf0ff, 0x4013, 0, 0 },
{ N_F, "stc.l\tvbr,@-r%d", 0xf0ff, 0x4023, 0, 0 },
{ N_F, "sts.l\tmach,@-r%d", 0xf0ff, 0x4002, 0, 0 },
{ N_F, "sts.l\tmacl,@-r%d", 0xf0ff, 0x4012, 0, 0 },
{ N_F, "sts.l\tpr,@-r%d", 0xf0ff, 0x4022, 0, 0 },
{ M_F, "ldc\tr%d,sr", 0xf0ff, 0x400e, 0, 0 },
{ M_F, "ldc\tr%d,gbr", 0xf0ff, 0x401e, 0, 0 },
{ M_F, "ldc\tr%d,vbr", 0xf0ff, 0x402e, 0, 0 },
{ M_F, "lds\tr%d,mach", 0xf0ff, 0x400a, 0, 0 },
{ M_F, "lds\tr%d,macl", 0xf0ff, 0x401a, 0, 0 },
{ M_F, "lds\tr%d,pr", 0xf0ff, 0x402a, 0, 0 },
{ M_F, "jmp\t@r%d", 0xf0ff, 0x402b, 0, 0 },
{ M_F, "jsr\t@r%d", 0xf0ff, 0x400b, 0, 0 },
{ M_F, "ldc.l\t@r%d+,sr", 0xf0ff, 0x4007, 0, 0 },
{ M_F, "ldc.l\t@r%d+,gbr", 0xf0ff, 0x4017, 0, 0 },
{ M_F, "ldc.l\t@r%d+,vbr", 0xf0ff, 0x4027, 0, 0 },
{ M_F, "lds.l\t@r%d+,mach", 0xf0ff, 0x4006, 0, 0 },
{ M_F, "lds.l\t@r%d+,macl", 0xf0ff, 0x4016, 0, 0 },
{ M_F, "lds.l\t@r%d+,pr", 0xf0ff, 0x4026, 0, 0 },
{ M_F, "braf\tr%d", 0xf0ff, 0x0023, 0, 1 },
{ M_F, "bsrf\tr%d", 0xf0ff, 0x0003, 0, 1 },
{ NM_F, "add\tr%d,r%d", 0xf00f, 0x300c, 0, 0 },
{ NM_F, "addc\tr%d,r%d", 0xf00f, 0x300e, 0, 0 },
{ NM_F, "addv\tr%d,r%d", 0xf00f, 0x300f, 0, 0 },
{ NM_F, "and\tr%d,r%d", 0xf00f, 0x2009, 0, 0 },
{ NM_F, "cmp/eq\tr%d,r%d", 0xf00f, 0x3000, 0, 0 },
{ NM_F, "cmp/hs\tr%d,r%d", 0xf00f, 0x3002, 0, 0 },
{ NM_F, "cmp/ge\tr%d,r%d", 0xf00f, 0x3003, 0, 0 },
{ NM_F, "cmp/hi\tr%d,r%d", 0xf00f, 0x3006, 0, 0 },
{ NM_F, "cmp/gt\tr%d,r%d", 0xf00f, 0x3007, 0, 0 },
{ NM_F, "cmp/str\tr%d,r%d", 0xf00f, 0x200c, 0, 0 },
{ NM_F, "div1\tr%d,r%d", 0xf00f, 0x3004, 0, 0 },
{ NM_F, "div0s\tr%d,r%d", 0xf00f, 0x2007, 0, 0 },
{ NM_F, "dmuls.l\tr%d,r%d", 0xf00f, 0x300d, 0, 1 },
{ NM_F, "dmulu.l\tr%d,r%d", 0xf00f, 0x3005, 0, 1 },
{ NM_F, "exts.b\tr%d,r%d", 0xf00f, 0x600e, 0, 0 },
{ NM_F, "exts.w\tr%d,r%d", 0xf00f, 0x600f, 0, 0 },
{ NM_F, "extu.b\tr%d,r%d", 0xf00f, 0x600c, 0, 0 },
{ NM_F, "extu.w\tr%d,r%d", 0xf00f, 0x600d, 0, 0 },
{ NM_F, "mov\tr%d,r%d", 0xf00f, 0x6003, 0, 0 },
{ NM_F, "mul.l\tr%d,r%d", 0xf00f, 0x0007, 0, 1 },
{ NM_F, "muls.w\tr%d,r%d", 0xf00f, 0x200f, 0, 0 },
{ NM_F, "mulu.w\tr%d,r%d", 0xf00f, 0x200e, 0, 0 },
{ NM_F, "neg\tr%d,r%d", 0xf00f, 0x600b, 0, 0 },
{ NM_F, "negc\tr%d,r%d", 0xf00f, 0x600a, 0, 0 },
{ NM_F, "not\tr%d,r%d", 0xf00f, 0x6007, 0, 0 },
{ NM_F, "or\tr%d,r%d", 0xf00f, 0x200b, 0, 0 },
{ NM_F, "sub\tr%d,r%d", 0xf00f, 0x3008, 0, 0 },
{ NM_F, "subc\tr%d,r%d", 0xf00f, 0x300a, 0, 0 },
{ NM_F, "subv\tr%d,r%d", 0xf00f, 0x300b, 0, 0 },
{ NM_F, "swap.b\tr%d,r%d", 0xf00f, 0x6008, 0, 0 },
{ NM_F, "swap.w\tr%d,r%d", 0xf00f, 0x6009, 0, 0 },
{ NM_F, "tst\tr%d,r%d", 0xf00f, 0x2008, 0, 0 },
{ NM_F, "xor\tr%d,r%d", 0xf00f, 0x200a, 0, 0 },
{ NM_F, "xtrct\tr%d,r%d", 0xf00f, 0x200d, 0, 0 },
{ NM_F, "mov.b\tr%d,@r%d", 0xf00f, 0x2000, 0, 0 },
{ NM_F, "mov.w\tr%d,@r%d", 0xf00f, 0x2001, 0, 0 },
{ NM_F, "mov.l\tr%d,@r%d", 0xf00f, 0x2002, 0, 0 },
{ NM_F, "mov.b\t@r%d,r%d", 0xf00f, 0x6000, 0, 0 },
{ NM_F, "mov.w\t@r%d,r%d", 0xf00f, 0x6001, 0, 0 },
{ NM_F, "mov.l\t@r%d,r%d", 0xf00f, 0x6002, 0, 0 },
{ NM_F, "mac.l\t@r%d+,@r%d+", 0xf00f, 0x000f, 0, 1 },
{ NM_F, "mac.w\t@r%d+,@r%d+", 0xf00f, 0x400f, 0, 0 },
{ NM_F, "mov.b\t@r%d+,r%d", 0xf00f, 0x6004, 0, 0 },
{ NM_F, "mov.w\t@r%d+,r%d", 0xf00f, 0x6005, 0, 0 },
{ NM_F, "mov.l\t@r%d+,r%d", 0xf00f, 0x6006, 0, 0 },
{ NM_F, "mov.b\tr%d,@-r%d", 0xf00f, 0x2004, 0, 0 },
{ NM_F, "mov.w\tr%d,@-r%d", 0xf00f, 0x2005, 0, 0 },
{ NM_F, "mov.l\tr%d,@-r%d", 0xf00f, 0x2006, 0, 0 },
{ NM_F, "mov.b\tr%d,@(r0,r%d)", 0xf00f, 0x0004, 0, 0 },
{ NM_F, "mov.w\tr%d,@(r0,r%d)", 0xf00f, 0x0005, 0, 0 },
{ NM_F, "mov.l\tr%d,@(r0,r%d)", 0xf00f, 0x0006, 0, 0 },
{ NM_F, "mov.b\t@(r0,r%d),r%d", 0xf00f, 0x000c, 0, 0 },
{ NM_F, "mov.w\t@(r0,r%d),r%d", 0xf00f, 0x000d, 0, 0 },
{ NM_F, "mov.l\t@(r0,r%d),r%d", 0xf00f, 0x000e, 0, 0 },
{ MD_F, "mov.b\t@(0x%03X,r%d), r0", 0xff00, 0x8400, 0, 0 },
{ MD_F, "mov.w\t@(0x%03X,r%d), r0", 0xff00, 0x8500, 0, 0 },
{ ND4_F, "mov.b\tr0,@(0x%03X,r%d)", 0xff00, 0x8000, 0, 0 },
{ ND4_F, "mov.w\tr0,@(0x%03X,r%d)", 0xff00, 0x8100, 0, 0 },
{ NMD_F, "mov.l\tr%d,@(0x%03X,r%d)", 0xf000, 0x1000, 0,0 },
{ NMD_F, "mov.l\t@(0x%03X,r%d),r%d", 0xf000, 0x5000, 0,0 },
{ D_F, "mov.b\tr0,@(0x%03X,gbr)", 0xff00, 0xc000, 1, 0 },
{ D_F, "mov.w\tr0,@(0x%03X,gbr)", 0xff00, 0xc100, 2, 0 },
{ D_F, "mov.l\tr0,@(0x%03X,gbr)", 0xff00, 0xc200, 4, 0 },
{ D_F, "mov.b\t@(0x%03X,gbr),r0", 0xff00, 0xc400, 1, 0 },
{ D_F, "mov.w\t@(0x%03X,gbr),r0", 0xff00, 0xc500, 2, 0 },
{ D_F, "mov.l\t@(0x%03X,gbr),r0", 0xff00, 0xc600, 4, 0 },
{ D_F, "mova\t@(0x%03X,pc),r0", 0xff00, 0xc700, 4, 0 },
{ D_F, "bf\t0x%08X", 0xff00, 0x8b00, 5, 0 },
{ D_F, "bf/s\t0x%08X", 0xff00, 0x8f00, 5, 1 },
{ D_F, "bt\t0x%08X", 0xff00, 0x8900, 5, 0 },
{ D_F, "bt/s\t0x%08X", 0xff00, 0x8d00, 5, 1 },
{ D12_F, "bra\t0x%08X", 0xf000, 0xa000, 0, 0 },
{ D12_F, "bsr\t0x%08X", 0xf000, 0xb000, 0, 0 },
{ ND8_F, "mov.w\t@(0x%03X,pc),r%d", 0xf000, 0x9000, 2, 0 },
{ ND8_F, "mov.l\t@(0x%03X,pc),r%d", 0xf000, 0xd000, 4, 0 },
{ I_F, "and.b\t#0x%02X,@(r0,gbr)", 0xff00, 0xcd00, 0,0 },
{ I_F, "or.b\t#0x%02X,@(r0,gbr)", 0xff00, 0xcf00, 0,0 },
{ I_F, "tst.b\t#0x%02X,@(r0,gbr)", 0xff00, 0xcc00, 0,0 },
{ I_F, "xor.b\t#0x%02X,@(r0,gbr)", 0xff00, 0xce00, 0,0 },
{ I_F, "and\t#0x%02X,r0", 0xff00, 0xc900, 0, 0 },
{ I_F, "cmp/eq\t#0x%02X,r0", 0xff00, 0x8800, 0, 0 },
{ I_F, "or\t#0x%02X,r0", 0xff00, 0xcb00, 0, 0 },
{ I_F, "tst\t#0x%02X,r0", 0xff00, 0xc800, 0, 0 },
{ I_F, "xor\t#0x%02X,r0", 0xff00, 0xca00, 0, 0 },
{ I_F, "trapa\t#0x%X", 0xff00, 0xc300, 0, 0 },
{ NI_F, "add\t#0x%02X,r%d", 0xf000, 0x7000, 0, 0 },
{ NI_F, "mov\t#0x%02X,r%d", 0xf000, 0xe000, 0, 0 },
{ 0, NULL, 0, 0, 0, 0 }
};
int FindOption(char *option, int p, int h, int u, int argc, char **argv)
{
static int t[] = { 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 };
int i;
char *c;
if (argc > 128)
argc = 128; /* maximum this function can handle is 128 */
/*
* if p = 1 and h = 0 will find option and return decimal value of
* argv[i+1], if h = 1 will read it as hex.
* if p = 0 then it will return index of option in argv[], 0 not found
* if u = 1 will return index of first occurance of untouched option
*/
if (u) /* find first untouched element */
{
for (i = 1; i < argc; i++)
{
if (!t[i]) /* 0 indicates untouched */
return i;
}
return 0;
}
if (p) /* find option and return integer value following it */
{
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], option) == 0) /* found */
{
if (i >= argc) /* bounds! */
return 0;
t[i + 1] = t[i] = 1; /* touched */
if (!h)
return atoi(argv[i + 1]);
else
return strtoul(argv[i + 1], &c, 16);
}
}
return 0; /* no match */
}
else /* find option and return position */
{
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], option) == 0)
{
t[i] = 1;
return i; /* found! return position */
}
}
return 0;
}
}
/*
* SH2Disasm(): SH-1/SH-2 disassembler routine. If mode = 0 then SH-2 mode,
* otherwise SH-1 mode
*/
void SH2Disasm(unsigned v_addr, unsigned char *p_addr, int mode, char *m_addr)
{
int i;
unsigned short op;
op = (unsigned short) (*p_addr << 8) | *(p_addr + 1);
printf("0x%08X: 0x%04X\t", v_addr, op);
if (m_addr[0]==ND8_F)
{
if (m_addr[2]==-1)
{
unsigned int tmp = (op << 16) | ((unsigned int) (p_addr [2] << 8) | p_addr[3]);
printf(".long\t0x%08X\t; 0x%08X",tmp,v_addr - (unsigned)m_addr[1]);
}
else
printf(".short\t0x%08X\t; 0x%08X",op,v_addr - (unsigned)m_addr[1]);
}
else if (m_addr[0] != -1)
{
for (i = 0; tab[i].mnem != NULL; i++) /* 0 format */
{
if ((op & tab[i].mask) == tab[i].bits)
{
if (tab[i].sh2 && mode) /* if SH-1 mode, no SH-2 */
printf("???");
else if (tab[i].format == ZERO_F)
printf("%s", tab[i].mnem);
else if (tab[i].format == N_F)
printf(tab[i].mnem, (op >> 8) & 0xf);
else if (tab[i].format == M_F)
printf(tab[i].mnem, (op >> 8) & 0xf);
else if (tab[i].format == NM_F)
printf(tab[i].mnem, (op >> 4) & 0xf,
(op >> 8) & 0xf);
else if (tab[i].format == MD_F)
{
if (op & 0x100)
printf(tab[i].mnem, (op & 0xf) * 2,
(op >> 4) & 0xf);
else
printf(tab[i].mnem, op & 0xf,
(op >> 4) & 0xf);
}
else if (tab[i].format == ND4_F)
{
if (op & 0x100)
printf(tab[i].mnem, (op & 0xf) * 2,
(op >> 4) & 0xf);
else
printf(tab[i].mnem, (op & 0xf),
(op >> 4) & 0xf);
}
else if (tab[i].format == NMD_F)
{
if ((op & 0xf000) == 0x1000)
printf(tab[i].mnem, (op >> 4) & 0xf,
(op & 0xf) * 4,
(op >> 8) & 0xf);
else
printf(tab[i].mnem, (op & 0xf) * 4,
(op >> 4) & 0xf,
(op >> 8) & 0xf);
}
else if (tab[i].format == D_F)
{
if (tab[i].dat <= 4)
{
if ((op & 0xff00) == 0xc700)
{
printf(tab[i].mnem,
(op & 0xff) *
tab[i].dat + 4);
printf("\t; 0x%08X",
(op & 0xff) *
tab[i].dat + 4 +
v_addr);
}
else
printf(tab[i].mnem,
(op & 0xff) *
tab[i].dat);
}
else
{
if (op & 0x80) /* sign extend */
printf(tab[i].mnem,
(((op & 0xff) +
0xffffff00) * 2) +
v_addr + 4);
else
printf(tab[i].mnem,
((op & 0xff) * 2) +
v_addr + 4);
}
}
else if (tab[i].format == D12_F)
{
if (op & 0x800) /* sign extend */
printf(tab[i].mnem,
((op & 0xfff) + 0xfffff000) * 2
+ v_addr + 4);
else
printf(tab[i].mnem, (op & 0xfff) * 2 +
v_addr + 4);
}
else if (tab[i].format == ND8_F)
{
int imm = (op & 0xff) * tab[i].dat + 4;
if ((op & 0xf000) == 0x9000) /* .W */
{
int dat = (unsigned short) (*(imm + p_addr) << 8) | *(imm + p_addr + 1);
m_addr[imm+0] = ND8_F; /* this couldn't be an instruction so mark it ! */
m_addr[imm+1] = imm;
printf(tab[i].mnem,
imm,
(op >> 8) & 0xf);
printf("\t; 0x%08X (0x%04X)",
imm + v_addr, dat);
}
else /* .L */
{
unsigned char *b_addr = (unsigned char *)((intptr_t)p_addr & ~3);
int dat = (unsigned int) (*(imm + b_addr) << 24) | (*(imm + b_addr + 1) << 16)
| (*(imm + b_addr + 2) << 8) | *(imm + b_addr + 3) ;
/* SH-1 register name lookup */
char* str = "";
if ( (dat & 0xfffffe00) == 0x05fffe00 )
str = regname[dat & 0x1ff];
m_addr[imm+(b_addr-p_addr)+0] = ND8_F; /* this couldn't be an instruction so mark it ! */
m_addr[imm+(b_addr-p_addr)+1] = imm;
m_addr[imm+(b_addr-p_addr)+2] = -1;
printf(tab[i].mnem,
imm,
(op >> 8) & 0xf);
printf("\t; 0x%08X (0x%08X) %s",
imm + (v_addr & 0xfffffffc), dat, str);
}
}
else if (tab[i].format == I_F)
printf(tab[i].mnem, op & 0xff);
else if (tab[i].format == NI_F)
printf(tab[i].mnem, op & 0xff, (op >> 8) &
0xf);
else
printf("???");
printf("\n");
return;
}
}
printf("???");
}
printf("\n");
}
void ShowHelp()
{
printf("sh2d Version %s by Bart Trzynadlowski: A Free SH-1/SH-2 "
"Disassembler\n", VERSION);
printf("Usage: sh2d <file> [options]\n");
printf("Options: -?,-h Show this help text\n");
printf(" -s # Start offset (hexadecimal)\n");
printf(" -l # Number of bytes (decimal)\n");
printf(" -o # Set origin (hexadecimal)\n");
printf(" -sh1 SH-1 disassembly only\n");
printf(" -sh2 SH-2 disassembly (default)\n");
exit(0);
}
int main(int argc, char **argv)
{
FILE *fp;
long fsize, file, mode;
unsigned start, len, calc_len = 0, org, do_org, i, j = 0;
char *buffer;
char *mark;
if (argc == 1) /* show help */
ShowHelp();
if (FindOption("-?", 0, 0, 0, argc, argv) ||
FindOption("-h", 0, 0, 0, argc, argv))
ShowHelp();
if (FindOption("-sh1", 0, 0, 0, argc, argv))
mode = 1; /* SH-1 mode */
else
mode = 0; /* SH-2 mode */
if (FindOption("-sh2", 0, 0, 0, argc, argv))
mode = 0; /* SH-2 mode */
start = FindOption("-s", 1, 1, 0, argc, argv);
org = FindOption("-o", 1, 1, 0, argc, argv);
if (!(len = FindOption("-l", 1, 0, 0, argc, argv)))
{
if (FindOption("-l", 0, 0, 0, argc, argv))
return 0; /* -l was actually specified w/ 0 */
calc_len = 1; /* no -l, calculate length */
}
if (FindOption("-o", 0, 0, 0, argc, argv))
do_org = 1; /* -o was actually 0 */
else
do_org = 0; /* there was no -o, ignore the org variable */
if (!(file = FindOption(NULL, 0, 0, 1, argc, argv)))
{
fprintf(stderr, "sh2d: No input file specified. Try "
"\"sh2d -h\" for usage instructions\n");
exit(1);
}
if ((fp = fopen(argv[file], "rb")) == NULL)
{
fprintf(stderr, "sh2d: Failed to open file: %s\n",
argv[file]);
exit(1);
}
fseek(fp, 0, SEEK_END);
fsize = ftell(fp);
rewind(fp);
if ((buffer = (char *) calloc(fsize * 2, sizeof(unsigned short)))
== NULL)
{
fprintf(stderr, "sh2d: Not enough memory to load input "
"file: %s, %lu bytes\n", argv[file], fsize);
exit(1);
}
fread(buffer, sizeof(unsigned char), fsize, fp);
fclose(fp);
if (calc_len)
len = fsize - start;
mark = buffer + fsize;
for (i = start; i < (unsigned) fsize && j < len; i += 2)
{
if (do_org)
{
SH2Disasm(org, (unsigned char*)&buffer[i], mode, &mark[i]);
org += 2;
}
else
SH2Disasm(i, (unsigned char *)&buffer[i], mode, &mark[i]);
j += 2;
}
return 0;
}
|
the_stack_data/99057.c | #include<stdio.h>
struct proc
{
int no,at,bt,ct,tat,wt,rt;
};
struct proc read(int i)
{
struct proc p;
printf("\nProcess No: %d\n",i);
p.no=i;
printf("Enter Arrival Time: ");
scanf("%d",&p.at);
printf("Enter Burst Time: ");
scanf("%d",&p.bt);
p.rt=p.bt;
return p;
}
int main()
{
struct proc p[10],tmp;
float avgtat=0,avgwt=0;
int n,tq,ct=0,flag=0,remaining;
printf("<--Round Robin Scheduling Algorithm-->\n");
printf("Enter Number of Processes: ");
scanf("%d",&n);
printf("Enter Time Quantum: ");
scanf("%d",&tq);
for(int i=0;i<n;i++)
p[i]=read(i+1);
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
if(p[j].at>p[j+1].at)
{
tmp=p[j];
p[j]=p[j+1];
p[j+1]=tmp;
}
remaining=n;
printf("\nProcessNo\tAT\tBT\tCT\tTAT\tWT\n");
for(int i=0;remaining!=0;)
{
if(p[i].rt<=tq&&p[i].rt>0)
{
ct+=p[i].rt;
p[i].rt=0;
flag=1;
}
else if(p[i].rt>0)
{
p[i].rt-=tq;
ct+=tq;
}
if(p[i].rt==0&&flag==1)
{
flag = 0;
remaining--;
p[i].ct=ct;
p[i].tat=p[i].ct-p[i].at;
avgtat+=p[i].tat;
p[i].wt=p[i].tat-p[i].bt;
avgwt+=p[i].wt;
printf("P%d\t\t%d\t%d\t%d\t%d\t%d\n",p[i].no,p[i].at,p[i].bt,p[i].ct,p[i].tat,p[i].wt);
}
if(i!=n-1&&p[i+1].at<=ct)
i++;
else
i=0;
}
avgtat/=n,avgwt/=n;
printf("\nAverage TurnAroundTime=%f\nAverage WaitingTime=%f",avgtat,avgwt);
} |
the_stack_data/78699.c | //8. Dados dois vetores “a” e “b” com 6 elementos inteiros cada. Implementar um programa que verifica se os
//v/etores sao iguais na ordem.
//Exemplo 1:
//int a[6] = {1, 2, 3, 4, 5, 6};
//int b[6] = {1, 2, 3, 4, 5, 6};
//Os vetores “a” e “b” sao iguais.
//Exemplo 2:
//int a[6] = {1, 2, 3, 4, 5, 6};
//int b[6] = {1, 6, 3, 4, 5, 2};
//Os vetores “a” e “b” sao diferentes.
//Mostre os valores dos vetores “a” e “b” e o resultado da verificacao: sao iguais; ou sao diferentes.
#include <stdio.h>
int main()
{
#define t 6 //tamanho vetor
int item;
int a[t], b[t];
int diferente = 0;
printf("Vetor A\n");
for (int i = 0; i < t; i++)
{
scanf("%d", &a[i]);
}
printf("Vetor B\n");
for (int j = 0; j < t; j++)
{
scanf("%d", &b[j]);
if (a[j] != b[j])
{ // ja aproveita o loop para verificar a condicao
diferente = 1;
}
}
for (int z = 0; z < t; z++)
{
printf("A[%d]= %d |B[%d]= %d |\n", z, a[z], z, b[z]);
}
if (diferente)
{
printf("A e B sao diferenes");
}
else
{
printf("A e B sao iguais ");
}
return 0;
}
|
the_stack_data/243892763.c | // RUN: rm -rf %t*
// RUN: 3c -base-dir=%S -addcr -alltypes %s -- | FileCheck -match-full-lines -check-prefixes="CHECK_ALL","CHECK" %s
// RUN: 3c -base-dir=%S -addcr %s -- | FileCheck -match-full-lines -check-prefixes="CHECK_NOALL","CHECK" %s
// RUN: 3c -base-dir=%S -addcr %s -- | %clang -c -fcheckedc-extension -x c -o /dev/null -
// RUN: 3c -base-dir=%S -alltypes -output-dir=%t.checked %s --
// RUN: 3c -base-dir=%t.checked -alltypes %t.checked/definedType.c -- | diff %t.checked/definedType.c -
#include <stdlib.h>
// From issue 204
// Here, we specifically want to test 3C's behavior on a macro that expands to a
// type. Use a different name to avoid any confusion with the `ulong` that is
// defined as a typedef in sys/types.h on some systems.
#define my_ulong unsigned long
my_ulong *TOP;
// CHECK_NOALL: my_ulong *TOP;
// CHECK_ALL: _Array_ptr<my_ulong> TOP = ((void *)0);
my_ulong channelColumns;
void DescribeChannel(void) {
my_ulong col;
TOP = (my_ulong *)malloc((channelColumns + 1) * sizeof(my_ulong));
// CHECK_ALL: TOP = (_Array_ptr<unsigned long>)malloc<unsigned long>((channelColumns + 1) * sizeof(my_ulong));
// CHECK_NOALL: TOP = (my_ulong *)malloc<unsigned long>((channelColumns + 1) * sizeof(my_ulong));
TOP[col] = 0;
}
#define integer int
integer foo(int *p, int l) {
// CHECK_ALL: integer foo(_Array_ptr<int> p : count(l), int l) _Checked {
// CHECK_NOALL: integer foo(int *p : itype(_Ptr<int>), int l) {
return p[l - 1];
}
int *bar(integer p, integer i) {
// CHECK: _Ptr<int> bar(integer p, integer i) _Checked {
return 0;
}
// Macros containing only the base type are kept in checked pointer
#define baz unsigned int
baz a;
// CHECK: baz a;
baz *b;
// CHECK: _Ptr<baz> b = ((void *)0);
baz **c;
// CHECK: _Ptr<_Ptr<baz>> c = ((void *)0);
baz d[1];
// CHECK_ALL: baz d _Checked[1];
baz *e[1];
// CHECK_ALL: _Ptr<baz> e _Checked[1] = {((void *)0)};
baz **f[1];
// CHECK_ALL: _Ptr<_Ptr<baz>> f _Checked[1] = {((void *)0)};
baz (*g)[1];
// CHECK_ALL: _Ptr<baz _Checked[1]> g = ((void *)0);
baz h[1][1];
// CHECK_ALL: baz h _Checked[1] _Checked[1];
baz *i() {
// CHECK: _Ptr<baz> i(void) _Checked {
return 0;
}
baz **j() {
// CHECK: _Ptr<_Ptr<baz>> j(void) _Checked {
return 0;
}
void k(baz x, baz *y, baz **z) {}
// COM: void k(baz x, _Ptr<baz> y, _Ptr<_Ptr<baz>> z) _Checked {}
// Macros are inlined if there's a pointer in the macro
// This could probably be handled better in the future.
#define buz int *
buz l;
// CHECK: _Ptr<int> l = ((void *)0);
buz *m;
// CHECK: _Ptr<_Ptr<int>> m = ((void *)0);
// Macro should not change when wild
buz n = (buz)1;
// CHECK: buz n = (buz)1;
// This was a regression in lua. The function type is wrapped in a ParenType.
int *(lua_test0)() {
// CHECK: _Ptr<int> lua_test0(void) _Checked {
return 0;
}
baz *(lua_test1)() {
// CHECK: _Ptr<baz> lua_test1(void) _Checked {
return 0;
}
baz(*lua_test2);
// CHECK: _Ptr<baz> lua_test2 = ((void *)0);
baz(*(*lua_test3));
// CHECK: _Ptr<_Ptr<baz>> lua_test3 = ((void *)0);
typedef int *StkId;
void lua_test4(StkId *x) {}
//CHECK: void lua_test4(_Ptr<StkId> x) _Checked {}
// Things declared inside macros should be WILD unless we start doing something
// extremely clever
// clang-format messes up this part of the file because it mistakes macro
// references for other syntactic constructs.
// clang-format off
#define declare_function(x) \
int *foo##x(int *a) { return a; } \
int *bar##x(int *a) { return a; }
declare_function(1)
#define declare_var(x) \
int *x##1; \
int **x##2; \
int ***x##3;
declare_var(y)
void test() {
int *x = 0;
int *y = 0;
int *a = foo1(x);
int *b = bar1(y);
int *c = y1;
int **d = y2;
int ***e = y3;
}
// CHECK: void test() {
// CHECK: int *x = 0;
// CHECK: int *y = 0;
// CHECK: int *a = foo1(x);
// CHECK: int *b = bar1(y);
// CHECK: int *c = y1;
// CHECK: int **d = y2;
// CHECK: int ***e = y3;
#define parm_decl int *a, int *b
void parm_test(parm_decl) {}
// CHECK: void parm_test(parm_decl) {}
#define declare_single_var(x) int *x = 0;
int *another_test(void) {
// CHECK: int *another_test(void) : itype(_Ptr<int>) {
declare_single_var(z)
// CHECK: declare_single_var(z)
declare_single_var(y)
// CHECK: declare_single_var(y)
return z;
}
// clang-format on
|
the_stack_data/750098.c | /*
* find two repeating elements in a given array
* approach 4 : using xor
* */
#include<stdio.h>
#include<stdlib.h>
void printRepElements(int *arr, int size)
{
int n = size - 2, i, x = 0, y = 0;
int xorRes = arr[0];
for (i = 1; i < size; ++i)
xorRes = xorRes ^ arr[i];
for (i = 1; i <= n; ++i)
xorRes = xorRes ^ i;
// xorRes is now equal to x ^ y, so our task is now to find out x and y
int setBit = xorRes & ~(xorRes-1);
for (i = 0; i < size; ++i)
{
if (arr[i] & setBit)
x = x ^ arr[i];
else
y = y ^ arr[i];
}
// now we even need to xor with natural numbers
for (i = 1; i <= n; ++i)
{
if (i & setBit)
x = x ^ i;
else
y ^= i;
}
printf("\nFirst number = %d\nSecond Number = %d", x, y);
}
int main()
{
int i;
int arr[] = {1, 4, 5, 1, 2, 5, 3};
int n = sizeof(arr)/sizeof(arr[0]) - 2;// because we have n+2 elements in array
printRepElements(arr, n+2);
printf("\n");
return 0;
}
// time is O(n)
// space is constant
|
the_stack_data/79511.c | /*
* Check that strace output contains RT_1 RT_3 RT_31 RT_32 here:
* rt_sigprocmask(SIG_BLOCK, [CHLD RT_1 RT_3 RT_31 RT_32], NULL, 8) = 0
* and here:
* sigreturn() (mask [CHLD RT_1 RT_3 RT_31 RT_32]) = 0
*
* On x86, both 32-bit and 64-bit strace needs to be checked.
*/
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void null_handler(int sig)
{
}
int main(int argc, char *argv[])
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGCHLD);
sigaddset(&set, 33);
sigaddset(&set, 35);
sigaddset(&set, 63);
sigaddset(&set, 64);
sigprocmask(SIG_BLOCK, &set, NULL);
signal(SIGWINCH, null_handler);
raise(SIGWINCH);
return 0;
}
|
the_stack_data/6350.c | #include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>
unsigned char check1[] = "\x1f\x4b\x3c\x6b\x02\x80\x59\xee\x02\x8a\xc8\x26\xc3\x76\x11\xea\x02\x88\xb1\xab\x62\x03\xb5\x8e\x02\x8a\xf0\x76\x7b\xc3\x72\xcb\x8a\x47\xc0\xc3\x28\xc5\xf0\x4a\x4a\x4b\x72\xcb\x9a\x03\xb5\x8e\x4a\x4b\x72\xcb\x92\x03\xb5\x8e\x4a\x4b\x72\xcb\xaa\x03\xb5\x8e\x4a\xc4\xf0\x66\x4a\x03\xb5\x8e\x2c\xc4\xf0\x62\x4a\x03\xfd\x36\x03\x25\xc7\xbb\x3c\x32\xa6\x8a\x02\x8a\xf0\x4b\x2c\xc4\xf0\x43\x04\x5d\x73\xcb\x85\x03\x72\xcb\xf2\x03\xb5\x8e\x4a\xc4\xf0\x32\x4b\x03\xb5\x8e\x8d\x46\x0d\x8e\x4a\x03\xb5\x65\x73\x88\xf0\x36\x02\x60\x65\xc6\xc1\x46\x1d\xc6\x4b\xd3\xba\x38\x42\x88\xf0\x36\xd3\xc2\x5f\x90\x4b\xd3\x36\x6e\x49\x2a\x65\xc6\xd2\x0c\x03\xca\x4f\xc3\x36\x66\x4d\x32\x74\x07\x80\x88\xf0\x36\x02\x9b\x3d\xda\x4f\xd3\x36\xcb\xf2\x02\x3e\xcb\xf2\x38\xf0\x2a\x36\xbc\x72\xcb\xf2\x03\xb5\x8e\x4a\xe8\x96\x05\x0f\xbb\xfd\x16\x45\xb5\xe1\x8b\x9a\x88\xf0\x36\x02\x9b\xba\x38\x0e\x06\x70\xb6\x88\x77\xb2\x49\x0f\xbf\xb5\x8e\x4a\x03\x36\xcb\xf2\x02\x3e\xcb\xf2\x38\xf0\x2a\x36\xd6\x3e\xcb\xf6\x4b\x3e\xfb\xb2\x67\xfd\xbd\x7e\x26\x9d\x8e\x4a\x03\xc1\x8b\xa2\xb7\x49\x71\xb5\xca\x76";
unsigned char check2[] = "\x11\x92\x76\x23\x0c\x59\x13\xb6\x0c\x53\x82\x5e\x20\x92\x74\xc2\x61\xf2\xff\xc6\x44\x92\x76\x83\xbc\xeb\x3f\x01\x01\x7e\xff\xc6\x44\xda\x38\x83\xec\xda\xff\xc6\x44\x1d\xba\x6a\x44\xda\xff\xc6\x83\x9f\x4f\xc7\x44\xda\xff\x01\x01\x0a\x42\x4b\x8f\x4f\x38\x83\x90\xa3\x33\x42\x4b\x1d\xba\x1e\x32\x72\x66\x7e\x83\x9f\x23\x93\xef\x87\xf5\x01\x01\x3a\x45\xfd\xcf\x40\x38\x83\xa0\x7d\xc7\x74\x34\x1d\xba\x2e\xb5\xe6\x4a\xb4\x83\x9f\x13\xcf\x46\xa6\x2b\x01\x01\x76\xff\xc6\x44\xda\x16\xd5\x45\xda\xff\x4d\x01\x76\xb7\xa5\x94\x92\x74\x83\xdc\x92\xfe\x16\x4b\x6c\xff\xc9\xfa\x1a\xda\x39\x44\xda\xff\x4f\x01\x7e\x74\x83\xe8\x92\x67\x8e\xc9\x8a\xfb\x8e\xcf\x9f\x67\x8e\x45\x0a\xf0\x70\x44\xd5\x41\x06\x61\x25\xff\xc6\x44\x53\xba\x6e\x83\x9f\x4b\xc6\x44\xda\xff\x01\x01\x66\x52\x18\x73\xc9\x38\x83\x84\x99\xff\xc6\x44\x1d\xba\x02\x74\xda\xff\xc6\x83\x9f\x37\x94\x44\xda\xff\x01\x01\x16\xcc\xc6\x44\xda\x38\x83\xfc\xda\xff\xc6\x44\x1d\xba\x7e\x44\xda\xff\xc6\xaf\xbf\x74\x83\xec\x1b\x1f\xc2\xcd\x18\x74\x83\xec\x1b\x17\xc3\x75\x18\x74\x83\xec\x57\xf3\xc4\xcf\x9f\x4b\x45\xa4\xd9\x76\x06\xcf\x8e\x7a\x06\xcf\x9f\x4b\xc7\x94\xeb\x37\xc7\x01\x7e\x74\x83\xf8\xdb\xba\x72\xcf\x9f\x5b\x07\xa4\xde\x76\x04\xcf\x9f\x5b\x07\xac\xdf\xce\x04\xcf\x9f\x5b\x4b\x48\xd8\x74\x83\xf0\x1b\x17\xcd\xc7\x3a\xfc\x4f\x84\x51\xab\x43\x84\x51\xba\x72\x45\x0a\xce\x0e\x45\x9f\x57\x45\x01\x62\xfe\x45\x39\x62\xe0\xb8\xd1\x51\xba\x6a\x45\x1a\xb7\x5e\xcf\x9e\x7a\x16\x7d\x9f\x5b\xb2\x43\x1d\xba\x76\x44\xda\xff\xc6\xcf\x9f\x53\xc7\x84\x59\x3f\xc7\x0c\x42\x74\x82\xc1\x0a\xc6\x83\xec\xae\xf8\x01\x01\x6a\xff\xc6\x44\xda\x7c\x83\xe8\xdb\x7c\xbb\xe8\xd9\xf0\x48\xa7\x24\x00\x39\xcf\x9f\x4f\x8e\xcf\xaf\x07\xa2\x0c\xe9\xcb\xe3\x6c\xda\xff\xc6\x30\xdf\x17\x3b\xbe\x25\x00\x0f\x87";
unsigned char check3[] = "\xb4\x77\x63\x60\xa9\xbe\x06\x65\xe1\x3f\xea\xcd\x68\x82\xc2\x7a\x1e\xc0\x63\x30\xc5\xc0\x15\x7a\x85\x77\x61\x81\xc4\x17\xea\x85\xe1\x77\x63\xc0\x19\x0e\x2a\xcd\x26\xba\x9a\x7a\x1e\xc0\xea\x85\xe1\x3f\xa2\x42\x64\x47\x15\x7a\x1e\x3f\xea\x85\xe1\x77\x2d\xc0\x61\x3f\xea\x85\xe1\x77\x2d\xc0\x69\x3f\xea\x85\xe1\x77\x2d\xc0\x71\x3f\xea\x85\xe1\x77\x2d\xc0\x79\x3f\xea\x85\xe1\x59\x2d\xc0\x41\x3f\xea\xcd\x59\x15\x96\xa8\xa8\x59\x84\xf4\xd3\x77\x50\xb5\xc0\x1f\xe0\xc4\xbb\x5b\xce\xcd\x68\x7a\x5a\xcd\x68\x6a\x52\xcd\x59\x4d\xd6\xdd\x8e\x63\xae\xaa\x9a\x77\x50\xce\xa2\x41\x8b\xb1\xb5\x45\xdd\xcd\x68\x7a\x2a\xcd\x68\x6a\x22\xcd\x59\x16\xb3\xdb\xdb\x47\x8a\x8e\x9c\x77\x50\xd6\x92\x0e\x93\xca\x8c\x56\x9c\xcd\x68\x7a\x3a\xcd\x68\x6a\x32\xcd\x59\x1c\xe7\xa0\xbc\x7f\xb1\xda\xaf\x77\x50\xad\xa9\x55\xc6\xd3\xb0\x4a\x8d\xcd\x68\x7a\x0a\xcd\x68\x6a\x02\x43\xa4\xcf\xea\xcd\x59\x0b\x8a\xd4\xc4\x7e\xb5\xc4\xc2\x77\x50\xd1\xdb\x65\xcf\xc4\xce\x77\x97\xcd\x68\xba\xba\x7a\x1e\xc0\xa2\x0c\x74\x67\x15\x7a\x1e\x77\x52\xfe\xc4\x52\xb9\xc4\xba\x6e\xe1\xcd\x68\xba\x8a\x7a\x1e\xc0\x2c\x00\x89\xc0\x15\x7a\xe1\xf8\x6f\xb5\x1e\xc0\x15\x84\xe1\x3f\xea\x0e\x64\x1b\x15\x7a\x1e\x77\x89\x55\xa9\xb4\x6f\xad\x1e\xc0\x15\xcd\xe0\xef\xa2\x0c\x64\x77\x15\x7a\x1e\x77\x61\x00\xc9\xc0\x15\x7a\xa9\xb6\x6f\xc5\x1e\xc0\x15\xcd\x6c\xba\x9a\x7a\x1e\xc0\xa2\x0c\x64\x07\x15\x7a\x1e\xd6\x10\x85\xe1\x3f\xa2\x0e\x64\x7f\x15\x7a\x1e\x30\x5c\x85\x21\xd7\xe8\x8a\x57\xff\xa2\x1d\xee\x89\xa6\x80\x51\x77\x61\x00\xd9\xc0\x15\x7a\xa9\xb2\xba\x84\xa9\xb6\x7f\xbd\x1e\xc0\x15\x0c\x2b\xb7\xfa\xcd\x6a\xba\xaa\x7a\x1e\xc0\xe5\x33\xe1\x30\x5c\x45\x20\xdf\xee\x06\x01\x0f\x63\x47\xa9\xb4\x6f\xc5\x1e\xc0\x15\xcd\x62\xff\xeb\x8a\x57\x3f\x2a\x6d\xe5\x30\x5c\x45\xe8\xef\xa2\x1d\xee\x89\xa6\x80\x51\x77\x61\x00\xd9\xc0\x15\x7a\xa9\xb2\xba\x84\xa9\xb6\x7f\xbd\x1e\xc0\x15\x0c\x2b\xb7\xfa\xcd\x6a\xba\xaa\x7a\x1e\xc0\xa2\x06\x21\x3e\xe5\x33\xe1\x30\x5c\x45\x20\xdf\xe8\x06\x01\x03\x63\x47\xa9\xb4\x6f\xc5\x1e\xc0\x15\xcd\x62\xff\xe8\x8a\x57\x3f\x2a\x6d\xe7\x30\x5c\x45\xe8\xef\xa2\x1d\xee\x89\xa6\x80\x51\x77\x61\x00\xd9\xc0\x15\x7a\xa9\xb2\xba\x84\xa9\xb6\x7f\xbd\x1e\xc0\x15\x0c\x2b\xb7\xfa\xcd\x6a\xba\xaa\x7a\x1e\xc0\xa2\x06\x21\x3d\xe5\x33\xe1\x30\x5c\x45\x62\xdf\xd5\xcd\x79\x30\x5c\xc9\xe4\x8f\xa2\x0e\x64\x07\x15\x7a\x1e\x77\x67\xd5\xe0\x77\x63\x10\xd9\xc0\x15\x7a\x68\xf5\x62\x95\xa9\xbc\x6f\xc5\x1e\xc0\x15\x86\xa9\xb4\x7f\xcd\x1e\xc0\x15\xcd\x6a\xba\xaa\x7a\x1e\xc0\xa2\xac\x23\x77\x63\x55\xa9\xbc\x12\x87\xee\xb0\x02\x7b\x1e\xc0\x2d\x00\xd5\xc0\x15\x7a\xe1\x3f\xea\x85\x26\xba\xde\x7a\x1e\xc0\xea\x85\xe1\x3f\x01\xbe\x6a\xba\xde\x7a\x1e\xc0\xa2\x1d\xee\x89\x6e\x80\x91\xc0\x15\x7a\xee\x89\x3a\x0e\x64\x0b\x15\x7a\x1e\x77\x72\x8a\x57\xbb\xef\xd5\x1e\xc0\x15\x8a\x5f\xff\xd3\x47\x95\x35\x2d\x00\xd1\xc0\x15\x7a\xe1\x3f\xea\x85\x62\xba\xde\x7a\x1e\xc0\xeb\x06\x5c\x0b\x15\x7a\x1e\x28\x94\x39\x6a\xba\xda\x7a\x1e\xc0\xa2\x0e\x94\xc7\x8e\xcd\xd2\x0b\xcf\xad\xe1\x3f\xea\xf1\xe4\xd7\xf3\x7d\x1e\xc0\x23\x46";
unsigned char check4[] = "\xa7\xd6\x24\xa7\xba\x1f\x41\xe2\xf6\x9e\xad\x0a\x7b\x23\xc5\xb9\x0d\x61\x24\xf7\x96\x65\x52\xbd\x96\xd6\x26\x46\xd7\xb6\xad\x42\xf2\xd6\x24\x07\x0a\xaf\x6d\x0a\x7f\x0b\x3d\xb9\x0d\x61\x15\x42\xf2\x9e\xad\xfb\x8f\x9e\xad\x42\xba\x17\x7a\xb1\xba\x35\xe5\xfa\xa2\xf2\x9e\x23\x81\xc1\xc9\x72\xba\x24\xc3\x65\x86\xc1\xce\x10\xc6\xab\xe5\xcb\xb7\x0e\xe5\xcb\xa7\x06\xe5\xfa\x9a\xc1\x9c\x2c\xad\xb5\xc5\x63\xba\x24\xde\x1d\x94\xcb\xc3\x01\xd9\xaf\xe5\xcb\xb7\x3e\xe5\xcb\xa7\x36\xcb\x85\xb7\x2e\x9d\x2c\x34\xdb\x1f\x42\xba\x59\xe8\x82\xf2\x9e\xad\x42\xba\x59\xe8\x8a\xf2\x9e\xad\x42\xba\x59\xe8\x92\xf2\x9e\xad\x42\xba\x59\xe8\x9a\xf2\x9e\xad\x42\xba\x59\xe8\xa2\xf2\x9e\xad\x42\xba\x59\xe8\xaa\xf2\x9e\xad\x42\x94\x59\xe8\xb2\xf2\x9e\xe5\xfa\xd9\xcb\xf0\xd1\x52\xdd\x70\x56\xba\x17\xe8\xc1\x35\xdb\x26\x01\xa0\xe3\x48\x84\xb7\x11\xad\x85\x77\x1e\x56\xbd\x0d\xbc\xad\x42\xf2\x59\x28\x32\x09\x61\x52\x42\xf2\x9e\xad\x85\x77\xea\x56\xbd\x0d\x9e\xad\x42\xf2\x59\x28\x3a\x09\x61\x52\x43\xf2\x9e\xad\x85\x77\xee\x56\xbd\x0d\x9e\xad\x42\xf2\x75\xb1\xc9\x77\xee\x56\xbd\x0d\xd6\x35\xc9\x67\xee\x56\xbd\x0d\x17\x39\xc7\x62\x65\x52\xbd\x71\x1b\xdd\xb9\x0d\x61\xac\xc3\x4f\xee\x56\xbd\x0d\x6b\xad\x42\xf2\xe0\x75\x85\x77\xee\x56\xbd\x0d\x9e\xad\x42\xf2\x77\x1e\x42\xf2\x9e\x26\xc7\x82\x65\x52\xbd\xba\x06\x26\xd6\x77\x0e\x56\xbd\x0d\x15\x28\x36\x09\x61\x52\xcf\xfe\x9c\x26\xc7\x82\x65\x52\xbd\x6b\x69\x10\xc2\x09\x61\x52\xcb\x22\xd6\x35\x4d\x44\xda\xa8\xd2\xfd\x28\x6d\x43\x33\x24\xb8\x40\xbf\xbf\x24\x8a\x05\x74\x6c\xb8\xf7\x17\x65\x83\x0a\x81\x84\x80\x7b\x4e\x24\xc7\x86\x65\x52\xbd\x79\x1b\xd9\xb9\x0d\x61\xc4\x82\x04\x9e\xad\x42\xdb\x5f\x24\x8a\x7b\x1b\xd9\xb9\x0d\x61\x26\xc7\x82\x65\x52\xbd\xba\x06\x26\xc6\x77\x0e\x56\xbd\x0d\x17\x28\xce\x09\x61\x52\xc9\x77\xea\x56\xbd\x0d\xd6\x35\xc9\x66\x1b\x3d\xb9\x0d\x61\x26\xc7\x82\x65\x52\xbd\xba\x06\x24\xd6\x77\x0e\x56\xbd\x0d\x15\x28\x36\x09\x61\x52\x0a\x6a\x15\x38\xce\x09\x61\x52\xcb\x66\x1b\x3d\xb9\x0d\x61\x2e\xc7\x82\x65\x52\xbd\xf3\x1f\x10\x32\x09\x61\x52\xb7\xf2\x9e\xad\x4d\x7c\xa3\x52\xbd\x0d\x59\x28\x3e\x09\x61\x52\x42\xf2\x9e\xad\x85\x77\xee\x56\xbd\x0d\x9e\xad\x42\xf2\x59\x28\x36\x09\x61\x52\x42\xf2\x9e\xad\xab\xbd\x9f\xad\x42\x79\x1b\xdd\xb9\x0d\x61\x20\x0a\xf3\x24\xb8\x40\xbf\xbf\x24\x8a\x05\x74\x6c\xb8\xf7\x17\x65\x83\x0a\x81\x84\x80\x7b\x4e\x24\xc7\x82\x65\x52\xbd\x79\x1b\xdd\xb9\x0d\x61\xc4\x82\x04\x9e\xad\x42\xdb\x5f\x24\x8a\x7b\x1b\xdd\xb9\x0d\x61\x26\xc7\x82\x65\x52\xbd\xba\x06\x26\xd6\x77\x0e\x56\xbd\x0d\x15\x28\x36\x09\x61\x52\xcf\xfe\x9c\x17\x57\xf0\xd3\x8c\xcb\x3a\x69\x47\x83\x08\x9b\x24\x8a\x33\x66\xb2\x6b\x30\x17\x7d\xcb\x77\xea\x56\xbd\x0d\x15\x28\x36\x09\x61\x52\x2b\x32\x68\xad\x42\xf2\xb7\x6c\xcb\x3a\x17\x28\x36\x09\x61\x52\xc9\x77\xee\x56\xbd\x0d\xd6\x35\xc9\x76\x1b\x3d\xb9\x0d\x61\x24\xc7\x76\x65\x52\xbd\x79\x1b\xd9\xb9\x0d\x61\xe5\xda\x79\x0a\x28\xd2\x09\x61\x52\xc9\x77\xee\x56\xbd\x0d\xd6\x35\xcb\x66\x1b\x3d\xb9\x0d\x61\x26\xc7\x86\x65\x52\xbd\xba\x06\x26\xd7\x76\x65\x52\xbd\x7b\x0a\x28\xd2\x09\x61\x52\xc9\x77\xee\x56\xbd\x0d\xd6\x35\xc9\x66\x1b\x3d\xb9\x0d\x61\x26\xc7\x86\x65\x52\xbd\xba\x06\x26\xc6\x77\x0e\x56\xbd\x0d\x13\xa1\x40\x48\x8b\xaf\x0f\xd3\x17\x65\xb5\x18\x5f\x57\x47\x7b\x56\x6c\xba\xed\xb7\x6f\xcb\x22\xf7\x6d\xb4\xf2\x9e\xad\x6b\x33\x17\x65\x0a\x6a\x15\x29\xc7\x62\x65\x52\xbd\x7b\x1b\x25\xb9\x0d\x61\x26\xc7\x7a\x65\x52\xbd\x7b\x5f\x26\xc7\x8e\x65\x52\xbd\xba\xfd\x7d\x0a\x79\x1b\xc5\xb9\x0d\x61\xe5\x43\x22\x91\x1b\x42\xc3\x56\x24\x80\x79\x1b\xd1\xb9\x0d\x61\xe5\xda\x7a\xca\xa8\x82\x71\x1b\xd1\xb9\x0d\x61\xac\xc9\x77\xe2\x56\xbd\x0d\xa5\x28\x26\x09\x61\x52\x4d\x7e\x01\x53\xbd\x0d\x59\x28\x32\x09\x61\x52\x42\xf2\x9e\xad\xa9\xdd\x15\x28\x32\x09\x61\x52\x0a\x6a\x91\x1b\x16\xf7\x5e\x26\xc7\x82\x65\x52\xbd\xba\x06\xa2\xf4\xb6\x9b\x2e\x7a\x30\xea\xa7\x85\x77\xe6\x56\xbd\x0d\x9e\xad\x42\xf2\x1d\x28\x32\x09\x61\x52\x43\x79\x1b\xdd\xb9\x0d\x61\x96\xc7\x96\x65\x52\xbd\x8e\x5d\x26\xc7\x8a\x65\x52\xbd\xba\x15\xd8\xba\x96\xd6\x9e\x76\xd7\xb6\xad\x42\xf2\xea\xa8\xaa\xc1\x6a\x52\xbd\x3b\x5d";
unsigned char check5[] = "\x09\x1b\x6b\x92\x14\xda\x9f\xaf\x9b\x16\x06\x77\x5c\x53\xe2\xb0\x19\xbb\xe2\x77\x5c\x53\x25\x32\xa8\x53\xe2\x77\x5c\x94\xa7\x9b\x5d\x53\xe2\x77\x9b\x16\x1a\x77\x5c\x53\xe2\xb0\x19\xa3\xe2\x77\x5c\x53\x25\x32\xa0\x53\xe2\x77\x5c\x94\xa7\x87\xa3\xac\x1d\x88\xb7\x07\x69\x32\xb8\xde\xb2\x76\xd5\x06\x06\x3f\x3f\x83\xaa\xfc\x19\x8b\xaa\x76\x8c\x5c\x54\x77\x53\xed\x22\xfe\x19\xab\x69\x32\xa4\x62\xa7\x87\x9b\x16\x0a\x70\x5c\x53\xe2\x9c\x7f\xd8\xa7\x87\xdf\xb3\xe3\x80\x84\xda\xa7\x8b\xd7\x16\x12\xa6\xb4\xda\x20\xfc\x19\xaf\xc7\x57\xdf\xeb\x0f\x46\x8c\xda\xa7\x87\xdf\x3e\x0a\x76\xdf\x2e\x0a\x77\x25\x84\x69\x32\xb8\x1b\x81\xa7\x14\xd8\xa7\xaf\x14\x52\x32\x78\xea\x53\x66\xb7\x29\xcb\x63\x0a\xac\x7a\xe3\xee\x75\x27\xe5\xb0\x19\xbf\xe2\x77\x5c\x53\x69\x32\xb0\x0e\x21";
unsigned char test[] = "\x37\x29\x98\xcc\x2a\x50\xd1\x61\xa5\xa1\x26\x3a\x62\x61\x81\x74\xa1";
int keys[6] = {0x8EB5034A, 0xC6FFDA44, 0x85EA3FE1, 0x42AD9EF2, 0x77E2535C, 0x29116162};
int code_len[6] = {0x10b, 0x1b1, 0x2e4, 0x3e6, 0xbf, 0x11};
typedef struct decc {
unsigned char* code;
int key;
int sz;
}DECC;
int my_strlen(char *str) {
int ret = 0;
char *c = str;
while(*c != 0){
c++;
ret++;
}
return ret;
}
void my_strncpy(char *dst, char *src, int len) {
char *c = dst;
int i = 0;
for(i = 0 ; i < len ; i++) {
*c++ = *src++;
}
}
void clear(char *buf, int sz) {
int i = 0;
for(i = 0 ; i < sz ; i++) {
buf[i] = 0;
}
}
void fail() {
puts(":(");
exit(0);
}
char* dec(DECC dec_code, char *code) {
int sz = dec_code.sz;
int key = dec_code.key;
char key_buf[4] = {};
key_buf[0] = (char)(key&0xff);
key_buf[1] = (char)((key>>8)&0xff);
key_buf[2] = (char)((key>>16)&0xff);
key_buf[3] = (char)((key>>24)&0xff);
int i = 0;
for(i = 0 ; i < sz ; i++) {
code[i] = (char)((dec_code.code[i] ^ key_buf[i%4])&0xff);
}
}
void call_2(DECC dec_code, char* in, int sz) {
char code_buf[0x500] = {};
dec(dec_code, code_buf);
int (*fptr)(char*, int);
fptr = (int (*)(char*, int))code_buf;
int ok = (int)(*fptr)(in, sz);
if(!ok) fail();
}
void call_1(DECC dec_code, char* in) {
char code_buf[0x500] = {};
dec(dec_code, code_buf);
int (*fptr)(char*);
fptr = (int (*)(char*))code_buf;
int ok = (int)(*fptr)(in);
if(!ok) fail();
}
int call_0(DECC dec_code) {
char code_buf[0x500] = {};
dec(dec_code, code_buf);
int (*fptr)();
fptr = (int (*)())code_buf;
int ret = (int)(*fptr)();
return ret;
}
int main(int argc, char *argv[])
{
setvbuf(stdin, 0LL, 2, 0LL);
setvbuf(stdout, 0LL, 2, 0LL);
setvbuf(stderr, 0LL, 2, 0LL);
int i = 0;
DECC dec_code[6];
dec_code[0].code = test;
dec_code[1].code = check1;
dec_code[2].code = check2;
dec_code[3].code = check3;
dec_code[4].code = check4;
dec_code[5].code = check5;
for (i = 1; i < 6; i++) {
dec_code[i].key = keys[i-1];
dec_code[i].sz = code_len[i-1];
}
dec_code[0].key = keys[5];
dec_code[0].sz = code_len[5];
/* test */
int check_1337 = call_0(dec_code[0]);
if (check_1337 != 0x1337 ) {
puts("Test failed !");
return 1;
}
char flag[60]={};
char in[60]={};
char out[60]={};
char *c = flag;
printf("Please enter the flag: ");
read(0, flag, 55);
while(*c != 0) {
if (*c == '\n' || *c == '\r') {
*c = '\0';
break;
}
c++;
}
if(my_strlen(flag) != 52) fail();
/* check1(char*, int) */
my_strncpy(in, flag, 10);
call_2(dec_code[1], in, 10);
/* check2(char*) */
clear(in, 55);
my_strncpy(in, &flag[10], 8);
call_1(dec_code[2], in);
/* check3(char*, int) */
clear(in, 55);
my_strncpy(in, &flag[18], 18);
call_2(dec_code[3], in, 18);
/* check4(char*, int) */
clear(in, 55);
my_strncpy(in, &flag[36], 12);
call_2(dec_code[4], in, 12);
/* check5(char*) */
clear(in, 55);
my_strncpy(in, &flag[48], 4);
call_1(dec_code[5], in);
// passes all the check, print flag
printf("Congratz ! The flag is hitcon{%s} :)\n", flag);
return 0;
}
|
the_stack_data/3262640.c | #include <stddef.h>
wchar_t a() { return L'\u37D0'; }
|
the_stack_data/29959.c | /*
* linux/kernel/vsprintf.c
*
* (C) 1991 Linus Torvalds
*/
/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
/*
* Wirzenius wrote this portably, Torvalds fucked it up :-)
*/
#include <stdarg.h>
#include <string.h>
/* we use this so that we can do without the ctype library */
#define is_digit(c) ((c) >= '0' && (c) <= '9')
static int skip_atoi(const char **s) {
int i = 0;
while (is_digit(**s)) i = i * 10 + *((*s)++) - '0';
return i;
}
#define ZEROPAD 1 /* pad with zero */
#define SIGN 2 /* unsigned/signed long */
#define PLUS 4 /* show plus */
#define SPACE 8 /* space if plus */
#define LEFT 16 /* left justified */
#define SPECIAL 32 /* 0x */
#define SMALL 64 /* use 'abcdef' instead of 'ABCDEF' */
#define do_div(n, base) \
({ \
int __res; \
__asm__("divl %4" : "=a"(n), "=d"(__res) : "0"(n), "1"(0), "r"(base)); \
__res; \
})
static char *number(char *str, int num, int base, int size, int precision, int type) {
char c, sign, tmp[36];
const char *digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i;
if (type & SMALL)
digits = "0123456789abcdefghijklmnopqrstuvwxyz";
if (type & LEFT)
type &= ~ZEROPAD;
if (base < 2 || base > 36)
return 0;
c = (type & ZEROPAD) ? '0' : ' ';
if (type & SIGN && num < 0) {
sign = '-';
num = -num;
} else
sign = (type & PLUS) ? '+' : ((type & SPACE) ? ' ' : 0);
if (sign)
size--;
if (type & SPECIAL)
if (base == 16)
size -= 2;
else if (base == 8)
size--;
i = 0;
if (num == 0)
tmp[i++] = '0';
else
while (num != 0) tmp[i++] = digits[do_div(num, base)];
if (i > precision)
precision = i;
size -= precision;
if (!(type & (ZEROPAD + LEFT)))
while (size-- > 0) *str++ = ' ';
if (sign)
*str++ = sign;
if (type & SPECIAL)
if (base == 8)
*str++ = '0';
else if (base == 16) {
*str++ = '0';
*str++ = digits[33];
}
if (!(type & LEFT))
while (size-- > 0) *str++ = c;
while (i < precision--) *str++ = '0';
while (i-- > 0) *str++ = tmp[i];
while (size-- > 0) *str++ = ' ';
return str;
}
int vsprintf(char *buf, const char *fmt, va_list args) {
int len;
int i;
char *str;
char *s;
int *ip;
int flags; /* flags to number() */
int field_width; /* width of output field */
int precision; /* min. # of digits for integers; max
number of chars for from string */
int qualifier; /* 'h', 'l', or 'L' for integer fields */
for (str = buf; *fmt; ++fmt) {
if (*fmt != '%') {
*str++ = *fmt;
continue;
}
/* process flags */
flags = 0;
repeat:
++fmt; /* this also skips first '%' */
switch (*fmt) {
case '-':
flags |= LEFT;
goto repeat;
case '+':
flags |= PLUS;
goto repeat;
case ' ':
flags |= SPACE;
goto repeat;
case '#':
flags |= SPECIAL;
goto repeat;
case '0':
flags |= ZEROPAD;
goto repeat;
}
/* get field width */
field_width = -1;
if (is_digit(*fmt))
field_width = skip_atoi(&fmt);
else if (*fmt == '*') {
/* it's the next argument */
field_width = va_arg(args, int);
if (field_width < 0) {
field_width = -field_width;
flags |= LEFT;
}
}
/* get the precision */
precision = -1;
if (*fmt == '.') {
++fmt;
if (is_digit(*fmt))
precision = skip_atoi(&fmt);
else if (*fmt == '*') {
/* it's the next argument */
precision = va_arg(args, int);
}
if (precision < 0)
precision = 0;
}
/* get the conversion qualifier */
qualifier = -1;
if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') {
qualifier = *fmt;
++fmt;
}
switch (*fmt) {
case 'c':
if (!(flags & LEFT))
while (--field_width > 0) *str++ = ' ';
*str++ = (unsigned char)va_arg(args, int);
while (--field_width > 0) *str++ = ' ';
break;
case 's':
s = va_arg(args, char *);
len = strlen(s);
if (precision < 0)
precision = len;
else if (len > precision)
len = precision;
if (!(flags & LEFT))
while (len < field_width--) *str++ = ' ';
for (i = 0; i < len; ++i) *str++ = *s++;
while (len < field_width--) *str++ = ' ';
break;
case 'o':
str = number(str, va_arg(args, unsigned long), 8, field_width, precision, flags);
break;
case 'p':
if (field_width == -1) {
field_width = 8;
flags |= ZEROPAD;
}
str = number(str, (unsigned long)va_arg(args, void *), 16, field_width, precision, flags);
break;
case 'x':
flags |= SMALL;
case 'X':
str = number(str, va_arg(args, unsigned long), 16, field_width, precision, flags);
break;
case 'd':
case 'i':
flags |= SIGN;
case 'u':
str = number(str, va_arg(args, unsigned long), 10, field_width, precision, flags);
break;
case 'n':
ip = va_arg(args, int *);
*ip = (str - buf);
break;
default:
if (*fmt != '%')
*str++ = '%';
if (*fmt)
*str++ = *fmt;
else
--fmt;
break;
}
}
*str = '\0';
return str - buf;
}
int sprintf(char *buf, const char *fmt, ...) {
int ret;
va_list args;
if (!fmt)
return 0;
va_start(args, fmt);
ret = vsprintf(buf, fmt, args);
va_end(args);
return ret;
}
|
the_stack_data/76698956.c | //quartz2963_6801/_tests/_group_1/_test_7.c
//+1.0017E305 5 +1.2159E306 +1.6163E305 +1.7957E41 5 -1.6196E-307 +1.4187E-307 +1.8598E306 +1.7620E-307 +0.0 +0.0 -1.7235E-313 -1.6086E305 -1.9217E131
//
/* This is a automatically generated test. Do not modify */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void compute(double comp, int var_1,double var_2,double var_3,double var_4,int var_5,double var_6,double var_7,double var_8,double var_9,double var_10,double var_11,double var_12,double var_13,double var_14) {
if (comp > atan((+1.3559E305 - (var_2 + +1.6203E-306 * (var_3 * -1.5065E306 + var_4))))) {
for (int i=0; i < var_1; ++i) {
comp += +1.4047E305 + -1.8643E305 - -1.1787E-320 - (-0.0 / (-0.0 - var_6));
double tmp_1 = -1.4206E305;
comp = tmp_1 + (var_7 - (var_8 / -1.2937E306));
for (int i=0; i < var_5; ++i) {
comp = (var_9 - var_10 + var_11 + (-0.0 - var_12));
comp += -0.0 / fmod((var_13 - (+1.1617E-313 + -1.4168E-65 * (-1.0486E-320 + +1.6037E305))), (-1.5038E306 * var_14));
}
}
}
printf("%.17g\n", comp);
}
double* initPointer(double v) {
double *ret = (double*) malloc(sizeof(double)*10);
for(int i=0; i < 10; ++i)
ret[i] = v;
return ret;
}
int main(int argc, char** argv) {
/* Program variables */
double tmp_1 = atof(argv[1]);
int tmp_2 = atoi(argv[2]);
double tmp_3 = atof(argv[3]);
double tmp_4 = atof(argv[4]);
double tmp_5 = atof(argv[5]);
int tmp_6 = atoi(argv[6]);
double tmp_7 = atof(argv[7]);
double tmp_8 = atof(argv[8]);
double tmp_9 = atof(argv[9]);
double tmp_10 = atof(argv[10]);
double tmp_11 = atof(argv[11]);
double tmp_12 = atof(argv[12]);
double tmp_13 = atof(argv[13]);
double tmp_14 = atof(argv[14]);
double tmp_15 = atof(argv[15]);
compute(tmp_1,tmp_2,tmp_3,tmp_4,tmp_5,tmp_6,tmp_7,tmp_8,tmp_9,tmp_10,tmp_11,tmp_12,tmp_13,tmp_14,tmp_15);
return 0;
}
|
the_stack_data/9513627.c | #include <stdio.h>
typedef struct {
int x, y;
} CASO;
int main () {
CASO c;
int n, i, j, soma=0, tmp;
scanf("%d", &n);
for (i=0; i < n; i++) {
soma = 0;
scanf("%d %d", &c.x, &c.y);
if (c.x > c.y) {
tmp = c.x;
c.x = c.y;
c.y = tmp;
}
for (j=(c.x)+1; j < c.y; j++)
if (j % 2 != 0) soma += j;
printf("%d\n", soma);
}
return 0;
}
|
the_stack_data/40093.c | /*
foot_filter.c
(C) 2010 Ben Schmidt
This Source Code Form is subject to the terms of the Mozilla Public License
Version 2.0. If a copy of the MPL was not distributed with this file, You can
obtain one at http://mozilla.org/MPL/2.0/.
*/
// Check out the -V option; it outputs this and more
#define FOOT_FILTER_VERSION "foot_filter version 1.2, (C) 2010 Ben Schmidt"
static const char * USAGE="\n\
usage: foot_filter [-p plain_footer_file] [-h html_footer_file]\n\
[{-P|-H} mime_footer_file] [-s]\n\
foot_filter -V\n\
\n\
plain_footer_file, if present, will be appended to mails with plain text\n\
sections only. Similarly, html_footer_file. If mime_footer_file (either\n\
plain, -P, or HTML, -H) is given, it will be used when a mail with\n\
alternative formats is encountered, or if the footer for the relevant\n\
type of mail is not present; a new MIME section will be added.\n\
\n\
-s turns on smart mode which endeavours to remove included/quoted copies of\n\
the (or a similar) footer by surrounding the footer with patterns it later\n\
recognises. It also endeavours to strip 'padding' surrounding the old\n\
footers to make things as clean as possible. This includes whitespace\n\
(including ' ' and '<br>'), '>' quoting characters, various pairs of\n\
HTML tags (p, blockquote, div, span, font; it's naive, it doesn't check\n\
tags in between are balanced at all, so in '<p>prefix</p><p>suffix</p>' the\n\
first and last tags are paired), and even horizontal rules when inside\n\
paired tags (e.g. use '<div><hr/>footer</div>'). If the smart strings are\n\
found in the footer, they won't be added by the program, so you have the\n\
necessary control to do this.\n\
\n\
New footers are added prior to trailing whitespace and a few closing html\n\
tags (body, html) as well. You almost certainly want to begin your footer\n\
with an empty line because of this.\n\
\n\
Since these alterations, by their very nature, break signed mail,\n\
signatures are removed while processing. To keep some value from signatures,\n\
have the MTA verify them and add a header (or even supply an alternative\n\
footer to this program), and resign them to authenticate they came from the\n\
mailing list directly after the signature verification was done and recorded.\n\
Or don't use these kinds of transformations at all.\n\
\n\
-V shows the version and exits.\n\
\n\
Program is running now. Send EOF or interrupt to stop it. To avoid this usage\n\
message if wanting to run without arguments, use '--' as an argument.\n\
\n";
/*
This is a fairly simple program not expecting much extension. As such, some
liberties have been taken and some fun has been had by the author. Correctness
has been prioritised in design, but speed and efficiency have been taken into
consideration and prioritised above readability and modularity and other such
generally recommended programming practices. If making changes, great care
should be taken to understand how and where (everywhere) globals are used
before making them. Don't try to modify the program without understanding how
the whole thing works together or you will get burnt. You have been warned.
Relevant RFCs:
http://www.ietf.org/rfc/rfc2015.txt
http://www.ietf.org/rfc/rfc3851.txt
http://www.ietf.org/rfc/rfc2045.txt
http://www.ietf.org/rfc/rfc2046.txt
http://www.ietf.org/rfc/rfc822.txt
http://www.ietf.org/rfc/rfc2183.txt
For program configuration, see the 'constants' section below.
Also see code comments throughout.
Future possibilities:
- Saving copies of original mail in 'semi-temp' files for debugging.
- Stripping attachments and save them (e.g. in a location that can become a
'files uploaded' section on a website). Replace them with links to the
website, even.
- Making the prefixes, suffixes, replacements, padding, guts, pairs,
configurable at runtime.
- Attaching signed mail, or wrapping in a multipart rather than removing
signatures; wouldn't be hard if always using MIME footers.
- Following a script to allow various other header transformations (addition,
removal, etc.), or other transformations.
- Prologues as well as or instead of footers.
*/
/* tag: includes */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>
#include <sysexits.h>
/* tag: typedefs */
// splint has bools, but C doesn't!
#ifndef S_SPLINT_S
typedef int bool;
#define false (0)
#define true (1)
#endif
// This is mostly to be able to include splint annotations
typedef /*@null@*//*@observer@*/ const char * const_null_string;
typedef /*@null@*/ char * null_string;
typedef /*@null@*//*@owned@*/ char * owned_null_string;
typedef /*@null@*//*@dependent@*/ char * dependent_null_string;
// 'Callbacks'; they communicate primarily using globals, see below
typedef bool (*callback_t)();
typedef void (*function_t)();
// For fill()
typedef enum {
echo,
encode,
shunt,
discard,
stop,
fail
} when_full_t;
// Various places
typedef enum {
unencoded,
quoted_printable,
base64
} encoding_t;
// For returning multiple characters, and a request to delete backlog
// when decoding
typedef struct {
int r;
int c1;
int c2;
int c3;
} decode_t;
/* tag: constants */
/* tag: header_constants */
// How many MIME Content- headers we expect, maximum, in a mail. If we have
// more than that, we won't be able to process MIME so well, but we won't fail
// catastrophically.
#define mime_headers_max 16
/* tag: footer_constants */
// Stuff for processing the footer's smart removal and (smart or not)
// insertion
static const char * plain_prefix = "------~----------";
static const char * plain_suffix = "------~~---------";
static const char * plain_replacement = "\r\n\r\n";
static const_null_string plain_tails[] = {
" ","\t","\r","\n",
NULL
};
static const_null_string plain_padding[] = {
">"," ","\t","\r","\n",
NULL
};
static const_null_string plain_guts[] = {
NULL
};
static const_null_string plain_pairs[] = {
NULL
};
static const char * html_prefix = "------~----------";
static const char * html_suffix = "------~~---------";
static const char * html_replacement = "\r\n<br/><br/>\r\n";
static const_null_string html_tails[] = {
"</html>","</HTML>","</body>","</BODY>",
" "," ","&NBSP;","\t","\r","\n",
"<br>","<BR>","<br/>","<BR/>","<br />","<BR />",
NULL
};
static const_null_string html_padding[] = {
">",">",
" "," ","&NBSP;","\t","\r","\n",
"<br>","<BR>","<br/>","<BR/>","<br />","<BR />",
NULL
};
static const_null_string html_guts[] = {
// These are removed in an attempt to make a pair
"<hr>","<HR>","<hr/>","<HR/>","<hr />","<HR />",
" "," ","&NBSP;","\t","\r","\n",
"<br>","<BR>","<br/>","<BR/>","<br />","<BR />",
NULL
};
static const_null_string html_pairs[] = {
// Closing part (or NULL to mark no more), end of opening part,
// start of opening part, NULL
// The search strategy is fairly naive; if it finds the closing part,
// it checks for the end of the opening part; if it finds that, it
// searches back for the first character of each of the opening part
// variants, and if that character is found and is the beginning of the
// whole variant, it removes the pair.
"</p>",">","<p>","<p ",NULL,
"</P>",">","<P>","<P ",NULL,
"</blockquote>",">","<blockquote>","<blockquote ",NULL,
"</BLOCKQUOTE>",">","<BLOCKQUOTE>","<BLOCKQUOTE ",NULL,
"</div>",">","<div>","<div ",NULL,
"</DIV>",">","<DIV>","<DIV ",NULL,
"</span>",">","<span>","<span ",NULL,
"</SPAN>",">","<SPAN>","<SPAN ",NULL,
"</font>",">","<font>","<font ",NULL,
"</FONT>",">","<FONT>","<FONT ",NULL,
NULL
};
/* tag: buffer_constants */
// Also see comment at buffer_globals about how the buffer works.
// The buffer size limits how far back footers can be deleted; the
// section of mail from the closing boundary back this far will be
// searched for footers to remove.
#define mem_buffer_size 65536
// mem_buffer_keep is how much we keep in memory when shunting
// off to disk; as we must be able to shunt off at least something
// to disk each time we need to, this must be at least 2 bytes
// less than mem_buffer_size. This is how much we will be able to
// backtrack in memory, e.g. to strip whitespace. Something a little
// larger than the SMTP line length limit of 998 should keep it safe.
#define mem_buffer_keep 1024
// mem_buffer_margin is how much space we keep in memory in case
// a callback (decoding!) needs to use it. Must be at least 4 for
// decoding not to cause nasty corruption.
#define mem_buffer_margin 8
// The number of replacements we may wish to make; usually removing
// the MIME headers is the most complicated thing to be done, plus
// removing the MIME version header and the newline that ends the
// headers.
#define replacements_max (mime_headers_max+4)
/* tag: error_constants */
// Enable one or both of these
#define USE_SYSLOG
//#define USE_STDERR
/* tag: helper_constants */
// Disable this to use stdin/stdout with CRLF line endings as the spec
// and transports do; footer files are always expected to have UNIX line
// endings
#define UNIX_EOL
/* tag: globals */
/* tag: header_globals */
// Offsets into the buffer; only valid while it's still in there!
static int mime_header_starts[mime_headers_max]={0};
static int mime_header_ends[mime_headers_max]={0};
// String copies (until freed)
static owned_null_string saved_mime_headers[mime_headers_max]={NULL};
// Count applies to all header globals above
static int mime_headers_count = 0;
// Individual header strings which are processed to have comments
// removed and have normalised syntax for easy deduction of types,
// etc.. _header_body pointers point into the _header strings.
// Indexes are into the header arrays above.
// We store the version start and end separately as we want to delete it,
// but not reoutput it.
static /*@owned@*/ null_string version_header=NULL;
static /*@dependent@*/ null_string version_header_body=NULL;
static int version_header_start=0;
static int version_header_end=0;
static /*@owned@*/ null_string type_header=NULL;
static /*@dependent@*/ null_string type_header_body=NULL;
static int type_header_index=0;
static /*@owned@*/ null_string transfer_header=NULL;
static /*@dependent@*/ null_string transfer_header_body=NULL;
static int transfer_header_index=0;
static /*@owned@*/ null_string disposition_header=NULL;
static /*@dependent@*/ null_string disposition_header_body=NULL;
static int disposition_header_index=0;
// Flag that we had errors reading headers so not to do anything fancy
static bool mime_bad = false;
/* tag: footer_globals */
// Footer text; we just store \n but it is translated to CRLF
// The actual buffers
static /*@owned@*/ null_string plain_footer_buffer = NULL;
static /*@owned@*/ null_string html_footer_buffer = NULL;
static /*@owned@*/ null_string mime_footer_buffer = NULL;
// Pointer to the string we're actually using
static /*@dependent@*/ null_string plain_footer = NULL;
static /*@dependent@*/ null_string html_footer = NULL;
static /*@dependent@*/ null_string mime_footer = NULL;
static bool html_mime_footer = false;
// Whether to attempt deletion by surrounding the footer with special strings
static bool smart_footer = false;
/* tag: buffer_globals */
// We have a buffer that may be partly on disk (disk_buffer), then
// in memory (mem_buffer). The memory buffer wraps around as necessary.
// The disk buffer begins at disk_buffer_start in the file. The _filled
// variables say how much is in each part of the buffer, and the total
// is in buffer_filled. A portion of the buffer is considered to have
// been 'read'; before this is the lookbehind, and after this is the
// lookahead. The buffer may also be marked at a certain location,
// which is and should be almost always in the lookbehind (if in the
// lookahead this should only be very temporary).
static char mem_buffer_start[mem_buffer_size];
static char * mem_buffer_end = mem_buffer_start+mem_buffer_size;
static char * mem_buffer_next_empty = mem_buffer_start; // logical start
static char * mem_buffer_next_fill = mem_buffer_start; // logical end + 1
static int mem_buffer_filled=0;
static /*@null@*/ FILE * disk_buffer = NULL;
// Cannot pass mkstemp an unwritable string, so careful to declare this
// as an array, not a pointer which would observe the string constant.
static char disk_buffer_template[] = "foot_filter.XXXXXX";
static int disk_buffer_start=0; // offset into temp file for buffer
static int disk_buffer_filled=0;
// disk_buffer_sought: location we are at in the temp file
static int disk_buffer_sought=0;
// at all times, buffer_filled == mem_buffer_filled + disk_buffer_filled
static int buffer_filled=0;
static int buffer_read=0; // offset into buffer
static int buffer_mark=0; // offset into buffer; should be in lookbehind
static bool buffer_marked=false;
// The first and 'after last' characters to replace are stored
static int replacement_starts[replacements_max] = {0};
static int replacement_ends[replacements_max] = {0};
static const_null_string replacement_strings[replacements_max] = {NULL};
static int replacements_count=0;
/* tag: callback_globals */
// Used to communicate a character from the buffer to callbacks by the
// functions the callback is directly called by
static int buffer_char;
// Used to communicate information between callback functions and the
// functions that set up the callback (not the function that actually
// calls the callback), and possibly for internal callback state. The
// callbacks document how these should be used. Take special care to
// follow the instructions, or things will go bad and be hard to track
// down!
static /*@dependent@*/ null_string callback_save;
static const_null_string callback_compare;
static int callback_match;
static int callback_int;
static bool callback_bool;
/* tag: encoding_globals */
// Current modes
static encoding_t encoding;
static encoding_t decoding;
// State for the routines
static char encoding_buffer[4];
static int encoding_filled=0;
static int encoding_echoed=0;
static char decoding_buffer[4];
static int decoding_filled=0;
static int decoding_white=0;
/* tag: prototypes */
// Comments are made at function definitions where warranted.
/* tag: main_prototypes */
int main(int argc,char * argv[]);
static void load_footer(/*@out@*//*@shared@*/ char ** footer,
/*@reldef@*/ char ** footer_buffer,
char * file,
/*@unique@*/ const_null_string prefix,
/*@unique@*/ const_null_string suffix);
static void process_section(bool add_footer,
bool can_reenvelope, /*@null@*/ bool * parent_needs_footer);
/* tag: header_prototypes */
static inline void read_and_save_mime_headers();
static char * remove_comments(/*@returned@*/ char * header,bool ext);
static inline bool delimiting(char c,bool ext);
static inline void remove_mime_headers();
static inline void output_saved_mime_headers();
static void free_saved_mime_headers();
static bool /*@falsewhennull@*/ is_multipart(/*@null@*//*@out@*/ char ** boundary);
static inline bool is_signed();
static inline bool is_alternative();
static inline bool is_mixed();
static inline bool is_html();
static inline bool is_plain();
static inline bool is_signature();
static inline bool is_attachment();
static inline void set_decoding_type();
static inline void change_to_mixed();
static inline void generate_boundary(/*@out@*/ char ** boundary);
static inline void output_mime_mixed_headers(const char * boundary);
static inline void output_prolog();
static void output_mime_footer(const char * boundary);
static inline void output_boundary(const char * boundary);
static inline void output_final_boundary(const char * boundary);
static bool at_final_boundary(char * boundary);
/* tag: footer_prototypes */
static inline void process_text_section(bool add_footer,
/*@null@*/ const char * footer,
const char * prefix, const char * suffix, const char * replacement,
const_null_string * tails, const_null_string * padding,
const_null_string * guts, const_null_string * pairs,
char * boundary);
static inline void pad(const_null_string * padding,
const_null_string * guts, const_null_string * pairs,
int * prefix_pos, int * suffix_pos);
static inline void mark_tail(const_null_string * padding);
static inline void encode_footer(const char * footer);
/* tag: buffer_prototypes */
static inline void read_buffer();
static inline void echo_buffer();
static inline void skip_buffer();
static inline void echo_lookbehind();
static inline void encode_lookbehind();
static inline void encode_replacements();
static inline void make_replacements(callback_t one_char,
callback_t start_marked);
static inline void encode_to_mark();
static inline void echo_disk_buffer();
static inline void skip_disk_buffer();
static inline void read_boundary(/*@out@*/ char ** boundary);
static inline void echo_to_boundary(const char * boundary);
static inline void skip_to_boundary(const char * boundary);
static inline void decode_and_read_to_boundary_encoding_when_full(
const char * boundary);
static inline bool process_one_line_checking_boundary(callback_t n_chars,
/*@null@*/ function_t process, callback_t processing,
when_full_t when_full, const char * boundary);
static int pos_of(const char * text,int from,int to);
static bool look(callback_t callback,int from,bool read);
static bool lookback(callback_t callback,int from,bool mark);
static bool empty(callback_t callback);
static bool fill(callback_t callback, when_full_t when_full);
static inline void create_disk_buffer();
static void remove_disk_buffer();
static inline void shunt_to_disk(int n);
/* tag: callback_prototypes */
static bool one_char();
static bool echoing_one_char();
static bool encoding_one_char();
static bool n_chars();
static bool echoing_n_chars();
static bool encoding_n_chars();
static bool saving_n_chars();
static bool n_chars_until_match();
static bool until_eol();
// static bool echoing_until_eol();
static bool counting_until_eol();
static bool saving_until_eol();
static bool decoding_until_eol();
// static bool until_no_lookbehind();
static bool echoing_until_no_lookbehind();
static bool encoding_until_no_lookbehind();
static bool until_no_disk_buffer();
static bool echoing_until_no_disk_buffer();
static bool encoding_until_no_disk_buffer();
static bool until_no_buffer();
// static bool echoing_until_no_buffer();
static bool until_start_marked();
static bool echoing_until_start_marked();
static bool encoding_until_start_marked();
static bool until_match();
static bool comparing_head();
static bool case_insensitively_comparing_head();
/* tag: encoding_prototypes */
static inline void encode_string(const char * s);
static void encodechar(int c);
static inline void finish_encoding();
static /*@reldef@*/ decode_t decodechar(int c);
static void decode_lookahead();
static inline void finish_decoding();
static inline int decode_hex(int c);
static inline int decode_64(int c);
static inline void encode_hex_byte(unsigned int h);
static inline void encode_64(unsigned int b);
/* tag: error_prototypes */
static inline void * alloc_or_exit(size_t s) /*@allocates result@*/;
static inline void /*@noreturnwhentrue@*/
resort_to_exit(bool when,const char * message,int status);
static inline void /*@noreturnwhentrue@*/
resort_to_errno(bool when,const char * message,int status);
static inline void resort_to_warning(bool when,const char * message);
static inline void warning(const char * message);
/* tag: helper_prototypes */
static inline int get();
static inline int put(int c);
static inline int putstr(const char * s);
static inline bool case_insensitively_heads(const char * head,const char * buffer);
/* tag: functions */
/* tag: main_functions */
int main(int argc, char * argv[]) {
int opt;
bool show_version=false;
null_string plain_footer_file=NULL;
null_string html_footer_file=NULL;
null_string mime_footer_file=NULL;
// Initialise
resort_to_errno(atexit(remove_disk_buffer)!=0,
"cannot register exit function",EX_OSERR);
srandom((unsigned int)(getpid()*time(NULL)));
// Parse args
while ((opt=getopt(argc,argv,"p:h:P:H:sV"))!=-1) {
switch ((char)opt) {
case 'p': plain_footer_file=optarg; break;
case 'h': html_footer_file=optarg; break;
case 'P': mime_footer_file=optarg; html_mime_footer=false; break;
case 'H': mime_footer_file=optarg; html_mime_footer=true; break;
case 's': smart_footer=true; break;
case 'V': show_version=true; break;
default: warning("unrecognised commandline option");
}
}
if (show_version||argc<2) {
printf("%s\n",FOOT_FILTER_VERSION);
#ifdef UNIX_EOL
printf(" with UNIX line endings\n");
#else
printf(" with DOS line endings\n");
#endif
printf(" reporting errors to: ");
#ifdef USE_SYSLOG
printf("syslog ");
#endif
#ifdef USE_STDERR
printf("stderr ");
#endif
printf("\n");
if (argc<2) fprintf(stderr,"%s",USAGE);
if (show_version) exit(EX_OK);
}
argc-=optind;
argv+=optind;
resort_to_warning(argc>0,"unexpected commandline argument");
// Load footers
if (plain_footer_file!=NULL)
load_footer(&plain_footer,&plain_footer_buffer,
plain_footer_file,
smart_footer?plain_prefix:NULL,smart_footer?plain_suffix:NULL);
if (html_footer_file!=NULL)
load_footer(&html_footer,&html_footer_buffer,
html_footer_file,
smart_footer?html_prefix:NULL,smart_footer?html_suffix:NULL);
if (mime_footer_file!=NULL)
load_footer(&mime_footer,&mime_footer_buffer,
mime_footer_file,NULL,NULL);
// Do the job
process_section(true,true,NULL);
// Finish
if (plain_footer_buffer!=NULL) free(plain_footer_buffer);
if (html_footer_buffer!=NULL) free(html_footer_buffer);
if (mime_footer_buffer!=NULL) free(mime_footer_buffer);
exit(EX_OK);
}
static void load_footer(/*@out@*//*@shared@*/ char ** footer,
/*@reldef@*/ char ** footer_buffer,
char * file,
/*@unique@*/ const_null_string prefix,
/*@unique@*/ const_null_string suffix) {
FILE * f;
int prefixl=0, footerl=0, suffixl=0;
char * ff;
if (prefix!=NULL&&suffix!=NULL) {
prefixl=(int)strlen(prefix);
suffixl=(int)strlen(suffix);
}
f=fopen(file,"r");
resort_to_errno(f==NULL,"error opening footer file",EX_NOINPUT);
resort_to_errno(fseek(f,0,SEEK_END)!=0,
"error seeking end of footer file",EX_IOERR);
resort_to_errno((footerl=(int)ftell(f))==-1,
"error finding footer length",EX_IOERR);
resort_to_errno(fseek(f,0,SEEK_SET)!=0,
"error seeking in footer file",EX_IOERR);
// prefix, \n, footer, \n, suffix, \0
*footer_buffer=alloc_or_exit(sizeof(char)*(prefixl+footerl+suffixl+3));
*footer=*footer_buffer;
*footer+=prefixl+1;
resort_to_errno(fread(*footer,1,(size_t)footerl,f)<(size_t)footerl,
"error reading footer",EX_IOERR);
// We strip off a single trailing newline to keep them from accumulating
// but to allow the user the option of adding them if desired
if ((*footer)[footerl-1]=='\n') --footerl;
(*footer)[footerl]='\0';
if (prefix==NULL||suffix==NULL) return;
// Put in the prefix and suffix as necessary
ff=strstr(*footer,prefix);
if (ff!=NULL) {
ff=strstr(ff,suffix);
if (ff!=NULL) return;
(*footer)[footerl]='\n';
++footerl;
strcpy(*footer+footerl,suffix);
(*footer)[footerl+suffixl]='\0';
} else {
ff=strstr(*footer,suffix);
if (ff==NULL) {
(*footer)[footerl]='\n';
++footerl;
strcpy(*footer+footerl,suffix);
(*footer)[footerl+suffixl]='\0';
}
*footer-=prefixl+1;
strcpy(*footer,prefix);
(*footer)[prefixl]='\n';
}
}
// Should be called with the boundary for the section as lookahead
// in the buffer, but nothing more, and no lookbehind.
static void process_section(bool add_footer,
bool can_reenvelope, /*@null@*/ bool * parent_needs_footer) {
char * external=NULL;
char * internal=NULL;
char * generated=NULL;
bool reenveloping=false;
bool child_needed_footer=false;
bool needs_footer=false;
bool unsigning=false;
if (parent_needs_footer!=NULL) *parent_needs_footer=false;
// The headers must be read, saved and echoed before making any
// recursive calls, as I'm naughty and using globals.
read_boundary(&external);
read_and_save_mime_headers();
if (mime_bad) {
// If an error, just resort to echoing
echo_buffer(); // Boundary and headers
// End headers with the extra line break
resort_to_errno(putstr("\r\n")==EOF,
"error echoing string",EX_IOERR);
free_saved_mime_headers();
// Body
echo_to_boundary(external);
free(external);
return;
}
// Headers determining we skip this section
if (is_signature()) {
skip_buffer(); // Boundary and headers
skip_to_boundary(external);
return;
}
// Header processing
if (is_signed()) unsigning=true;
if (unsigning) change_to_mixed();
if (add_footer&&mime_footer!=NULL&&(
is_alternative()||(is_multipart(NULL)&&!is_mixed())||
(is_plain()&&plain_footer==NULL)||
(is_html()&&html_footer==NULL)
)) {
add_footer=false;
if (can_reenvelope) {
reenveloping=true;
remove_mime_headers();
} else if (parent_needs_footer!=NULL) *parent_needs_footer=true;
}
// Headers
echo_buffer(); // Boundary and possibly modified headers
if (reenveloping) {
generate_boundary(&generated);
output_mime_mixed_headers(generated);
output_prolog();
output_boundary(generated);
output_saved_mime_headers();
}
// End the headers with the extra line break
resort_to_errno(putstr("\r\n")==EOF,
"error echoing string",EX_IOERR);
// Body processing
if (is_multipart(&internal)) {
// This branch frees the MIME headers before recursing.
// Don't include the prolog if it used to be signed;
// it usually says something like 'this message is signed'
if (unsigning) {
skip_to_boundary(internal);
resort_to_errno(putstr("\r\n")==EOF,
"error echoing string",EX_IOERR);
} else {
echo_to_boundary(internal);
}
// The recursive call needs these globals
free_saved_mime_headers();
while (!at_final_boundary(internal)) {
process_section(add_footer,false,&child_needed_footer);
if (child_needed_footer) needs_footer=true;
}
if (needs_footer) output_mime_footer(internal);
free(internal);
echo_to_boundary(external);
} else {
// This branch frees the MIME headers at the end
if (!is_attachment()&&(
(is_plain()&&plain_footer!=NULL)||
(is_html()&&html_footer!=NULL))) {
// alternatively
// if (!is_attachment()&&(
// (is_plain()&&((add_footer&&plain_footer!=NULL)||smart_footer))||
// (is_html()&&((add_footer&&html_footer!=NULL)||smart_footer)))) {
if (is_plain()) {
process_text_section(add_footer,plain_footer,
plain_prefix,plain_suffix,plain_replacement,
plain_tails,plain_padding,plain_guts,plain_pairs,external);
} else {
process_text_section(add_footer,html_footer,
html_prefix,html_suffix,html_replacement,
html_tails,html_padding,html_guts,html_pairs,external);
}
} else {
echo_to_boundary(external);
}
free_saved_mime_headers();
}
// MIME stuff is freed now; take care not to use it.
/*@-branchstate@*/
if (reenveloping) {
// We ensure generated is not null in another if(reenveloping)
// conditional above
/*@-nullpass@*/
output_mime_footer(generated);
output_final_boundary(generated);
free(generated);
/*@=nullpass@*/
}
/*@=branchstate@*/
free(external);
}
/* tag: header_functions */
static inline void read_and_save_mime_headers() {
/*@-mustfreeonly@*/
mime_bad=false;
// Mark current end of buffer
buffer_mark=buffer_read;
buffer_marked=true;
for (;;) {
do {
// Extend current header until beginning of next
callback_bool=false;
(void)fill(until_eol,shunt);
if (buffer_filled==buffer_read) {
// We probably hit EOF; just get out, and the whole
// mail will end up echoed out
warning("unexpected end of input");
break;
}
(void)look(one_char,buffer_read,false);
if (callback_int==(int)' '||callback_int==(int)'\t') {
// Continuation of previous header; read it
read_buffer();
continue;
}
// Start of new header; don't read it; process the old one
// (from the mark to the end of the lookbehind)
break;
} while (true);
// Process the old header, if there is one
if (buffer_mark<buffer_read) {
do {
callback_compare="MIME-Version:";
(void)look(case_insensitively_comparing_head,buffer_mark,false);
if (callback_bool) {
// MIME version header
version_header_start=buffer_mark;
version_header_end=buffer_read;
version_header=alloc_or_exit(sizeof(char)*(buffer_read-buffer_mark+1));
callback_save=version_header;
callback_int=buffer_read-buffer_mark;
callback_save[callback_int]='\0';
(void)look(saving_n_chars,buffer_mark,false);
callback_save=NULL;
version_header_body=remove_comments(version_header,true);
if (!case_insensitively_heads("1.0",version_header_body)) {
mime_bad=true;
}
break;
}
callback_compare="Content-";
(void)look(case_insensitively_comparing_head,buffer_mark,false);
if (!callback_bool) break;
// Another MIME header
if (mime_headers_count==mime_headers_max) {
warning("too many MIME headers");
mime_bad=true;
break;
}
mime_header_starts[mime_headers_count]=buffer_mark;
mime_header_ends[mime_headers_count]=buffer_read;
saved_mime_headers[mime_headers_count]=
alloc_or_exit(sizeof(char)*(buffer_read-buffer_mark)+1);
saved_mime_headers[mime_headers_count][0]='\0';
callback_save=saved_mime_headers[mime_headers_count];
callback_int=buffer_read-buffer_mark;
callback_save[callback_int]='\0';
(void)look(saving_n_chars,buffer_mark,false);
callback_compare="Content-Type:";
(void)look(case_insensitively_comparing_head,buffer_mark,false);
if (callback_bool) {
type_header=alloc_or_exit(sizeof(char)*(buffer_read-buffer_mark+1));
strcpy(type_header,saved_mime_headers[mime_headers_count]);
type_header_body=remove_comments(type_header,true);
type_header_index=mime_headers_count;
++mime_headers_count;
break;
}
callback_compare="Content-Transfer-Encoding:";
(void)look(case_insensitively_comparing_head,buffer_mark,false);
if (callback_bool) {
transfer_header=alloc_or_exit(sizeof(char)*(buffer_read-buffer_mark+1));
strcpy(transfer_header,saved_mime_headers[mime_headers_count]);
transfer_header_body=remove_comments(transfer_header,true);
transfer_header_index=mime_headers_count;
++mime_headers_count;
break;
}
callback_compare="Content-Disposition:";
(void)look(case_insensitively_comparing_head,buffer_mark,false);
if (callback_bool) {
disposition_header=alloc_or_exit(sizeof(char)*(buffer_read-buffer_mark+1));
strcpy(disposition_header,saved_mime_headers[mime_headers_count]);
disposition_header_body=remove_comments(disposition_header,true);
disposition_header_index=mime_headers_count;
++mime_headers_count;
break;
}
++mime_headers_count;
} while (false);
}
// Mark the new header
buffer_mark=buffer_read;
if (buffer_read==buffer_filled) {
// EOF; return
return;
}
// Read the first part of the new header; loop to read rest
read_buffer();
callback_compare="\r\n";
(void)look(comparing_head,buffer_mark,false);
if (callback_bool) {
// End of headers; strip the extra line; return
resort_to_exit(replacements_count==replacements_max,
"internal error: too many replacements",EX_SOFTWARE);
replacement_starts[replacements_count]=buffer_read-2;
replacement_ends[replacements_count]=buffer_read;
replacement_strings[replacements_count]=NULL;
++replacements_count;
return;
}
}
/*@=mustfreeonly@*/
}
// Returns a pointer to the body part of the header field
static char * remove_comments(/*@returned@*/ char * header,bool ext) {
// This removes comments and any superfluous whitespace in the
// header (a structured header, that is, RFC822); it fiddles with
// the quoted strings in such a way that backslash escaping means
// simply take the next character literally, rather than needing
// to do funny things with folded strings. The result is not suitable
// for output.
char * h=header;
char * hh;
char * hhh;
char * body=NULL;
char close;
int levels=0;
while (*h!=':') ++h;
++h;
if (*h==' '||*h=='\t') ++h;
body=h;
hh=h;
while (*h!='\0') {
if (*h=='\r'&&*(h+1)=='\n') {
h+=2;
continue;
} else if ((*h==' '||*h=='\t')&&delimiting(*(hh-1),ext)) {
++h;
continue;
} else if (delimiting(*h,ext)&&(*(hh-1)==' '||*(hh-1)=='\t')) {
if (hh!=body) --hh;
}
if (*h=='(') {
++h;
levels=1;
while (levels>0) {
if (*h=='\0') break;
if (*h=='\\') {
++h;
if (*h=='\0') break;
}
else if (*h=='(') ++levels;
else if (*h==')') --levels;
++h;
}
if (!delimiting(*h,ext)&&!delimiting(*(hh-1),ext)) {
// Put in some whitespace if something delimiting isn't
// coming and hasn't just been
*hh=' ';
++hh;
}
continue;
} else if (*h=='"'||*h=='[') {
if (*h=='[') close=']';
else close='"';
*hh=*h;
++h; ++hh;
hhh=hh;
while (*h!='\0'&&*h!=close) {
if (*h=='\\') {
*hh=*h;
++hh; ++h;
if (*h=='\0') break;
if (*h=='\r'&&*(h+1)=='\n') {
*hh=*h; ++hh; ++h;
*hh=*h; ++hh; ++h;
if (*h=='\0') break;
++hh; ++h;
continue;
}
} else if (*h==(char)8) {
--hh; ++h;
if (hh<hhh) hh=hhh;
continue;
} else if (*h=='\r'&&*(h+1)=='\n') {
h+=2;
continue;
// alternatively
// *hh=*h; ++hh; ++h;
// *hh=*h; ++hh; ++h;
// if (*h=='\0') break;
// ++h;
// continue;
// or perhaps even (the spec is a bit ambiguous)
// h+=2;
// if (*h=='\0') break;
// ++h;
// continue;
}
*hh=*h;
++h; ++hh;
}
if (*h=='\0') break;
}
*hh=*h;
++h; ++hh;
}
if (*(hh-1)==' ') *(hh-1)='\0';
else *hh='\0';
return body;
}
static inline bool delimiting(char c,bool ext) {
// 'ext' (extended) delimiters include '/', '?' and '=' and assist
// by removing whitespace surrounding those, as these are
// delimiters in the MIME header fields, even though not RFC822;
// note that MIME doesn't use '.' but we still do.
return (c==' '||c=='\t'||c=='<'||c=='>'||c=='@'||
c==','||c==';'||c==':'||c=='\\'||c=='"'||
c=='.'||c=='['||c==']'||
(ext&&(c=='/'||c=='='||c=='?')));
}
static inline void remove_mime_headers() {
int h;
for (h=0;h<mime_headers_count;++h) {
resort_to_exit(replacements_count==replacements_max,
"internal error: too many replacements",EX_SOFTWARE);
replacement_starts[replacements_count]=mime_header_starts[h];
replacement_ends[replacements_count]=mime_header_ends[h];
replacement_strings[replacements_count]=NULL;
++replacements_count;
}
if (version_header!=NULL) {
resort_to_exit(replacements_count==replacements_max,
"internal error: too many replacements",EX_SOFTWARE);
replacement_starts[replacements_count]=version_header_start;
replacement_ends[replacements_count]=version_header_end;
replacement_strings[replacements_count]=NULL;
++replacements_count;
}
}
static inline void output_saved_mime_headers() {
int h;
for (h=0;h<mime_headers_count;++h) {
// The header includes its terminating CRLF
/*@-nullpass@*/
resort_to_errno(putstr(saved_mime_headers[h])==EOF,
"error echoing string",EX_IOERR);
/*@=nullpass@*/
}
}
static void free_saved_mime_headers() {
int h;
for (h=0;h<mime_headers_count;++h) {
/*@-nullpass@*/
free(saved_mime_headers[h]);
/*@=nullpass@*/
}
mime_headers_count=0;
if (version_header!=NULL) free(version_header);
version_header=NULL;
version_header_body=NULL;
if (type_header!=NULL) free(type_header);
type_header=NULL;
type_header_body=NULL;
if (transfer_header!=NULL) free(transfer_header);
transfer_header=NULL;
transfer_header_body=NULL;
if (disposition_header!=NULL) free(disposition_header);
disposition_header=NULL;
disposition_header_body=NULL;
}
static bool /*@falsewhennull@*/ is_multipart(/*@null@*//*@out@*/ char ** boundary) {
char * b;
/*@dependent@*/ char * bb;
int l=0;
if (type_header_body==NULL||
!case_insensitively_heads("multipart/",type_header_body)) {
if (boundary!=NULL) *boundary=NULL;
return false;
}
b=type_header_body+10;
for (;;) {
while (*b!='\0'&&*b!=';') ++b;
if (*b=='\0') {
warning("no boundary given");
if (boundary!=NULL) *boundary=NULL;
return false;
}
++b;
if (case_insensitively_heads("boundary=",b)) break;
}
b+=9;
if (*b=='"') {
for (bb=b+1;*bb!='\0'&&*bb!='"';++bb) {
if (*bb=='\\') {
++bb;
if (*bb=='\0') break;
}
++l;
}
if (*bb=='\0') {
warning("error in boundary syntax");
if (boundary!=NULL) *boundary=NULL;
return false;
}
} else {
// MIME tokens can include '.'
for (bb=b;*bb!='\0'&&(!delimiting(*bb,true)||*bb=='.');++bb) ++l;
}
/*@-mustdefine@*/
if (boundary==NULL) return true;
/*@=mustdefine@*/
// Room for leading and trailing '--', and terminator
*boundary=alloc_or_exit(sizeof(char)*(l+5));
bb=*boundary;
*bb++='-';
*bb++='-';
if (*b=='"') {
++b;
while (*b!='\0'&&*b!='"') {
if (*b=='\\') ++b;
*bb++=*b++;
}
} else {
// MIME tokens can include '.'
while (*b!='\0'&&(!delimiting(*b,true)||*b=='.')) *bb++=*b++;
}
*bb='\0';
return true;
}
static inline bool is_signed() {
return type_header_body!=NULL&&
case_insensitively_heads("multipart/signed",type_header_body);
}
static inline bool is_alternative() {
return type_header_body!=NULL&&
case_insensitively_heads("multipart/alternative",type_header_body);
}
static inline bool is_mixed() {
return type_header_body!=NULL&&
case_insensitively_heads("multipart/mixed",type_header_body);
}
static inline bool is_html() {
return type_header_body!=NULL&&
case_insensitively_heads("text/html",type_header_body);
}
static inline bool is_plain() {
return type_header_body==NULL||
case_insensitively_heads("text/plain",type_header_body);
}
static inline bool is_signature() {
return type_header_body!=NULL&&(
case_insensitively_heads("application/x-pkcs7-signature",
type_header_body)||
case_insensitively_heads("application/pgp-signature",
type_header_body));
}
static inline bool is_attachment() {
return disposition_header_body!=NULL&&
case_insensitively_heads("attachment",disposition_header_body);
}
static inline void set_decoding_type() {
if (transfer_header_body==NULL) {
decoding=unencoded;
return;
}
if (case_insensitively_heads("quoted-printable",transfer_header_body)) {
decoding=quoted_printable;
return;
}
if (case_insensitively_heads("base64",transfer_header_body)) {
decoding=base64;
return;
}
decoding=unencoded;
if (case_insensitively_heads("7bit",transfer_header_body)) return;
if (case_insensitively_heads("8bit",transfer_header_body)) return;
if (case_insensitively_heads("binary",transfer_header_body)) return;
warning("unrecognised transfer encoding");
}
static inline void change_to_mixed() {
char * boundary=NULL;
char * header;
char * b, * h;
int l=0;
if (!is_multipart(&boundary)) {
warning("internal error: changing non-multipart to mixed");
return;
}
boundary+=2;
// The special cases should never happen, as '\', '"', '\r' and '\n'
// aren't allowed in boundaries...but...just in case...
for (b=boundary;*b!='\0';++b) {
if (*b=='\r'||*b=='\n') {
warning("boundary with newline");
return;
}
if (*b=='"'||*b=='\\') ++l;
++l;
}
header=alloc_or_exit(sizeof(char)*(50+l)); // Play it safe
strcpy(header,"Content-Type: multipart/mixed;\r\n boundary=\"");
for (h=header+43,b=boundary;*b!='\0';++h,++b) {
if (*b=='"'||*b=='\\') { *h='\\'; ++h; }
*h=*b;
}
*h++='"'; *h++='\r'; *h++='\n'; *h++='\0';
free(boundary-2);
/*@-nullpass@*/
free(saved_mime_headers[type_header_index]);
/*@=nullpass@*/
saved_mime_headers[type_header_index]=header;
resort_to_exit(replacements_count==replacements_max,
"internal error: too many replacements",EX_SOFTWARE);
replacement_starts[replacements_count]=
mime_header_starts[type_header_index];
replacement_ends[replacements_count]=
mime_header_ends[type_header_index];
replacement_strings[replacements_count]=
saved_mime_headers[type_header_index];
++replacements_count;
}
static inline void generate_boundary(/*@out@*/ char ** boundary) {
int r;
*boundary=alloc_or_exit(sizeof(char)*42); // Life, the universe and everything
strcpy(*boundary,"--=_foot_filter_boundary_0123456789012_=");
for (r=25;r<38;++r) {
(*boundary)[r]=(char)((int)'A'+(random()%16));
}
}
static inline void output_mime_mixed_headers(const char * boundary) {
resort_to_errno(
putstr("MIME-Version: 1.0\r\n")==EOF,
"error echoing string",EX_IOERR);
resort_to_errno(
putstr("Content-Type: multipart/mixed;\r\n boundary=\"")==EOF,
"error echoing string",EX_IOERR);
resort_to_errno(putstr(boundary+2)==EOF,
"error echoing string",EX_IOERR);
// I put an extra CRLF just in case some mail reader expects the
// initial boundary to include one that is separate from the one that
// ends the headers.
resort_to_errno(
putstr("\"\r\n\r\n\r\n")==EOF,
"error echoing string",EX_IOERR);
}
static inline void output_prolog() {
// Deliberately empty; we don't need any prolog
}
static void output_mime_footer(const char * boundary) {
output_boundary(boundary);
if (html_mime_footer) {
resort_to_errno(
putstr("Content-Type: text/html; charset=UTF-8\r\n")==EOF,
"error echoing string",EX_IOERR);
} else {
resort_to_errno(
putstr("Content-Type: text/plain; charset=UTF-8\r\n")==EOF,
"error echoing string",EX_IOERR);
}
resort_to_errno(
putstr("Content-Transfer-Encoding: quoted-printable\r\n")==EOF,
"error echoing string",EX_IOERR);
encoding=quoted_printable;
resort_to_errno(putstr("\r\n")==EOF,
"error echoing string",EX_IOERR);
/*@-nullpass@*/
encode_footer(mime_footer);
/*@=nullpass@*/
encodechar((int)'\r');
encodechar((int)'\n');
finish_encoding();
// This is logically part of the boundary that is about to come
resort_to_errno(putstr("\r\n")==EOF,
"error echoing string",EX_IOERR);
}
static inline void output_boundary(const char * boundary) {
resort_to_errno(putstr(boundary)==EOF,"error echoing string",EX_IOERR);
resort_to_errno(putstr("\r\n")==EOF,"error echoing string",EX_IOERR);
}
static inline void output_final_boundary(const char * boundary) {
resort_to_errno(putstr(boundary)==EOF,"error echoing string",EX_IOERR);
resort_to_errno(putstr("--\r\n")==EOF,"error echoing string",EX_IOERR);
}
static bool at_final_boundary(char * boundary) {
int l;
// If no lookahead, we probably hit EOF, so we primarily just need to get
// out of loops and exit
if (buffer_filled-buffer_read==0) {
warning("probably unexpected end of input");
return true;
}
l=(int)strlen(boundary);
boundary[l]='-';
boundary[l+1]='-';
boundary[l+2]='\0';
/*@-temptrans@*/
callback_compare=boundary;
/*@=temptrans@*/
(void)look(comparing_head,buffer_read,false);
callback_compare=NULL;
boundary[l]='\0';
return callback_bool;
}
/* tag: footer_functions */
static inline void process_text_section(bool add_footer,
/*@null@*/ const char * footer,
const char * prefix, const char * suffix, const char * replacement,
const_null_string * tails, const_null_string * padding,
const_null_string * guts, const_null_string * pairs,
char * boundary) {
int prefix_pos;
int later_prefix_pos;
int suffix_pos;
bool removed_footers=false;
bool removed_newline=false;
bool boundary_newline=false;
int prefixl=(int)strlen(prefix);
int suffixl=(int)strlen(suffix);
resort_to_exit(buffer_filled>0,
"internal error: unexpected data in buffer",EX_SOFTWARE);
set_decoding_type();
encoding=decoding;
decode_and_read_to_boundary_encoding_when_full(boundary);
if (smart_footer&&footer!=NULL) {
// alternatively
// if (smart_footer) {
for (;;) {
prefix_pos=pos_of(prefix,0,buffer_read);
if (prefix_pos==EOF) break;
suffix_pos=pos_of(suffix,prefix_pos,buffer_read);
if (suffix_pos==EOF) break;
for (;;) {
later_prefix_pos=
pos_of(prefix,prefix_pos+prefixl,suffix_pos-prefixl);
if (later_prefix_pos!=EOF) prefix_pos=later_prefix_pos;
else break;
}
suffix_pos+=suffixl;
pad(padding,guts,pairs,&prefix_pos,&suffix_pos);
replacement_starts[replacements_count]=prefix_pos;
replacement_ends[replacements_count]=suffix_pos;
// We may not want the last replacement so replace
// with nothing first
replacement_strings[replacements_count]=NULL;
++replacements_count;
// We want the last replacement; encode it now before
// doing any more encoding
if (removed_footers) encode_string(replacement);
encode_replacements();
removed_footers=true;
}
}
if (*boundary!='\0'&&(decoding==quoted_printable||decoding==unencoded)) {
// If we're not using base64 encoding, and we're in multipart, there
// will be a final CRLF that is part of the input but logically part of
// the boundary, not the text. Removing the footer may have already
// removed it, so we need to check if it's here or not.
if (buffer_read>1) {
callback_compare="\r\n";
(void)look(comparing_head,buffer_read-2,false);
callback_compare=NULL;
if (callback_bool) boundary_newline=true;
}
}
if (add_footer&&footer!=NULL) {
// This will skip past the boundary newline
mark_tail(tails);
if (removed_footers&&buffer_mark==0) {
// The last replacement coincides with where the footer
// is going to go; don't use the replacement text.
removed_footers=false;
}
}
if (removed_footers) encode_string(replacement);
if (add_footer&&footer!=NULL) {
if (buffer_mark<buffer_read-2||
(buffer_mark==buffer_read-2&&!boundary_newline)) {
// If we tailed back past a newline (that wasn't the boundary
// newline which isn't really there) we don't bother appending
// a new one to the footer
callback_compare="\r\n";
(void)look(comparing_head,buffer_mark,false);
if (callback_bool) removed_newline=true;
}
encode_to_mark();
encodechar((int)'\r');
encodechar((int)'\n');
encode_footer(footer);
if (!removed_newline) {
encodechar((int)'\r');
encodechar((int)'\n');
}
}
if (boundary_newline) {
// Actually remove the boundary newline now
if (replacements_count==replacements_max) {
warning("internal error: too many replacements");
} else {
replacement_starts[replacements_count]=buffer_read-2;
replacement_ends[replacements_count]=buffer_read;
replacement_strings[replacements_count]=NULL;
++replacements_count;
}
}
encode_lookbehind();
finish_encoding();
if (*boundary!='\0') {
// This is logically part of the boundary
resort_to_errno(putstr("\r\n")==EOF,"error echoing string",EX_IOERR);
}
}
static inline void pad(const_null_string * padding,
const_null_string * guts, const_null_string * pairs,
int * prefix_pos, int * suffix_pos) {
const char ** run;
const char ** test;
const char ** opening;
const char ** closing;
int saved_prefix_pos;
int definite_prefix_pos;
int definite_suffix_pos;
bool pair_succeeded;
bool pad_succeeded;
// Could generate lengths at init time for speed
int l;
int ll;
// If we succeed for one thing, we try it again straight away,
// as a number of types of padding are likely to occur in multiples.
// Then we keep trying the whole lot until nothing is left to do.
do {
// Try each piece of padding (or guts)
definite_prefix_pos=EOF;
definite_suffix_pos=EOF;
run=padding;
do {
do {
pad_succeeded=false;
test=run;
while (*test!=NULL) {
l=(int)strlen(*test);
for (;;) {
// Check for padding at tail
if (buffer_filled-*suffix_pos<l) break;
callback_compare=*test;
(void)look(comparing_head,*suffix_pos,false);
if (!callback_bool) break;
*suffix_pos+=l;
pad_succeeded=true;
}
for (;;) {
// Check for padding at head
if (*prefix_pos-l<0) break;
callback_compare=*test;
(void)look(comparing_head,*prefix_pos-l,false);
if (!callback_bool) break;
*prefix_pos-=l;
pad_succeeded=true;
}
++test;
}
} while (pad_succeeded);
if (definite_prefix_pos==EOF) {
// Do a second run to deal with guts in a more tentative way
definite_prefix_pos=*prefix_pos;
definite_suffix_pos=*suffix_pos;
run=guts;
} else break;
} while (true);
// Try each pair
pair_succeeded=false;
closing=pairs;
while (*closing!=NULL) {
l=(int)strlen(*closing);
opening=closing+1;
// This loop is just to be broken out of; we don't try
// pairs twice when they succeed as they aren't too likely
// to nest.
do {
// Check for closing part
if (buffer_filled-*suffix_pos<l) break;
callback_compare=*closing;
(void)look(comparing_head,*suffix_pos,false);
if (!callback_bool) break;
// Check for end of opening part
ll=(int)strlen(*opening);
if (*prefix_pos-ll<0) break;
callback_compare=*opening;
(void)look(comparing_head,*prefix_pos-ll,false);
if (!callback_bool) break;
saved_prefix_pos=*prefix_pos;
// Try each variant
for (++opening;*opening!=NULL;
*prefix_pos=saved_prefix_pos,++opening) {
// Search back for first character
ll=(int)strlen(*opening);
if (*prefix_pos-ll<0) continue;
*prefix_pos-=ll;
callback_match=(int)**opening;
if (lookback(until_match,*prefix_pos,true)) {
// Check if this is the variant
callback_compare=*opening;
(void)look(comparing_head,*prefix_pos,false);
if (!callback_bool) continue;
*suffix_pos+=l;
pair_succeeded=true;
break;
}
}
} while (false);
// Skip all the variants if not skipped already
while (*opening!=NULL) ++opening;
closing=opening+1;
}
if (!pair_succeeded) {
// If the pair didn't succeed, we don't remove the guts
*prefix_pos=definite_prefix_pos;
*suffix_pos=definite_suffix_pos;
}
} while (pair_succeeded);
}
static inline void mark_tail(const_null_string * padding) {
// This is basically pad() with deletions, but adding the two lines
// at the start to initially place the mark. Comments at pad() apply.
bool something_changed;
const char ** test;
int l;
buffer_mark=buffer_read;
buffer_marked=true;
do {
something_changed=false;
// Try each piece of padding
test=padding;
while (*test!=NULL) {
l=(int)strlen(*test);
for (;;) {
// Check for padding at head
if (buffer_mark-l<0) break;
callback_compare=*test;
(void)look(comparing_head,buffer_mark-l,false);
if (!callback_bool) break;
buffer_mark-=l;
something_changed=true;
}
++test;
}
} while (something_changed);
}
static inline void encode_footer(const char * footer) {
while (*footer!='\0') {
if (*footer=='\n') encodechar((int)'\r');
encodechar((int)(unsigned int)*footer);
footer++;
}
}
/* tag: buffer_functions */
// The first few of these handle replacements, the rest not.
static inline void read_buffer() {
buffer_read=buffer_filled;
}
static inline void echo_buffer() {
read_buffer();
echo_lookbehind();
}
static inline void skip_buffer() {
if (buffer_filled>0) (void)empty(until_no_buffer);
}
static inline void echo_lookbehind() {
make_replacements(echoing_one_char,echoing_until_start_marked);
if (buffer_read>0) (void)empty(echoing_until_no_lookbehind);
}
static inline void encode_lookbehind() {
make_replacements(encoding_one_char,encoding_until_start_marked);
if (buffer_read>0) (void)empty(encoding_until_no_lookbehind);
}
static inline void encode_replacements() {
make_replacements(encoding_one_char,encoding_until_start_marked);
}
static inline void make_replacements(callback_t one_char,
callback_t start_marked) {
int r, minr=0;
const char * c;
if (buffer_read==0) return;
buffer_marked=false;
while (replacements_count>0) {
for (r=0;r<replacements_count;++r) {
if (!buffer_marked||replacement_starts[r]<buffer_mark) {
buffer_marked=true;
minr=r;
buffer_mark=replacement_starts[r];
}
}
for (r=0;r<replacements_count;++r) {
replacement_starts[r]-=buffer_mark;
replacement_ends[r]-=buffer_mark;
}
if (buffer_mark>0) (void)empty(start_marked);
c = replacement_strings[minr];
if (c!=NULL) {
while (*c!='\0') {
buffer_char=(int)(unsigned int)*c;
(void)(*one_char)();
++c;
}
}
buffer_marked=true;
buffer_mark=replacement_ends[minr];
for (r=0;r<replacements_count;++r) {
replacement_starts[r]-=buffer_mark;
replacement_ends[r]-=buffer_mark;
}
if (buffer_mark>0) (void)empty(until_start_marked);
for (r=minr;r<replacements_count-1;++r) {
replacement_starts[r]=replacement_starts[r+1];
replacement_ends[r]=replacement_ends[r+1];
replacement_strings[r]=replacement_strings[r+1];
}
--replacements_count;
buffer_marked=false;
}
}
static inline void encode_to_mark() {
if (buffer_mark>0) (void)empty(encoding_until_start_marked);
}
static inline void echo_disk_buffer() {
if (disk_buffer_filled>0) (void)empty(echoing_until_no_disk_buffer);
}
static inline void encode_disk_buffer() {
if (disk_buffer_filled>0) (void)empty(encoding_until_no_disk_buffer);
}
static inline void skip_disk_buffer() {
if (disk_buffer_filled>0) (void)empty(until_no_disk_buffer);
}
static inline void read_boundary(/*@out@*/ char ** boundary) {
int l=0;
if (buffer_filled>buffer_read) {
callback_bool=false;
callback_int=0;
resort_to_exit(!look(counting_until_eol,buffer_read,false),
"internal error: missing eol at section boundary",EX_SOFTWARE);
l=callback_int-2; // remove the CRLF, but keep the leading '--'
}
// Leave room to append a trailing '--' for testing final boundary;
// the CRLF will be written in this space by saving_until_eol too.
*boundary = alloc_or_exit(sizeof(char)*(l+3));
if (buffer_filled>buffer_read) {
callback_bool=false;
callback_save=*boundary;
(void)look(saving_until_eol,buffer_read,false);
callback_save=NULL;
}
(*boundary)[l]='\0';
if (buffer_filled>buffer_read) {
callback_bool=false;
(void)look(until_eol,buffer_read,true);
}
}
static inline void echo_to_boundary(const char * boundary) {
do {
echo_buffer();
} while (!process_one_line_checking_boundary(
echoing_n_chars,NULL,until_eol,echo,boundary));
}
static inline void skip_to_boundary(const char * boundary) {
do {
skip_buffer();
} while (!process_one_line_checking_boundary(
n_chars,NULL,until_eol,discard,boundary));
}
static inline void decode_and_read_to_boundary_encoding_when_full(
const char * boundary) {
do {
read_buffer();
} while (!process_one_line_checking_boundary(
encoding_n_chars,decode_lookahead,
decoding_until_eol,encode,boundary));
finish_decoding(); // This just sets state, doesn't change data
}
static inline bool process_one_line_checking_boundary(callback_t n_chars,
/*@null@*/ function_t process, callback_t processing,
when_full_t when_full, const char * boundary) {
bool stopped_by_design;
if (feof(stdin)!=0) {
// We're done! Call it a boundary (even if it isn't--we need to
// get out of loops cleanly and tidy up as best we can).
return true;
}
// Empty until enough space for boundary
if (mem_buffer_size-mem_buffer_filled<80) {
callback_int=80-(mem_buffer_size-mem_buffer_filled);
(void)empty(n_chars);
}
callback_bool=false;
stopped_by_design=fill(until_eol,stop);
if (stopped_by_design||feof(stdin)!=0) {
if (buffer_filled-buffer_read==0) {
return *boundary=='\0';
}
callback_bool=false;
if (*boundary!='\0') {
// Can only be at a boundary without being at EOF if there
// really is a boundary
/*@-temptrans@*/
callback_compare=boundary;
/*@=temptrans@*/
(void)look(comparing_head,buffer_read,false);
callback_compare=NULL;
}
if (!callback_bool&&process!=NULL) (*process)();
return callback_bool;
} else {
// Line is too long to be a boundary, so must be decoded
if (process!=NULL) (*process)();
callback_bool=false;
(void)fill(processing,when_full);
return false;
}
}
// Return the position of text whose start may occur in the buffer
// anywhere between from and (just before) to. Use EOF for from to
// go from current location; use EOF for to to read indefinitely;
// EOF is returned if text is not found.
static int pos_of(const char * text,int from,int to) {
int saved_buffer_read;
int pos=EOF;
if (*text=='\0') return from;
saved_buffer_read=buffer_read;
if (from!=EOF) buffer_read=from;
callback_match=(int)(unsigned int)*text;
for (;;) {
if (to!=EOF) {
callback_int=to-buffer_read;
if (!look(n_chars_until_match,buffer_read,true)) break;
} else {
if (!look(until_match,buffer_read,true)) break;
}
if (!callback_bool) break;
/*@-temptrans@*/
callback_compare=text+1;
/*@=temptrans@*/
(void)look(comparing_head,buffer_read,false);
callback_compare=NULL;
if (callback_bool) {
// Include the first character
pos=buffer_read-1;
break;
}
}
buffer_read=saved_buffer_read;
return pos;
}
// Look at characters in the buffer, starting at offset from,
// 'reading' if so indicated (and looking at that location).
// The callback is called after updating the reading pointer
// and placing the character in the buffer. The character is
// also passed by means of the buffer_char global.
// EOF is sent to the callback when we run out of data.
// There is no automatic attempt to fill the buffer.
// The callback should return a boolean indicating whether
// to continue. This function will return true if the callback
// indicated to stop (including if it so indicated on EOF), or
// false if it stopped for EOF.
// We always call the callback at least once, so don't call
// this function at all unless you definitely want to look
// at something.
static bool look(callback_t callback,int from,bool read) {
int pos=from;
int disk_buffer_pos;
char * mem_buffer_pos;
if (pos<disk_buffer_filled) {
disk_buffer_pos=disk_buffer_start+pos;
if (disk_buffer_sought!=disk_buffer_pos) {
/*@-nullpass@*/
resort_to_errno(fseek(disk_buffer,disk_buffer_pos,SEEK_SET)!=0,
"error seeking in temporary file",EX_IOERR);
/*@=nullpass@*/
disk_buffer_sought=disk_buffer_pos;
}
while (pos<disk_buffer_filled) {
/*@-nullpass@*/
buffer_char=getc(disk_buffer);
/*@=nullpass@*/
resort_to_errno(buffer_char==EOF,
"error reading temporary file",EX_IOERR);
// ++disk_buffer_pos; logically this happens, but it is unnecessary
++disk_buffer_sought;
if (read&&pos==buffer_read) ++buffer_read;
++pos;
if (!(*callback)()) return true;
}
}
if (pos<buffer_filled) {
mem_buffer_pos=mem_buffer_next_empty+(pos-disk_buffer_filled);
if (mem_buffer_pos>=mem_buffer_end) mem_buffer_pos-=mem_buffer_size;
while (pos<buffer_filled) {
buffer_char=(int)(unsigned int)*mem_buffer_pos;
++mem_buffer_pos;
if (mem_buffer_pos==mem_buffer_end) mem_buffer_pos=mem_buffer_start;
if (read&&pos==buffer_read) ++buffer_read;
++pos;
if (!(*callback)()) return true;
}
}
buffer_char=EOF;
if (!(*callback)()) return true;
return false;
}
// Does the same backwards, moving the mark if so indicated (and
// looking at that location). The callback is called before the
// mark is moved, though, and if it returns false, the mark is
// not moved, but the function returns true immediately.
// There is no call to the callback with EOF when we get to the
// start of the buffer, so the function always returns false in
// that case, and unmarks the buffer. Again, the callback is
// always called at least once.
static bool lookback(callback_t callback,int from,bool mark) {
int pos=from;
int disk_buffer_pos;
char * mem_buffer_pos;
if (pos>=disk_buffer_filled) {
mem_buffer_pos=mem_buffer_next_empty+(pos-disk_buffer_filled);
if (mem_buffer_pos>=mem_buffer_end) mem_buffer_pos-=mem_buffer_size;
while (pos>=disk_buffer_filled) {
buffer_char=(int)(unsigned int)*mem_buffer_pos;
if (!(*callback)()) return true;
--mem_buffer_pos;
if (mem_buffer_pos==mem_buffer_start-1)
mem_buffer_pos=mem_buffer_end-1;
if (mark&&pos==buffer_mark) --buffer_mark;
--pos;
}
}
if (pos>=0&&disk_buffer_filled>0) {
disk_buffer_pos=disk_buffer_start+pos;
// Reading backwards in the disk buffer is potentially very nasty;
// hopefully it never actually happens
while (pos>=0) {
/*@-nullpass@*/
resort_to_errno(fseek(disk_buffer,disk_buffer_pos,SEEK_SET)!=0,
"error seeking in temporary file",EX_IOERR);
disk_buffer_sought=disk_buffer_pos;
buffer_char=getc(disk_buffer);
/*@=nullpass@*/
resort_to_errno(buffer_char==EOF,
"error reading temporary file",EX_IOERR);
++disk_buffer_sought;
if (!(*callback)()) return true;
--disk_buffer_pos;
if (mark&&pos==buffer_mark) --buffer_mark;
--pos;
}
}
if (mark&&buffer_mark==-1) {
buffer_mark=0;
buffer_marked=false;
}
// We don't call the callback on EOF when going backwards
// buffer_char=EOF;
// (void)(*callback)();
return false;
}
// Remove characters from the (beginning of the) buffer. The same
// general principles as for look() apply. The callback is called
// after the character is removed and all accounting has been done, so
// perhaps the only place you can reliably find the character is in
// the buffer_char global. Again the callback gets an EOF call if
// there's nothing more to empty, and no automatic filling is done.
// The callback and function return values are as for look() and
// again, the callback is always called at least once; this means at
// least one character is always removed from the buffer, so only call
// the function if something definitely should be removed.
static bool empty(callback_t callback) {
if (disk_buffer_filled>0) {
if (disk_buffer_sought!=disk_buffer_start) {
/*@-nullpass@*/
resort_to_errno(fseek(disk_buffer,disk_buffer_start,SEEK_SET)!=0,
"error seeking in temporary file",EX_IOERR);
/*@=nullpass@*/
disk_buffer_sought=disk_buffer_start;
}
while (disk_buffer_filled>0) {
/*@-nullpass@*/
buffer_char=getc(disk_buffer);
/*@=nullpass@*/
resort_to_errno(buffer_char==EOF,
"error reading temporary file",EX_IOERR);
++disk_buffer_sought;
++disk_buffer_start;
--disk_buffer_filled;
--buffer_filled;
if (buffer_read>0) --buffer_read;
if (buffer_marked) {
if (buffer_mark>0) --buffer_mark;
else buffer_marked=false;
}
if (!(*callback)()) return true;
}
}
while (mem_buffer_filled>0) {
buffer_char=(int)(unsigned int)*mem_buffer_next_empty;
++mem_buffer_next_empty;
if (mem_buffer_next_empty==mem_buffer_end) mem_buffer_next_empty=mem_buffer_start;
--mem_buffer_filled;
--buffer_filled;
if (buffer_read>0) --buffer_read;
if (buffer_marked) {
if (buffer_mark>0) --buffer_mark;
else buffer_marked=false;
}
if (!(*callback)()) return true;
}
buffer_char=EOF;
if (!(*callback)()) return true;
return false;
}
// Get more characters into the (end of the) buffer. The same
// general principles as for look() apply. The callback is called
// after the character is added and all accounting has been done,
// gets the character via buffer_char, including an EOF when no more
// input is available (EOF on stdin). It should return whether to get
// more characters, and this function will return whether its exit was
// requested by the callback or not (the callback may signal EOF is
// an appropriate place to stop and we still return true).
// When the buffer is full there are a number of automatic options
// echo old the data to stdout or call encodechar for it one character
// at a time; shunt a block off to disk, keeping mem_buffer_keep in
// memory, discard it a character at a time, stop (and return false;
// no EOF call is made), or fail (exit). Here 'full' is defined as
// less than mem_buffer_margin of space after adding the most recent
// character, so there is always a bit of space for callbacks to do
// input transformations. Again, at least one character is always
// added (if possible), and thus consumed from stdin, so only call this
// if you really want to do that.
static bool fill(callback_t callback, when_full_t when_full) {
if (feof(stdin)!=0) {
buffer_char=EOF;
if (!(*callback)()) return true;
return false;
}
for (;;) {
/*@-infloops@*/
while (mem_buffer_filled>=mem_buffer_size-mem_buffer_margin) {
switch (when_full) {
case echo:
if (disk_buffer_filled>0) echo_disk_buffer();
(void)empty(echoing_one_char);
break;
case encode:
if (disk_buffer_filled>0) encode_disk_buffer();
(void)empty(encoding_one_char);
break;
case discard:
if (disk_buffer_filled>0) skip_disk_buffer();
(void)empty(one_char);
break;
case shunt:
shunt_to_disk(mem_buffer_filled-mem_buffer_keep);
break;
case stop:
return false;
case fail: default:
resort_to_exit(true,"buffer full",EX_SOFTWARE);
}
}
/*@=infloops@*/
buffer_char=get();
if (buffer_char==EOF) {
resort_to_errno(ferror(stdin)!=0,"error reading input",EX_IOERR);
if (!(*callback)()) return true;
return false;
}
*mem_buffer_next_fill=(char)buffer_char;
++mem_buffer_next_fill;
if (mem_buffer_next_fill==mem_buffer_end) mem_buffer_next_fill=mem_buffer_start;
++mem_buffer_filled;
++buffer_filled;
if (!(*callback)()) return true;
}
}
static inline void create_disk_buffer() {
int fildes;
fildes=mkstemp(disk_buffer_template);
resort_to_errno(fildes==-1,
"cannot create temporary file",EX_CANTCREAT);
disk_buffer=fdopen(fildes,"rw");
resort_to_errno(disk_buffer==NULL,
"cannot create temporary stream",EX_CANTCREAT);
}
static void remove_disk_buffer() {
if (disk_buffer!=NULL) {
resort_to_warning(fclose(disk_buffer)!=0,
"error closing temporary file");
disk_buffer=NULL;
resort_to_warning(unlink(disk_buffer_template)!=0,
"error removing temporary file");
}
}
static inline void shunt_to_disk(int n) {
if (disk_buffer==NULL) create_disk_buffer();
if (disk_buffer_sought!=disk_buffer_start+disk_buffer_filled) {
disk_buffer_sought=disk_buffer_start+disk_buffer_filled;
/*@-nullpass@*/
resort_to_errno(fseek(disk_buffer,
disk_buffer_start+disk_buffer_filled,SEEK_SET)!=0,
"cannot seek to end of temporary file",EX_IOERR);
/*@=nullpass@*/
}
while (n>0) {
resort_to_exit(mem_buffer_filled==0,
"internal error: shunting too much to disk",EX_SOFTWARE);
/*@-nullpass@*/
resort_to_errno(putc(*mem_buffer_next_empty,disk_buffer)==EOF,
"error writing to temporary file",EX_IOERR);
/*@=nullpass@*/
++disk_buffer_sought;
++disk_buffer_filled;
++mem_buffer_next_empty;
if (mem_buffer_next_empty==mem_buffer_end) mem_buffer_next_empty=mem_buffer_start;
--mem_buffer_filled;
--n;
}
}
/* tag: callback_functions */
static bool one_char() {
callback_int=buffer_char;
return false;
}
static bool echoing_one_char() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
callback_int=buffer_char;
return false;
}
static bool encoding_one_char() {
if (buffer_char!=EOF) encodechar(buffer_char);
callback_int=buffer_char;
return false;
}
// Set up callback_int before using this.
static bool n_chars() {
return --callback_int>0;
}
// Set up callback_int before using this.
static bool echoing_n_chars() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
return --callback_int>0;
}
// Set up callback_int before using this.
static bool encoding_n_chars() {
if (buffer_char!=EOF) encodechar(buffer_char);
return --callback_int>0;
}
// Set up callback_int and callback_save before using this.
static bool saving_n_chars() {
if (buffer_char!=EOF) *callback_save++=(char)buffer_char;
// We don't actually need this, though it's a good idea, really!
// *callback_save='\0';
return --callback_int>0;
}
// Set up callback_int and callback_match before using this.
static bool n_chars_until_match() {
callback_bool=buffer_char==callback_match;
return --callback_int>0&&buffer_char!=callback_match;
}
// Do callback_bool=false before using this.
static bool until_eol() {
if (buffer_char==(int)'\n') return !callback_bool;
callback_bool=buffer_char==(int)'\r';
return true;
}
// Do callback_bool=false before using this.
/*static bool echoing_until_eol() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
if (buffer_char==(int)'\n') return !callback_bool;
callback_bool=buffer_char==(int)'\r';
return true;
}*/
// Do callback_bool=false, callback_int=0 before using this.
static bool counting_until_eol() {
if (buffer_char!=EOF) ++callback_int;
if (buffer_char==(int)'\n') return !callback_bool;
callback_bool=buffer_char==(int)'\r';
return true;
}
// Do callback_bool=false and set up callback_save before using this.
static bool saving_until_eol() {
if (buffer_char!=EOF) *callback_save++=(char)buffer_char;
// We don't actually need this, though it's a good idea, really!
// *callback_save='\0';
if (buffer_char==(int)'\n') return !callback_bool;
callback_bool=buffer_char==(int)'\r';
return true;
}
// Do callback_bool=false before using this.
static bool decoding_until_eol() {
// We decode as we fill and work directly in the buffer to make
// the transformation. We are guaranteed enough space to do this by
// mem_buffer_margin.
decode_t decoded;
decoded=decodechar(buffer_char);
// We always remove the latest undecoded character from the
// buffer.
++decoded.r;
if (decoded.r>mem_buffer_filled) {
// This will only happen for quoted-printable decoding
// whitespace stripping, and we can just live with it
// if we can't get rid of it all; with sensible constants
// something really is disobeying MIME and probably SMTP
// about line length anyway if this happens.
warning("unable to strip all whitespace; not enough in memory");
decoded.r=mem_buffer_filled;
}
if (buffer_filled-decoded.r<buffer_read) {
// We should always be working in lookahead when this happens,
// but better safe than sorry!
warning("unable to strip all whitespace; not enough unread");
decoded.r=buffer_filled-buffer_read;
}
if (buffer_marked&&buffer_filled-decoded.r<buffer_mark) {
// Marks should be in lookbehind too, but again,
// better safe than sorry! We unmark. Filling often
// does that anyway.
buffer_marked=false;
buffer_mark=0;
}
mem_buffer_next_fill-=decoded.r;
if (mem_buffer_next_fill<mem_buffer_start)
mem_buffer_next_fill+=mem_buffer_size;
mem_buffer_filled-=decoded.r;
buffer_filled-=decoded.r;
if (decoded.c1!=EOF) {
*mem_buffer_next_fill=(char)decoded.c1;
++mem_buffer_next_fill;
if (mem_buffer_next_fill==mem_buffer_end) mem_buffer_next_fill=mem_buffer_start;
++mem_buffer_filled;
++buffer_filled;
if (decoded.c2!=EOF) {
*mem_buffer_next_fill=(char)decoded.c2;
++mem_buffer_next_fill;
if (mem_buffer_next_fill==mem_buffer_end) mem_buffer_next_fill=mem_buffer_start;
++mem_buffer_filled;
++buffer_filled;
if (decoded.c3!=EOF) {
*mem_buffer_next_fill=(char)decoded.c3;
++mem_buffer_next_fill;
if (mem_buffer_next_fill==mem_buffer_end) mem_buffer_next_fill=mem_buffer_start;
++mem_buffer_filled;
++buffer_filled;
}
}
}
// We check for eol using the input stream, not the decoded
// stream, as it's all about the upcoming boundary
if (buffer_char==(int)'\n') return !callback_bool;
callback_bool=buffer_char==(int)'\r';
return true;
}
/*static bool until_no_lookbehind() {
return buffer_read!=0;
}*/
static bool echoing_until_no_lookbehind() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
return buffer_read!=0;
}
static bool encoding_until_no_lookbehind() {
if (buffer_char!=EOF) encodechar(buffer_char);
return buffer_read!=0;
}
static bool until_no_disk_buffer() {
return disk_buffer_filled!=0;
}
static bool echoing_until_no_disk_buffer() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
return disk_buffer_filled!=0;
}
static bool encoding_until_no_disk_buffer() {
if (buffer_char!=EOF) encodechar(buffer_char);
return disk_buffer_filled!=0;
}
static bool until_no_buffer() {
return buffer_filled!=0;
}
/*static bool echoing_until_no_buffer() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
return buffer_filled!=0;
}*/
static bool until_start_marked() {
return !(buffer_marked?buffer_mark==0:buffer_read==0);
}
static bool echoing_until_start_marked() {
if (buffer_char!=EOF) {
resort_to_errno(put(buffer_char)==EOF,"error echoing",EX_IOERR);
}
return !(buffer_marked?buffer_mark==0:buffer_read==0);
}
static bool encoding_until_start_marked() {
if (buffer_char!=EOF) encodechar(buffer_char);
return !(buffer_marked?buffer_mark==0:buffer_read==0);
}
// Set up callback_match before using this.
static bool until_match() {
return buffer_char!=callback_match;
}
// Set up callback_compare before using this.
static bool comparing_head() {
/*@-nullderef@*/
if (buffer_char!=(int)(unsigned int)*callback_compare) {
callback_bool=false;
return false;
}
/*@-modobserver@*/
++callback_compare;
/*@=modobserver@*/
if (*callback_compare=='\0') {
callback_bool=true;
return false;
}
return true;
/*@=nullderef@*/
}
// Set up callback_compare before using this.
static bool case_insensitively_comparing_head() {
/*@-nullderef@*/
int c1=(int)(unsigned int)*callback_compare;
int c2=buffer_char;
if (c1!=c2&&
(c1<(int)'A'||c1>(int)'Z'||c2!=c1-(int)'A'+(int)'a')&&
(c2<(int)'A'||c2>(int)'Z'||c1!=c2-(int)'A'+(int)'a')) {
callback_bool=false;
return false;
}
/*@-modobserver@*/
++callback_compare;
/*@=modobserver@*/
if (*callback_compare=='\0') {
callback_bool=true;
return false;
}
return true;
/*@=nullderef@*/
}
/* tag: encoding_functions */
static inline void encode_string(const char * s) {
while (*s!='\0') {
encodechar((int)(unsigned int)*s);
s++;
}
}
static void encodechar(int c) {
if (encoding==unencoded) {
if (c!=EOF) resort_to_errno(put(c)==EOF,"error encoding",EX_IOERR);
return;
} else if (encoding==quoted_printable) {
if (encoding_echoed>=68) {
// We need a soft line break, or are close enough to needing
// one (76 chars max; unclear whether that counts the CRLF; and
// we may output two 3 character sequences which we don't want
// to follow with an unescaped CRLF). This scheme will probably
// make mail look a bit awful, but that's fairly standard anyway,
// and it shouldn't degrade.
resort_to_errno(putstr("=\r\n")==EOF,
"error encoding string",EX_IOERR);
encoding_echoed=0;
}
if (encoding_filled==1) {
// Whatever happens, we'll deal with this now
encoding_filled=0;
if (encoding_buffer[0]=='\r') {
if (c==(int)'\n') {
// Output them as is and we're done for now
resort_to_errno(putstr("\r\n")==EOF,
"error encoding string",EX_IOERR);
encoding_echoed=0;
return;
} else {
// Must encode the bare CR and continue as normal
resort_to_errno(put((int)'=')==EOF,"error encoding",EX_IOERR);
encode_hex_byte((unsigned int)'\r');
encoding_echoed+=3;
}
} else {
// encoding_buffer[0] must be whitespace
if (c==EOF||c==(int)'\r') {
// Must encode it
resort_to_errno(put((int)'=')==EOF,"error encoding",EX_IOERR);
encode_hex_byte((unsigned int)encoding_buffer[0]);
encoding_echoed+=3;
} else {
// It is fine to output it now as something else is coming
resort_to_errno(put(
(int)(unsigned int)encoding_buffer[0])==EOF,
"error encoding",EX_IOERR);
encoding_echoed+=1;
}
}
}
if ((c>=33&&c<=60)||(c>=62&&c<=126)) {
resort_to_errno(put(c)==EOF,"error encoding",EX_IOERR);
++encoding_echoed;
} else if (c==(int)' '||c==(int)'\t') {
if (encoding_echoed>=55) {
// My concession to readability; since it's likely to be
// a big mess with a 68 character width, we might as well
// break a bit earlier on a nice word boundary. And it'll
// in fact look better if we break with roughly equal size
// lines, assuming they come in at close to 76 characters
// wide, so we might as well make a nice skinny column.
// rather than a ragged one that uses the same amount of
// space. Compromising between the two, then, as some
// formats, like HTML, don't have many hard line breaks
// anyway, is what we get.
resort_to_errno(put(c)==EOF,"error encoding",EX_IOERR);
resort_to_errno(putstr("=\r\n")==EOF,
"error encoding string",EX_IOERR);
encoding_echoed=0;
} else {
// Store it; we may need to encode it if it's at end of line
encoding_filled=1;
encoding_buffer[0]=(char)c;
}
} else if (c==(int)'\r') {
// Store it; '\n' may be coming up
encoding_filled=1;
encoding_buffer[0]='\r';
} else if (c==EOF) {
// No buffer, and we're done! Reset for another run.
encoding_echoed=0;
} else {
// Anything else must be encoded as a sequence.
resort_to_errno(put((int)'=')==EOF,"error encoding",EX_IOERR);
encode_hex_byte((unsigned int)c);
encoding_echoed+=3;
}
} else if (encoding==base64) {
if (c==EOF) {
// Reset for next run; we won't need it here
encoding_echoed=0;
if (encoding_filled==0) return;
encoding_buffer[encoding_filled]='\0';
} else {
encoding_buffer[encoding_filled++]=(char)c;
}
if (encoding_filled==3||c==EOF) {
encode_64((((unsigned int)encoding_buffer[0]>>2)&0x3f));
encode_64((((unsigned int)encoding_buffer[0]&0x03)<<4)|
(((unsigned int)encoding_buffer[1]>>4)&0x0f));
if (encoding_filled==1) {
resort_to_errno(put((int)'=')==EOF,"error encoding",EX_IOERR);
resort_to_errno(put((int)'=')==EOF,"error encoding",EX_IOERR);
// Reset for next run
encoding_filled=0;
return;
}
encode_64((((unsigned int)encoding_buffer[1]&0x0f)<<2)|
(((unsigned int)encoding_buffer[2]>>6)&0x03));
if (encoding_filled==2) {
resort_to_errno(put((int)'=')==EOF,"error encoding",EX_IOERR);
// Reset for next run
encoding_filled=0;
return;
}
encode_64((((unsigned int)encoding_buffer[2]&0x3f)));
encoding_echoed+=4;
if (encoding_echoed>=72) {
resort_to_errno(putstr("\r\n")==EOF,
"error encoding string",EX_IOERR);
encoding_echoed=0;
}
encoding_filled=0;
}
} else {
resort_to_exit(true,"internal error: unknown encoding",EX_SOFTWARE);
}
}
static inline void finish_encoding() {
encodechar(EOF);
}
// The function takes an input character c and returns up to four output
// characters (a character will be EOF to indicate no further characters
// to store; note that this doesn't mean there will be no more ever; only
// if EOF is returned when EOF was input does it meant this), and a number
// of characters to remove before adding the aforementioned characters.
static decode_t decodechar(int c) {
int h;
unsigned int b1, b2, b3, b4;
decode_t o;
o.r=0; o.c1=EOF; o.c2=EOF; o.c3=EOF;
if (decoding==unencoded) {
o.c1=c;
return o;
} else if (decoding==quoted_printable) {
// decoding_buffer may hold '=' and maybe a hex digit or a CR.
if (decoding_filled==2) {
// Whatever happens, it's all settled now.
decoding_filled=0;
if (decoding_buffer[1]=='\r') {
if (c==(int)'\n') { return o; }
// Invalid; leave as is--will be encoded later.
o.c1=(int)'='; o.c2=(int)'\r'; o.c3=c;
return o;
}
h=decode_hex(c);
if (h==EOF) {
// Invalid; leave as is--will be encoded later.
o.c1=(int)'='; o.c2=(int)(unsigned int)decoding_buffer[1]; o.c3=c;
return o;
}
// We have a full sequence representing a single character.
o.c1=decode_hex((int)(unsigned int)decoding_buffer[1])*16+h;
return o;
} else if (decoding_filled==1) {
if (c==(int)'\r'||decode_hex(c)!=EOF) {
// Valid character after =
decoding_filled=2;
decoding_buffer[1]=(char)c;
return o;
}
// Invalid; leave as is--will be encoded later.
decoding_filled=0;
o.c1=(int)'='; o.c2=c;
return o;
} else if (decoding_filled==0) {
if (c==(int)'=') {
// The first character can only ever be '=' so we
// don't actually bother to store it; just say it's there.
decoding_white=0;
decoding_filled=1;
return o;
}
// Keep track of whitespace.
if (c==(int)' '||c==(int)'\t') ++decoding_white;
else decoding_white=0;
// Remove trailing whitespace.
if (c==EOF||c==(int)'\r') { o.r=decoding_white; decoding_white=0; }
// Otherwise we just keep it. If it's EOF, we're done.
o.c1=c;
return o;
} else {
warning("internal error: decoding buffer too full");
return o;
}
} else if (decoding==base64) {
if (c==EOF) {
// Just in case it was corrupted, make sure we're reset
decoding_filled=0;
return o;
}
if (c==(int)'='||decode_64(c)!=EOF)
decoding_buffer[decoding_filled++]=(char)c;
if (decoding_filled==4) {
// We empty it whatever happens here
decoding_filled=0;
b1=(unsigned int)decode_64((int)decoding_buffer[0]);
b2=(unsigned int)decode_64((int)decoding_buffer[1]);
o.c1=(int)(((b1&0x3f)<<2)|((b2>>4)&0x03));
if (decoding_buffer[2]=='=') return o;
b3=(unsigned int)decode_64((int)decoding_buffer[2]);
o.c2=(int)(((b2&0x0f)<<4)|((b3>>2)&0x0f));
if (decoding_buffer[3]=='=') return o;
b4=(unsigned int)decode_64((int)decoding_buffer[3]);
o.c3=(int)(((b3&0x03)<<6)|(b4&0x3f));
}
return o;
} else {
resort_to_exit(true,"internal error: unknown encoding",EX_SOFTWARE);
// Never reached
return o;
}
}
static void decode_lookahead() {
// Decoding will always shrink, so this is quite easy
char * c;
char * cc;
decode_t decoded;
int pos=buffer_read;
int decpos=buffer_read;
resort_to_exit(buffer_read<disk_buffer_filled,
"internal error: decoding from disk",EX_SOFTWARE);
c=mem_buffer_next_empty+pos-disk_buffer_filled;
if (c>=mem_buffer_end) c-=mem_buffer_size;
cc=c;
while (pos<buffer_filled) {
decoded=decodechar((int)(unsigned int)*c);
if (decoded.r>0) {
resort_to_exit(decpos-decoded.r<buffer_read,
"internal error: removing more than was decoded",EX_SOFTWARE);
decpos-=decoded.r;
cc-=decoded.r;
if (cc<mem_buffer_start) cc+=mem_buffer_size;
}
if (decoded.c1!=EOF) {
*cc=(char)decoded.c1;
++decpos; ++cc;
if (cc==mem_buffer_end) cc=mem_buffer_start;
if (decoded.c2!=EOF) {
*cc=(char)decoded.c2;
++decpos; ++cc;
if (cc==mem_buffer_end) cc=mem_buffer_start;
if (decoded.c3!=EOF) {
*cc=(char)decoded.c3;
++decpos; ++cc;
if (cc==mem_buffer_end) cc=mem_buffer_start;
}
}
}
++pos; ++c;
if (c==mem_buffer_end) c=mem_buffer_start;
}
buffer_filled+=decpos-pos;
mem_buffer_filled+=decpos-pos;
mem_buffer_next_fill+=decpos-pos;
if (mem_buffer_next_fill<mem_buffer_start)
mem_buffer_next_fill+=mem_buffer_size;
}
static inline void finish_decoding() {
// As it will have just experienced a CRLF or an EOF, the only thing
// this can do is reset the state if base64 was truncated.
// We won't gain any more characters or need to remove anything.
// It is important that this is always the case as other routines
// rely on it.
(void)decodechar(EOF);
}
// These are slow but easy to write! Lookup tables would be quicker.
// Still, I think it'll probably be fast enough.
static inline int decode_hex(int c) {
if (c>=(int)'0'&&c<=(int)'9') return c-(int)'0';
if (c>=(int)'A'&&c<=(int)'F') return c-(int)'A'+10;
return EOF;
}
static inline int decode_64(int c) {
if (c>=(int)'A'&&c<=(int)'Z') return c-(int)'A';
if (c>=(int)'a'&&c<=(int)'z') return c-(int)'a'+26;
if (c>=(int)'0'&&c<=(int)'9') return c-(int)'0'+52;
if (c==(int)'+') return 62;
if (c==(int)'/') return 63;
// if (c==(int)'=') return EOF;
return EOF;
}
static inline void encode_hex_byte(unsigned int h) {
int h1=(int)((h>>4)&0x0f);
int h2=(int)(h&0x0f);
if (h1<10) resort_to_errno(put((int)'0'+h1)==EOF,"error encoding",EX_IOERR);
else if (h1<16)
resort_to_errno(put((int)'A'+h1-10)==EOF,"error encoding",EX_IOERR);
else resort_to_exit(true,"internal error: byte too large",EX_SOFTWARE);
if (h2<10) resort_to_errno(put((int)'0'+h2)==EOF,"error encoding",EX_IOERR);
else if (h2<16)
resort_to_errno(put((int)'A'+h2-10)==EOF,"error encoding",EX_IOERR);
else resort_to_exit(true,"internal error: byte too large",EX_SOFTWARE);
}
static inline void encode_64(unsigned int b) {
if (b<26)
resort_to_errno(put((int)'A'+b)==EOF,"error encoding",EX_IOERR);
else if (b<52)
resort_to_errno(put((int)'a'+b-26)==EOF,"error encoding",EX_IOERR);
else if (b<62)
resort_to_errno(put((int)'0'+b-52)==EOF,"error encoding",EX_IOERR);
else if (b==62)
resort_to_errno(put((int)'+')==EOF,"error encoding",EX_IOERR);
else if (b==63)
resort_to_errno(put((int)'/')==EOF,"error encoding",EX_IOERR);
else resort_to_exit(true,
"internal error: base64 value too large",EX_SOFTWARE);
}
/* tag: error_functions */
// Syslog constants:
// level: LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG
// facility: LOG_MAIL, LOG_DAEMON, LOG_USER, LOG_LOCALn(0-7)
static inline void * alloc_or_exit(size_t s) /*@allocates result@*/ {
void * m;
m=malloc(s);
if (m==NULL) {
#ifdef USE_STDERR
fprintf(stderr,"foot_filter: %s\n","out of memory");
#endif
#ifdef USE_SYSLOG
syslog(LOG_ERR|LOG_MAIL,"%s\n","out of memory");
#endif
exit(EX_OSERR);
}
return m;
}
static inline void /*noreturnwhentrue*/
resort_to_exit(bool when,const char * message,int status) {
if (when) {
#ifdef USE_STDERR
fprintf(stderr,"foot_filter: %s\n",message);
#endif
#ifdef USE_SYSLOG
syslog(LOG_ERR|LOG_MAIL,"%s\n",message);
#endif
exit(status);
}
}
static inline void /*noreturnwhentrue*/
resort_to_errno(bool when,const char * message,int status) {
if (when) {
#ifdef USE_STDERR
fprintf(stderr,"foot_filter: %s (%s)\n",message,strerror(errno));
#endif
#ifdef USE_SYSLOG
syslog(LOG_ERR|LOG_MAIL,"%s (%m)\n",message);
#endif
exit(status);
}
}
static inline void resort_to_warning(bool when,const char * message) {
if (when) warning(message);
}
static inline void warning(const char * message) {
#ifdef USE_STDERR
fprintf(stderr,"foot_filter: %s\n",message);
#endif
#ifdef USE_SYSLOG
syslog(LOG_WARNING|LOG_MAIL,"%s\n",message);
#endif
}
/* tag: helper_functions */
// The program was written following all the specs using CRLF for newlines,
// but we get them from Postfix with LF only, so these wrapper functions
// do the translation in such a way that it can easily be disabled if desired.
static inline int get() {
int c;
#ifdef UNIX_EOL
static bool got_nl=false;
if (got_nl) {
got_nl=false;
return 10;
}
#endif
c=getchar();
#ifdef UNIX_EOL
if (c==10) {
got_nl=true;
return 13;
}
#endif
return c;
}
static inline int put(int c) {
#ifdef UNIX_EOL
if (c==13) return c;
#endif
return putchar(c);
}
static inline int putstr(const char * s) {
while (*s!='\0') if (put((int)(unsigned int)*s++)==EOF) return EOF;
return 0;
}
static inline bool case_insensitively_heads(const char * head,const char * buffer) {
const char * s1=head;
const char * s2=buffer;
for (;;) {
if (*s1=='\0') return true; /* for equality return *s2=='\0'; */
else if (*s2=='\0') return false;
if (*s1!=*s2&&
(*s1<'A'||*s1>'Z'||*s2!=*s1-'A'+'a')&&
(*s2<'A'||*s2>'Z'||*s1!=*s2-'A'+'a')) return false;
++s1; ++s2;
}
}
|
the_stack_data/148522.c | #include <stdio.h>
int main() {
FILE *archivo;
char letra;
int numero;
int total = 0;
archivo = fopen("numeros.txt", "r");
if(archivo == NULL){
printf("\n No existe el archivo");
printf("\n\n");
return 0;
}
while(!feof(archivo)){
numero = 0;
fscanf(archivo, "%d,", &numero );
total = total + numero;
}
fclose(archivo);
printf("El total es: %d", total);
printf("\n\n");
return 0;
}
|
the_stack_data/165764570.c | /*
* rofdump
*
* Utility program for reading ROF binary files from Rigol 8xx series lab
* power supplies.
*
* Copyright (C) 2017 Mark Ruiz ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the standard MIT license. See COPYING for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdbool.h>
#ifdef __MACH__
#include <machine/endian.h>
#else
#include <endian.h>
#endif
#define VERSION "1.0"
#define OFFSET_PERIOD 16
#define OFFSET_CHANNELS_DATA 28
void print_usage(int error)
{
FILE *output = error ? stderr : stdout;
fprintf(output, "ROFDUMP %s: A utility for reading ROF files produced"
"by Rigol 8xx lab power supplies - Mark Ruiz ([email protected])"
"\n", VERSION);
fprintf(output, "usage: rofdump [-h] [-c] filename\n");
fprintf(output, "options:\n");
fprintf(output, "\t-h\tprint usage\n");
fprintf(output, "\t-c\toutput CSV\n");
}
int main(int argc, char *argv[])
{
if (argc < 2) {
print_usage(1);
exit(EXIT_FAILURE);
}
// Prevent getopt() from writing to stderr
opterr = 0;
int ch;
bool output_csv;
while ((ch = getopt(argc, argv, "ch")) != EOF) {
switch(ch) {
case 'c':
output_csv = true;
break;
case 'h':
print_usage(0);
exit(EXIT_SUCCESS);
case '?':
printf("rofdump: invalid option '-%c'\n", optopt);
print_usage(1);
exit(EXIT_FAILURE);
}
}
int fd = open(argv[optind], O_RDONLY, 0);
if (fd == -1) {
perror("Cannnot open specified file");
exit(EXIT_FAILURE);
}
// Read the first 4 bytes and make sure we're reading an ROF file
char magic[4];
ssize_t bytes_read = read(fd, &magic, sizeof(magic));
if (strcmp(magic, "ROF") != 0) {
printf("Specified file is not a valid ROF file\n");
exit(EXIT_FAILURE);
}
// Try and seek to byte offset for period
off_t pos = lseek(fd, OFFSET_PERIOD, SEEK_SET);
if (pos == -1) {
perror("Cannnot seek ROF file");
exit(EXIT_FAILURE);
}
// Read the period
uint32_t period;
bytes_read = read(fd, &period, sizeof(period));
if (bytes_read != sizeof(period)) {
printf("Could not read period from ROF file\n");
exit(EXIT_FAILURE);
}
// Read the number of data points
uint32_t points;
bytes_read = read(fd, &points, sizeof(points));
if (bytes_read != sizeof(points)) {
printf("Could not read number of data points from ROF file\n");
exit(EXIT_FAILURE);
}
// Determine the number of channels in the data section
pos = lseek(fd, 0, SEEK_END);
if (pos == -1) {
perror("Could not determine number of channels in ROF file\n");
exit(EXIT_FAILURE);
}
int num_channels = (pos - OFFSET_CHANNELS_DATA) / points / 8;
if (output_csv) {
printf("Seconds");
for (int i = 1; i <= num_channels; i++)
printf(",CH%i Voltage,CH%i Current", i, i);
printf("\n");
} else {
printf("Data points: %i\n", points);
printf("Period: %i second(s)\n", period);
printf("Number of channels: %i\n\n", num_channels);
}
// Read the data for each channel at each point
pos = lseek(fd, OFFSET_CHANNELS_DATA, SEEK_SET);
if (pos == -1) {
perror("Could not seek to data section of ROF file\n");
exit(EXIT_FAILURE);
}
int seconds = 0;
off_t end = lseek(fd, 0, SEEK_END);
lseek(fd, pos, SEEK_SET);
while (lseek(fd, 0, SEEK_CUR) != end) {
if (output_csv)
printf("%i", seconds);
else
printf("%i:\t", seconds);
for (int channel = 0; channel < num_channels; channel++) {
uint32_t value;
// Read the recorded voltage
bytes_read = read(fd, &value, sizeof(value));
if (bytes_read != sizeof(value)) {
fprintf(stderr, "Failed to read voltage value at %i seconds",
seconds);
exit(EXIT_FAILURE);
}
float voltage = (float)value / 10000;
// Read the recorded current
bytes_read = read(fd, &value, sizeof(value));
if (bytes_read != sizeof(value)) {
fprintf(stderr, "Failed to read current value at %i seconds",
seconds);
exit(EXIT_FAILURE);
}
float current = (float)value / 10000;
if (output_csv)
printf(",%f,%f", voltage, current);
else
printf("%f(V), %f(A)\t", voltage, current);
}
printf("\n");
seconds += period;
}
exit(EXIT_SUCCESS);
}
|
the_stack_data/14198956.c | /*
** EPITECH PROJECT, 2020
** NWP_myftp_2019
** File description:
** TODO: add description
*/
#include <zconf.h>
void close_fd(int *fd)
{
if (*fd == -1)
return;
close(*fd);
*fd = -1;
} |
the_stack_data/955603.c | #include "stdbool.h"
#include "stdio.h"
#include <stdlib.h>
bool isFileExist(FILE* fileName)
{
return (fileName != NULL);
}
void readFile(FILE* fileName, int* letters)
{
char symbol = fgetc(fileName);
while (symbol != EOF) {
if (symbol >= 97 && symbol <= 122)
letters[symbol - 97] += 1;
symbol = fgetc(fileName);
}
}
void printInFile(int* letters)
{
FILE* output = fopen("output.txt", "w");
for (int i = 0; i < 26; i++) {
if (letters[i] != 0)
fprintf(output, "%c: %d\n", i + 97, letters[i]);
}
fclose(output);
}
int main(int argc, char* argv[])
{
FILE* input = fopen(argv[1], "r");
if (!(isFileExist(input))) {
printf("The file doesn't exist");
return 0;
}
int* array = calloc(26, sizeof(int));
readFile(input, array);
printInFile(array);
free(array);
fclose(input);
return 0;
} |
the_stack_data/87293.c | #include <stdio.h>
#include <stdlib.h>
int main(){
float n;
printf("Digite o valor em Polegadas:");
scanf("%f",&n);
printf("\nValor em centimetros: %.2f\n\n", n =n * 2.54);
system("PAUSE");
return 0;
}
|
the_stack_data/107826.c | #include <pthread.h>
int count;
void* thread(void *arg) {
count = count + 1;
return NULL;
}
void main() {
pthread_t t;
count = 0;
pthread_create(&t, NULL, thread, NULL);
pthread_create(&t, NULL, thread, NULL);
assert(count <= 2);
}
|
the_stack_data/67326158.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* converte_n_bin(int x, int n){
// 30 é maior do que qualquer campo
char str[30] = {'\0'};
char* inv = calloc(30, sizeof(char));
int tam = 0;
int negativo = (x < 0);
x = (x >= 0)?x:-x; // x = |x|
while(x >= 2){
if(x%2 == 0)
str[tam++] = '0';
else
str[tam++] = '1';
x /= 2;
}
if(x == 0){
str[tam] = '0';
}else{
str[tam] = '1';
}
int i, extra = n - tam - 1;
for(i = 0; i < extra; i ++){
inv[i] = '0';
}
for(i = 0; i <= tam; i ++){
inv[extra + i] = str[tam - i];
}
// lógica do compl. de 2 : se negativo, inverter bits e somar 1
if(negativo){
for(i = 0; i < strlen(inv); i ++){
if(inv[i] == '0'){
inv[i] = '1';
}else{
inv[i] = '0';
}
}
tam = strlen(inv);
if(inv[tam] == '0')
inv[tam] = '1';
else{
int temp = tam-1;
while(inv[temp] != '0'){
inv[temp] = '0';
temp--;
}
inv[temp] = '1';
}
}
return inv;
}
int main(int argc, char** argv){
int x = 9;
char* bin;
do{
printf("\nDigite um número inteiro\n");
scanf("%d", &x);
bin = converte_n_bin(x, 12);
printf("Bin(%d) = %s\n", x, bin);
free(bin);
}while(1);
return 0;
}
|
the_stack_data/853660.c | // RUN: mlir-clang %s %stdinclude --function=alloc -S | FileCheck %s
#include <time.h>
#include <sys/time.h>
double alloc() {
struct timeval Tp;
gettimeofday(&Tp, NULL);
return Tp.tv_sec + Tp.tv_usec * 1.0e-6;
}
// CHECK: func @alloc() -> f64
// CHECK-NEXT: %cst = arith.constant 9.9999999999999995E-7 : f64
// CHECK-NEXT: %0 = memref.alloca() : memref<1x2xi64>
// CHECK-NEXT: %1 = "polygeist.memref2pointer"(%0) : (memref<1x2xi64>) -> !llvm.ptr<struct<(i64, i64)>>
// CHECK-NEXT: %2 = llvm.mlir.null : !llvm.ptr<i8>
// CHECK-NEXT: %3 = llvm.bitcast %2 : !llvm.ptr<i8> to !llvm.ptr<struct<(i32, i32)>>
// CHECK-NEXT: %4 = llvm.call @gettimeofday(%1, %3) : (!llvm.ptr<struct<(i64, i64)>>, !llvm.ptr<struct<(i32, i32)>>) -> i32
// CHECK-NEXT: %5 = affine.load %0[0, 0] : memref<1x2xi64>
// CHECK-NEXT: %6 = arith.sitofp %5 : i64 to f64
// CHECK-NEXT: %7 = affine.load %0[0, 1] : memref<1x2xi64>
// CHECK-NEXT: %8 = arith.sitofp %7 : i64 to f64
// CHECK-NEXT: %9 = arith.mulf %8, %cst : f64
// CHECK-NEXT: %10 = arith.addf %6, %9 : f64
// CHECK-NEXT: return %10 : f64
// CHECK-NEXT: }
|
the_stack_data/874126.c | #include <stdio.h>
enum test{ ACE, JACK, QUEEN};
typedef enum test TEST; // rename it to ...
int main()
{
int a = ('A' || 'a'); // for case 'A'||'a', it ==> case 1
char grade;
scanf("%c", &grade); // %c ==> _%c, add blank before %c to omit blank
if (grade == 'A' || 'a')
{
printf("Always execute here as it right part is TRUE!\n");
}
switch(grade)
{
case 'A':
printf("Excellent Job!");
break;
case 'B' || 'b': // always test it whether it is true
printf("Good job!");
break;
default:
break;
}
printf("%d\n", a);
return 0;
}
|
the_stack_data/86075847.c | #include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
/**
*
*/
int main()
{
int n;
n = 0;
if (fork() == 0)
{
n++;
printf("Je suis le fils, n=%i\n", n);
exit(0);
}
printf("Je suis le père, n=%i\n", n);
exit(0);
} |
the_stack_data/108830.c | /*
SUBWAY_DOORS_MAP.C
Map Source File.
Info:
Section :
Bank : 0
Map size : 2 x 2
Tile set : C:\Users\pfsar\OneDrive\Documents\GitHub\gameboy_micro_game_collection\Resouces\minigames_0.gbr
Plane count : 1 plane (8 bits)
Plane order : Tiles are continues
Tile offset : 0
Split data : No
This file was generated by GBMB v1.8
*/
#define subway_doors_mapWidth 2
#define subway_doors_mapHeight 2
#define subway_doors_mapBank 0
unsigned char subway_doors_map[] =
{
0x67,0x5C,0x66,0x62
};
/* End of SUBWAY_DOORS_MAP.C */
|
the_stack_data/88285.c | #include <stdio.h>
extern void start_a1( void ) __attribute__((constructor));
extern void finish_a1( void ) __attribute__((destructor));
void
start_a1( void )
{
printf( "start_a1\n" );
}
void
finish_a1( void )
{
printf( "finish_a1\n" );
}
|
the_stack_data/20450531.c | #include<stdio.h>
int main()
{
printf("india\n");
}
|
the_stack_data/237643249.c | /* start_lib_test_1.c -- test --start-lib/--end-lib.
Copyright (C) 2010-2014 Free Software Foundation, Inc.
Written by Cary Coutant <[email protected]>
This file is part of gold.
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, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA.
This is a test of the --start-lib and --end-lib options. */
extern void t1 (void);
extern void t2 (void);
void
t1 (void)
{
t2 ();
}
|
the_stack_data/147534.c | #include<stdio.h>
int main()
{
int n;
printf("Enter the marks\n");
scanf("%d",&n);
if(n<=100 && n>=85)
printf("Your grade is A\n");
else if(n<=84 && n>=70)
printf("Your grade is B\n");
else if (n<=69 && n>=55)
printf("Your grade is C\n");
else if (n<=54 && n>=40)
printf("Your grade is D\n");
else
printf("Your grade is F\n");
return;
}
|
the_stack_data/111079042.c | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
extern void psg_abort(int error);
/*-------------------------------------------------------------------
|
| terminated() we have been told to exit, clean things up and die.
|
+---------------------------------------------------------------------*/
static
void terminated()
{
fprintf(stdout,
"PSG was User Terminated.. \n");
fflush(stdout);
psg_abort(1);
}
/*--------------------------------------------------------------------------------
|
| Fatal Error signal catchers, core dump after cleaning up & notifing all users
|
+--------------------------------------------------------------------------------*/
static
void Segment()
{
fprintf(stdout,
"'PSG: Segmentation Violation, Core Dumped.'\n");
fprintf(stdout,
"'Check for: Non NULL terminated Attribute-List Functions, or\n");
fprintf(stdout,
" Pointers or Array indices past allocated memory.'\n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void Ill_instr()
{
fprintf(stdout,
"'PSG: Illegal Instruction, Core Dumped.'\n");
fprintf(stdout,
"'Recompile and try again.'\n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void FPexcept()
{
fprintf(stdout,
"'PSG: Arithmetic Exception, Core Dumped.' \n");
fprintf(stdout,
"'Did You divide by ZERO ?'\n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void BusErr()
{
fprintf(stdout,
"'PSG: Bus Error, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void CpuLim()
{
fprintf(stdout,
"'PSG: Exceeded CPU Time Limit, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void FsLim()
{
fprintf(stdout,
"'PSG: Exceeded File Size Limit, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void SigQuit()
{
fprintf(stdout,
"'PSG: Quit Signal, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
static
void Trap()
{
fprintf(stdout,
"'PSG: Trace Trap, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
/*--------------- Commented Out ------------------------
static
void IOTtrap()
{
fprintf(stdout,
"'PSG: IOT Trap, Core Dumped.' \n");
}
+----------------------------------------------------*/
void PIPEtrap()
{
/* Ignore pipe error */
}
#ifdef SOLARIS
static
void EMTtrap()
{
fprintf(stdout,
"'PSG: EMT Trap, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
#endif
static
void SYStrap()
{
fprintf(stdout,
"'PSG: Bad Argument to a System Call, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
/*--------------- Commented Out ------------------------
static
void ResLost()
{
fprintf(stdout,
"'PSG: Resource Lost Exception, Core Dumped.' \n");
fflush(stdout);
kill(getpid(),SIGIOT);
}
+----------------------------------------------------*/
/*-------------------------------------------------------------------------
|
| Setup the exception handlers for fatal type errors
|
+--------------------------------------------------------------------------*/
void setupsignalhandler()
{
sigset_t qmask;
struct sigaction intquit;
struct sigaction segquit;
/* --- set up interrupt handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGINT );
intquit.sa_mask = qmask;
intquit.sa_handler = terminated;
intquit.sa_flags = 0;
sigaction(SIGINT,&intquit,0L);
/* --- set up segmentation violation handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGSEGV );
segquit.sa_mask = qmask;
segquit.sa_handler = Segment;
segquit.sa_flags = 0;
sigaction(SIGSEGV,&segquit,0L);
/* --- set up illegal instruction handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGILL );
segquit.sa_mask = qmask;
segquit.sa_handler = Ill_instr;
segquit.sa_flags = 0;
sigaction(SIGILL,&segquit,0L);
/* --- set up arithmetic exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGFPE );
segquit.sa_mask = qmask;
segquit.sa_handler = FPexcept;
segquit.sa_flags = 0;
sigaction(SIGFPE,&segquit,0L);
/* --- set up buss error exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGBUS );
segquit.sa_mask = qmask;
segquit.sa_handler = BusErr;
segquit.sa_flags = 0;
sigaction(SIGBUS,&segquit,0L);
/* --- set up cpu limit error exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGXCPU );
segquit.sa_mask = qmask;
segquit.sa_handler = CpuLim;
segquit.sa_flags = 0;
sigaction(SIGXCPU,&segquit,0L);
/* --- set up file size limit error exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGXFSZ );
segquit.sa_mask = qmask;
segquit.sa_handler = FsLim;
segquit.sa_flags = 0;
sigaction(SIGXFSZ,&segquit,0L);
/* --- set up quit signal exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGQUIT );
segquit.sa_mask = qmask;
segquit.sa_handler = SigQuit;
segquit.sa_flags = 0;
sigaction(SIGQUIT,&segquit,0L);
/* --- set up Trace Trap exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGTRAP );
segquit.sa_mask = qmask;
segquit.sa_handler = Trap;
segquit.sa_flags = 0;
sigaction(SIGTRAP,&segquit,0L);
/* not needed for SUN 3s */
/* --- set up IOT trap exception handler --- */
/*
sigemptyset( &qmask );
sigaddset( &qmask, SIGIOT );
segquit.sa_mask = qmask;
segquit.sa_handler = IOTtrap;
segquit.sa_flags = 0;
sigaction(SIGIOT,&segquit,0L);
*/
/* --- set up PIPE trap exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGPIPE );
segquit.sa_mask = qmask;
segquit.sa_handler = PIPEtrap;
segquit.sa_flags = 0;
sigaction(SIGPIPE,&segquit,0L);
#ifdef SOLARIS
/* --- set up EMT trap exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGEMT );
segquit.sa_mask = qmask;
segquit.sa_handler = EMTtrap;
segquit.sa_flags = 0;
sigaction(SIGEMT,&segquit,0L);
#endif
/* --- set up bad argument to system call exception handler --- */
sigemptyset( &qmask );
sigaddset( &qmask, SIGSYS );
segquit.sa_mask = qmask;
segquit.sa_handler = SYStrap;
segquit.sa_flags = 0;
sigaction(SIGSYS,&segquit,0L);
/* --- set up bad argument to system call exception handler --- */
/*sigemptyset( &qmask );
sigaddset( &qmask, SIGLOST );
segquit.sa_mask = qmask;
segquit.sa_handler = ResLost;
segquit.sa_flags = 0;
sigaction(SIGLOST,&segquit,0L);*/
}
|
the_stack_data/9346.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char*argv[])
{
FILE *fileIn;
FILE *fileOut;
char* inputFile = "in";
char* outputFile = "out";
char ch[256];
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "-i") == 0)
{
inputFile = argv[i + 1];
i++;
}
if (strcmp(argv[i], "-o") == 0)
{
outputFile = argv[i + 1];
i++;
}
}
if (strcmp(inputFile, "in") != 0)
{
fileIn = fopen(inputFile, "r");
//
}
else
{
printf("Enter text: ");
gets(ch);
}
if (strcmp(outputFile, "out") != 0)
{
fileOut = fopen(outputFile, "w");
fprintf(fileOut, "%s", ch);
}
else
{
printf("%s", ch);
}
return 0;
} |
the_stack_data/51241.c | #include <stdio.h>
int main()
{
int n=0,price=0,i=0,f=0,m=0,k=0,otstupka=0,sum=0;
scanf("%d",&n);
scanf("%d",&m);
scanf("%d",&k);
//m=m+2;
f=n/k;
while(i<f)
{
price=(m-otstupka)*k;
sum=sum+price;
//m=m/k;
otstupka=otstupka+0.02*m;
i++;
}
printf("%d\n",sum);
return 0;
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.