file
stringlengths 18
26
| data
stringlengths 3
1.04M
|
---|---|
the_stack_data/87637529.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 1024
void error_handling(char *message);
int main(int argc, char *argv[])
{
int sock;
char message[BUF_SIZE];
int str_len;
struct sockaddr_in serv_adr;
if(argc!=2) {
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
sock=socket(PF_INET, SOCK_STREAM, 0);
if(sock==-1)
error_handling("socket() error");
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
if(connect(sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr))==-1)
error_handling("connect() error!");
else
puts("Connected...........");
while(1)
{
fputs("Input message(Q to quit): ", stdout);
fgets(message, BUF_SIZE, stdin);
if(!strcmp(message,"q\n") || !strcmp(message,"Q\n"))
break;
write(sock, message, strlen(message));
// printf("Send Message to Server: %s", message);
message[0] = 0;
}
close(sock);
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
|
the_stack_data/133775.c
|
// RUN: %clang_cc1 -triple x86_64-darwin-apple -emit-llvm %s -o - | FileCheck %s
// PR6695
// CHECK: define{{.*}} void @test0(i32* noundef %{{.*}}, i32 noundef %{{.*}})
void test0(int *x, int y) {
}
// CHECK: define{{.*}} void @test1(i32* noalias noundef %{{.*}}, i32 noundef %{{.*}})
void test1(int * restrict x, int y) {
}
// CHECK: define{{.*}} void @test2(i32* noundef %{{.*}}, i32* noalias noundef %{{.*}})
void test2(int *x, int * restrict y) {
}
typedef int * restrict rp;
// CHECK: define{{.*}} void @test3(i32* noalias noundef %{{.*}}, i32 noundef %{{.*}})
void test3(rp x, int y) {
}
// CHECK: define{{.*}} void @test4(i32* noundef %{{.*}}, i32* noalias noundef %{{.*}})
void test4(int *x, rp y) {
}
|
the_stack_data/150141466.c
|
/* Demonstrates passing a pointer to a multidimensional */
/* array to a function. */
/* Adapted: Thu 19 Jul 2001 19:12:27 (Bob Heckel -- InformIT) */
#include <stdio.h>
void printarray_1(int (*ptr)[4]);
void printarray_2(int (*ptr)[4], int n);
int main(void) {
int multi[3][4] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
/* ptr is a pointer to an array of 4 ints. */
int (*ptr)[4], count;
/* Set ptr to point to the first element of multi. */
ptr = multi;
/* With each loop, ptr is incremented to point to the next */
/* element (that is, the next 4-element integer array) of multi. */
for (count = 0; count < 3; count++)
printarray_1(ptr++);
puts("\n\nPress Enter...");
getchar();
printarray_2(multi, 3);
printf("\n");
return(0);
}
void printarray_1(int (*ptr)[4]) {
/* Prints the elements of a single four-element integer array. */
/* p is a pointer to type int. You must use a type cast */
/* to make p equal to the address in ptr. */
int *p, count;
p = (int *)ptr;
for (count = 0; count < 4; count++)
printf("\n%d", *p++);
}
void printarray_2(int (*ptr)[4], int n) {
/* Prints the elements of an n by four-element integer array. */
int *p, count;
p = (int *)ptr;
for (count = 0; count < (4 * n); count++)
printf("\n%d", *p++);
}
|
the_stack_data/594497.c
|
// PROGRAMA p05a.c
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <signal.h>
void sig_chld_handler(int signo){
wait(NULL);
}
int main(void)
{
pid_t pid;
int i, n;
struct sigaction usrAction;
usrAction.sa_handler = SIG_IGN;
usrAction.sa_flags = 0;
sigemptyset(&usrAction.sa_mask);
sigaction(SIGCHLD,&usrAction,NULL);
for (i = 1; i <= 20; i++)
{
pid = fork();
if (pid == 0)
{
printf("CHILD no. %d (PID=%d) working ... \n", i, getpid());
sleep(15); // child working ...
printf("CHILD no. %d (PID=%d) exiting ... \n", i, getpid());
exit(0);
}
}
for (i = 1; i <= 4; i++)
{
printf("PARENT: working hard (task no. %d) ...\n", i);
n = 20;
while ((n = sleep(n)) != 0);
printf("PARENT: end of task no. %d\n", i);
}
exit(0);
}
|
the_stack_data/1045759.c
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int idade;
int num2[] = {1,5,9,15,43};
char vogais[5] = {'a','e','i','o','u'};
float notas[3] = {7.5,8.3,9.5};
printf("%d", num2[0]); //Informando o indice do vetor
for(int i = 0; i < 5; i++){
printf("%d ", num2[i]);
}
printf("\n\n");
for (int i = 0; i < 5; i++){
printf("%c ", vogais[i]);
}
printf("\n\n");
for (int i = 0; i < 3; i++){
printf("%.2f ", notas[i]);
}
return 0;
}
|
the_stack_data/53886.c
|
#include<stdio.h>
int main()
{
int i;
char type;
int course[3] = {0,0,0};
printf("Press E to exit.\n");
for (i = 0; i <= 100; ++i)
{
printf("Enter course type(H/M/F): ");
scanf("%c%*c", &type);
if (type == 'E' || type == 'e')
break;
else if (type == 'H' || type == 'h')
++course[0];
else if (type == 'M' || type == 'm')
++course[1];
else if (type == 'F' || type == 'f')
++course[2];
else {
printf("Invalid Input!\n");
--i;
}
}
printf("\nCourse\tNo of students\tTotal income");
printf("\nH\t%d\t\t%.2f", course[0], course[0] * 1500.00);
printf("\nM\t%d\t\t%.2f", course[1], course[1] * 2000.00);
printf("\nF\t%d\t\t%.2f", course[2], course[2] * 2500.00);
return 0;
}
|
the_stack_data/734383.c
|
#include <stdio.h>
void printarfuncao (int, int);
int main(void) {
int i, N, j;
while (1) {
scanf("%d", &N);
if (N == 0) break;
else {
int M [N] [N];
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (i == j) {
M [i] [j] = 1;
}
if (i > j) {
M [i] [j] = (i - j) + 1;
}
if (i < j) {
M [i] [j] = (j - i) + 1;
}
}
}
// for(i = 0; i < N; i++) {
// for(j = 1; j < N; j++) {
// M [i] [j] = (M [i] [j - 1]) + 1;
// }
// }
for(i = 0; i < N; i++) {
for(j = 0; j < N; j++) {
printf (" %d ", M [i] [j]);
}
printf ("\n");
}
}
}
}
|
the_stack_data/23576546.c
|
#include <stdio.h>
int f1() {
return 1;
}
int main() {
int a = f1();
printf("%d", a);
return 0;
}
|
the_stack_data/212643932.c
|
#include <stdio.h>
void main()
{
int i = 1, sum = 0;
while (i <= 30)
{
if (i % 2 == 0)
sum += i;
i++;
}
printf("Sum of even numbers from 1-30 is %d\n\n", sum);
}
|
the_stack_data/150143935.c
|
/*Write a function “insertion_sort” to implement Insertion Sort. Pass
array “arr” and size “n” as arguments from main.*/
#include<stdio.h>
void insertion_sort(int *, int );
int main()
{
int i, size;
printf("\nEnter the size of array : ");
scanf("%d", &size);
int arr[size];
printf("\nEnter the elements of array are : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
printf("\nElements of array are : ");
for(i=0; i<size; i++)
printf("%d, ", arr[i]);
insertion_sort(arr, size);
printf("\n\nSorted array using insertion sort : ");
for(i=0; i<size; i++)
printf("%d, ", arr[i]);
printf("\n\n");
return 0;
}
void insertion_sort(int *arr, int n)
{
int i, j, key;
for(i=0; i<n; i++)
{
key = arr[i];
j = i-1;
while((j >=0) && (arr[j] >key))
{
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
|
the_stack_data/154827247.c
|
#include <stdio.h>
int main()
{
int a, b; // Integer variables a and b
int *p; // Pointer p
a = 10; // Set a to 10
b = 20; // Set b to 20
p = &a; // Assign memory address to p
printf("Address of P is %d\n",p); // Print the memory address of p
printf("Value at p is %d\n",*p); // Print the value of p
*p = b; // Assign a new value to the pointer *p
printf("Address of P is %d\n",p); // The address of p itself does not change
printf("Value at p is %d\n",*p); // However the value of p has changed
}
|
the_stack_data/963403.c
|
/* Copyright (C) 2006 Free Software Foundation, Inc. */
/* Contributed by Carlos O'Donell on 2006-01-30 */
/* Test a division corner case where the expression simplifies
to a comparison, and the optab expansion is wrong. The optab
expansion emits a function whose return is unbiased and needs
adjustment. */
/* Origin: Carlos O'Donell <[email protected]> */
/* { dg-do run { target arm-*-*eabi* } } */
/* { dg-options "" } */
#include <stdlib.h>
#define BIG_CONSTANT 0xFFFFFFFF80000000ULL
int main (void)
{
unsigned long long OneULL = 1ULL;
unsigned long long result;
result = OneULL / BIG_CONSTANT;
if (result)
abort ();
exit (0);
}
|
the_stack_data/62637126.c
|
#include <stdio.h>
int stack[1009], stack_top = 0;
int queue[1009], queue_top = 0, queue_bot = 0;
int heap[1009], heap_top = 1, heap_size = 0;
void push_stack(int x);
void push_queue(int x);
void push_heap(int x);
int pop_stack(int *ret);
int pop_queue(int *ret);
int pop_heap(int *ret);
int main(void)
{
int N;
while (scanf("%d", &N) == 1) {
register int i;
int n, op;
int is_stack = 1, is_queue = 1, is_heap = 1;
stack_top = 0;
queue_top = 0, queue_bot = 0;
heap_top = 1, heap_size = 0;
for (i = 0; i < N; ++i) {
scanf("%d%d", &op, &n);
if (op == 1) {
push_stack(n);
push_queue(n);
push_heap(n);
} else {
int ret;
if (pop_stack(&ret) || ret != n)
is_stack = 0;
if (pop_queue(&ret) || ret != n)
is_queue = 0;
if (pop_heap(&ret) || ret != n)
is_heap = 0;
}
}
if (is_stack + is_queue + is_heap >= 2) {
puts("not sure");
} else if (is_stack + is_queue + is_heap == 0) {
puts("impossible");
} else if (is_stack) {
puts("stack");
} else if (is_queue) {
puts("queue");
} else if (is_heap) {
puts("priority queue");
}
}
return 0;
}
void push_stack(int x)
{
stack[stack_top++] = x;
}
void push_queue(int x)
{
queue[queue_top++] = x;
}
void push_heap(int x)
{
int pos = heap_top;
heap[heap_top++] = x;
while (pos > 1) {
int fa = pos / 2;
if (heap[pos] > heap[fa]) {
int t = heap[pos];
heap[pos] = heap[fa];
heap[fa] = t;
pos = fa;
} else {
break;
}
}
++heap_size;
}
int pop_stack(int *ret)
{
if (stack_top == 0)
return 1;
*ret = stack[--stack_top];
return 0;
}
int pop_queue(int *ret)
{
if (queue_top == queue_bot)
return 1;
*ret = queue[queue_bot++];
return 0;
}
int pop_heap(int *ret)
{
int pos = 1;
if (heap_size == 0)
return 1;
*ret = heap[pos];
heap[pos] = 0;
while (pos * 2 < heap_top) {
int l = pos * 2, r = pos * 2 + 1;
if (r < heap_top && heap[r] > heap[l]) {
int t = heap[r];
heap[r] = heap[pos];
heap[pos] = t;
pos = r;
} else {
int t = heap[l];
heap[l] = heap[pos];
heap[pos] = t;
pos = l;
}
}
--heap_size;
return 0;
}
|
the_stack_data/23574815.c
|
/*
* Counting lines, words, and character
*/
#include <stdio.h>
#define EARGS -1 /* error on command line */
#define EFILE -2 /* error on file */
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Error: Not enough parameters!\n");
return EARGS;
}
FILE *fs = fopen(argv[1], "r");
if (!fs)
return EFILE;
int c, nLine, nWord, nChar, state;
state = OUT;
nLine = nWord = nChar = 0;
while ((c = fgetc(fs)) != EOF)
{
++nChar;
if (c == '\n')
++nLine;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT)
{
state = IN;
++nWord;
}
}
++nLine; /* the last line does not contain an endline syntax (bug was found and fixed)*/
fclose(fs);
printf("Line count: %d\nWord count: %d\nChar count: %d\n", nLine, nWord, nChar);
return 0;
}
|
the_stack_data/170452230.c
|
/*
* Copyright (c) 2000, Intel Corporation
* All rights reserved.
*
* WARRANTY DISCLAIMER
*
* THESE MATERIALS ARE 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 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 THESE
* MATERIALS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Intel Corporation is the author of the Materials, and requests that all
* problem reports or change requests be submitted to it directly at
* http://developer.intel.com/opensource.
*/
void IEL_VER (void);
void IEL_VER () {}
|
the_stack_data/76293.c
|
/*
Exercise 5-1. As written, getint treats a + or - not followed by a digit as
a valid representation of zero. Fix it to push such a character back on the
input.
*/
#include <ctype.h>
#include <stdio.h>
int getch(void);
void ungetch(int);
int main(void) {
const int SIZE = 10;
int n, p, array[SIZE], getint(int *);
/* print the result */
for (n = 0; n < SIZE && (p = getint(&array[n])) != EOF; n++)
if (p != 0)
printf("%i\n", array[n]);
else
printf("non-digit\n");
return 0;
}
/* getint: get next integer from input into *pn */
int getint(int *pn)
{
int c, sign;
while (isspace(c = getch())) /* skip white space */
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
/* assuming there is nothing else to be done with the rest of the
input (with the non-digits), then ungetch is wrong here and leads
to loop with the next getch */
//ungetch(c);
return 0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
c = getch(); /* get one more character */
/* +/- followed by non-digit:
I would just skip both, but now to comply with the assignment: */
if (!isdigit(c)) {
ungetch(c);
return 0;
}
}
/* build the int */
for (*pn = 0; isdigit(c); c = getch())
*pn = 10 * *pn + (c - '0');
*pn *= sign;
/* the last c is non-digit - push it back */
if (c != EOF)
ungetch(c);
return c;
}
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
/* get a (possibly pushed-back) character */
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
/* push character back on input */
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
|
the_stack_data/1218914.c
|
// RUN: %clang_cc1 -fsyntax-only -verify %s
#define PLACE_IN_TCB(NAME) __attribute__ ((enforce_tcb(NAME)))
#define PLACE_IN_TCB_LEAF(NAME) __attribute__ ((enforce_tcb_leaf(NAME)))
void foo1 (void) PLACE_IN_TCB("bar");
void foo2 (void) PLACE_IN_TCB("bar");
void foo3 (void); // not in any TCB
void foo4 (void) PLACE_IN_TCB("bar2");
void foo5 (void) PLACE_IN_TCB_LEAF("bar");
void foo6 (void) PLACE_IN_TCB("bar2") PLACE_IN_TCB("bar");
void foo7 (void) PLACE_IN_TCB("bar3");
void foo8 (void) PLACE_IN_TCB("bar") PLACE_IN_TCB("bar2");
void foo9 (void);
void foo1(void) {
foo2(); // OK - function in same TCB
foo3(); // expected-warning {{calling 'foo3' is a violation of trusted computing base 'bar'}}
foo4(); // expected-warning {{calling 'foo4' is a violation of trusted computing base 'bar'}}
foo5(); // OK - in leaf node
foo6(); // OK - in multiple TCBs, one of which is the same
foo7(); // expected-warning {{calling 'foo7' is a violation of trusted computing base 'bar'}}
(void) __builtin_clz(5); // OK - builtins are excluded
}
// Normal use without any attributes works
void foo3(void) {
foo9(); // no-warning
}
void foo5(void) {
// all calls should be okay, function in TCB leaf
foo2(); // no-warning
foo3(); // no-warning
foo4(); // no-warning
}
void foo6(void) {
foo1(); // expected-warning {{calling 'foo1' is a violation of trusted computing base 'bar2'}}
foo4(); // expected-warning {{calling 'foo4' is a violation of trusted computing base 'bar'}}
foo8(); // no-warning
foo7(); // #1
// expected-warning@#1 {{calling 'foo7' is a violation of trusted computing base 'bar2'}}
// expected-warning@#1 {{calling 'foo7' is a violation of trusted computing base 'bar'}}
}
// Ensure that attribute merging works as expected across redeclarations.
void foo10(void) PLACE_IN_TCB("bar");
void foo10(void) PLACE_IN_TCB("bar2");
void foo10(void) PLACE_IN_TCB("bar3");
void foo10(void) {
foo1(); // #2
// expected-warning@#2 {{calling 'foo1' is a violation of trusted computing base 'bar2'}}
// expected-warning@#2 {{calling 'foo1' is a violation of trusted computing base 'bar3'}}
foo3(); // #3
// expected-warning@#3 {{calling 'foo3' is a violation of trusted computing base 'bar'}}
// expected-warning@#3 {{calling 'foo3' is a violation of trusted computing base 'bar2'}}
// expected-warning@#3 {{calling 'foo3' is a violation of trusted computing base 'bar3'}}
foo4(); // #4
// expected-warning@#4 {{calling 'foo4' is a violation of trusted computing base 'bar'}}
// expected-warning@#4 {{calling 'foo4' is a violation of trusted computing base 'bar3'}}
foo7(); // #5
// expected-warning@#5 {{calling 'foo7' is a violation of trusted computing base 'bar'}}
// expected-warning@#5 {{calling 'foo7' is a violation of trusted computing base 'bar2'}}
}
|
the_stack_data/589888.c
|
/*
This file is part of MAMBO, a low-overhead dynamic binary modification tool:
https://github.com/beehive-lab/mambo
Copyright 2015-2017 Guillermo Callaghan <guillermocallaghan at hotmail dot com>
Copyright 2016-2016 Cosmin Gorgovan <cosmin at linux-geek dot org>
Copyright 2017 The University of Manchester
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifdef __aarch64__
#include <assert.h>
#include <stdio.h>
#include "../../dbm.h"
#include "../../scanner_common.h"
#include "../../pie/pie-a64-decoder.h"
#include "../../pie/pie-a64-encoder.h"
#include "../../pie/pie-a64-field-decoder.h"
#include "../../api/helpers.h"
#define NOP_INSTRUCTION 0xD503201F
#define MIN_FSPACE 60
//#define DEBUG
#ifdef DEBUG
#define debug(...) fprintf(stderr, __VA_ARGS__)
#else
#define debug(...)
#endif
/*
* Macros for Pushing and Poping pair or single registers.
* ====== === ======= === ====== ==== == ====== =========
*
* PUSH-POP Pair of registers
*
* The "L" field defines if the instruction is a Load (L = 1) or a
* Store (L = 0).
* The field "type" controls the addressing mode.
* C4.3.15 Load/store register pair (post-indexed, page 205.
* C4.3.16 Load/store register pair (pre-indexed), page 206.
*
* A64_LDP_STP_encode (address, opc, V, type, L, imm7, Rt2, Rn, Rt)
* imm7:
* For the 64-bit post-index and 64-bit pre-index variant: is the signed
* immediate byte offset, a multiple of 8 in the range -512 to 504, encoded
* in the "imm7" field as <imm>/8. Page 668.
*/
#define a64_copy() *(write_p++) = *read_address;
#define a64_brk() *(write_p++) = 0xD4200000;
void a64_branch_helper(uint32_t *write_p, uint64_t target, bool link) {
int64_t difference = target - (uint64_t)write_p;
assert(((difference & 3) == 0)
&& (difference < 128*1024*1024 && difference >= -128*1024*1024));
a64_B_BL(&write_p, link ? 1 : 0, difference >> 2);
}
void a64_b_helper(uint32_t *write_p, uint64_t target) {
a64_branch_helper(write_p, target, false);
}
void a64_cc_branch(dbm_thread *thread_data, uint32_t *write_p, uint64_t target) {
a64_b_helper(write_p, target);
record_cc_link(thread_data, (uintptr_t)write_p, target);
}
void a64_bl_helper(uint32_t *write_p, uint64_t target) {
a64_branch_helper(write_p, target, true);
}
void a64_b_cond_helper(uint32_t *write_p, uint64_t target, mambo_cond cond) {
int64_t difference = target - (uint64_t)write_p;
assert(((difference & 3) == 0)
&& (difference < 1024*1024 && difference >= - 1024*1024));
a64_B_cond(&write_p, difference >> 2, cond);
}
int a64_cbz_cbnz_helper(uint32_t *write_p, bool cbnz, uint64_t target, uint32_t sf, uint32_t rt) {
int64_t difference = target - (uint64_t)write_p;
if (((difference & 3) != 0) ||
(difference >= 1024*1024 && difference < - 1024*1024)) {
return -1;
}
a64_CBZ_CBNZ(&write_p, sf, cbnz ? 1 : 0, difference >> 2, rt);
return 0;
}
void a64_cbz_helper(uint32_t *write_p, uint64_t target, uint32_t sf, uint32_t rt) {
int ret = a64_cbz_cbnz_helper(write_p, false, target, sf, rt);
assert(ret == 0);
}
void a64_cbnz_helper(uint32_t *write_p, uint64_t target, uint32_t sf, uint32_t rt) {
int ret = a64_cbz_cbnz_helper(write_p, true, target, sf, rt);
assert(ret == 0);
}
void a64_tbz_tbnz_helper(uint32_t *write_p, bool is_tbnz,
uint64_t target, enum reg reg, uint32_t bit) {
int64_t difference = target - (uint64_t)write_p;
assert(((difference & 3) == 0)
&& (difference < 32*1024 && difference >= - 32*1024));
a64_TBZ_TBNZ(&write_p, bit >> 5, is_tbnz ? 1 : 0, bit & 0x1F, difference >> 2, reg);
}
void a64_tbz_helper(uint32_t *write_p, uint64_t target, enum reg reg, uint32_t bit) {
a64_tbz_tbnz_helper(write_p, false, target, reg, bit);
}
void a64_tbnz_helper(uint32_t *write_p, uint64_t target, enum reg reg, uint32_t bit) {
a64_tbz_tbnz_helper(write_p, true, target, reg, bit);
}
/*
* Copy a value up to 64 bits to a register.
*/
void a64_copy_to_reg_64bits(uint32_t **write_p, enum reg reg, uint64_t value)
{
uint32_t first_half_word = value & 0xFFFF;
uint32_t second_half_word = (value >> 16) & 0xFFFF;
uint32_t third_half_word = (value >> 32) & 0xFFFF;
uint32_t fourth_half_word = (value >> 48) & 0xFFFF;
// MOVZ
a64_MOV_wide(write_p, 1, 2, 0, first_half_word, reg);
(*write_p)++;
if (second_half_word > 0) { // MOVK
a64_MOV_wide(write_p, 1, 3, 1, second_half_word, reg);
(*write_p)++;
}
if (third_half_word > 0) { // MOVK
a64_MOV_wide(write_p, 1, 3, 2, third_half_word, reg);
(*write_p)++;
}
if (fourth_half_word > 0) { // MOVK
a64_MOV_wide(write_p, 1, 3, 3, fourth_half_word, reg);
(*write_p)++;
}
}
void a64_branch_save_context (uint32_t **o_write_p)
{
uint32_t *write_p = *o_write_p;
a64_push_pair_reg(x0, x1);
*o_write_p = write_p;
}
void a64_branch_jump(dbm_thread *thread_data, uint32_t **o_write_p,
int basic_block, uint64_t target, uint32_t flags) {
/*
* +------------------------------+
* | STP |
* | MOV |
* | MOV |
* | B DISPATCHER |
* +------------------------------+
*/
uint32_t *write_p = *o_write_p;
debug("A64 branch target: 0x%lx\n", target);
if (flags & REPLACE_TARGET) {
a64_copy_to_reg_64bits(&write_p, x0, target);
}
if (flags & INSERT_BRANCH) {
a64_copy_to_reg_64bits(&write_p, x1, basic_block);
a64_b_helper(write_p, thread_data->dispatcher_addr);
write_p++;
}
*o_write_p = write_p;
}
void a64_branch_jump_cond(dbm_thread *thread_data, uint32_t **o_write_p, int basic_block,
uint64_t target, uint32_t *read_address, uint32_t cond) {
/*
* +-------------------------------+
* branch_cond -> | NOP |
* branch_1 -> | NOP |
* | |
* branch_2 -> | STP |
* | MOV X1, BB_ID |
* | |
* | B.op_cond SKIPPED |
* | |
* | MOV X0, TARGET |
* | B DISPATCHER |
* | |
* | SKIPPED: MOV X0, READ+4 |
* | B DISPATCHER |
* +-------------------------------+
*/
uint32_t *write_p = *o_write_p;
uint32_t *cond_branch;
debug("A64 branch: read_addr: %p, target: 0x%lx\n", read_address, target);
*write_p = NOP_INSTRUCTION;
write_p++;
*write_p = NOP_INSTRUCTION;
write_p++;
a64_branch_save_context(&write_p);
a64_copy_to_reg_64bits(&write_p, x1, basic_block);
cond_branch = write_p++;
a64_copy_to_reg_64bits(&write_p, x0, target);
a64_b_helper(write_p, thread_data->dispatcher_addr);
write_p++;
a64_b_cond_helper(cond_branch, (uint64_t)write_p, invert_cond(cond));
a64_copy_to_reg_64bits(&write_p, x0, (uint64_t)read_address + 4);
a64_b_helper(write_p, thread_data->dispatcher_addr);
write_p++;
*o_write_p = write_p;
}
void a64_branch_imm_reg(dbm_thread *thread_data, uint32_t **o_write_p,
int basic_block, a64_instruction inst, uint32_t *read_address) {
/*
* +------------------------------+
* cb(n)z_branch | NOP |
* b taken/not taken | NOP |
* | |
* b not taken/taken | STP |
* | |
* | TAKEN: [C/T](N)BZ SKIPPED |
* | |
* | MOV |
* | MOV |
* | B DISPATCHER |
* | |
* | SKIPPED: MOV |
* | MOV |
* | B DISPATCHER |
* +------------------------------+
*/
uint32_t *write_p = *o_write_p;
uint32_t *cbz_branch;
uint32_t sf, op, b5, b40, imm, rt, bit;
uint64_t branch_offset, target;
debug("A64 [c/t](n)bz: read_addr: %p, target: 0x%lx\n", read_address, target);
switch(inst) {
case A64_CBZ_CBNZ:
a64_CBZ_CBNZ_decode_fields(read_address, &sf, &op, &imm, &rt);
branch_offset = sign_extend64(19, imm) << 2;
#ifdef DBM_LINK_CBZ
thread_data->code_cache_meta[basic_block].exit_branch_type = cbz_a64;
thread_data->code_cache_meta[basic_block].branch_condition = op;
thread_data->code_cache_meta[basic_block].rn = (sf << 5) | rt;
#endif
break;
case A64_TBZ_TBNZ:
a64_TBZ_TBNZ_decode_fields(read_address, &b5, &op, &b40, &imm, &rt);
branch_offset = sign_extend64(14, imm) << 2;
bit = (b5 << 5) | b40;
#ifdef DBM_LINK_TBZ
thread_data->code_cache_meta[basic_block].exit_branch_type = tbz_a64;
thread_data->code_cache_meta[basic_block].branch_condition = op;
thread_data->code_cache_meta[basic_block].rn = (bit << 5) | rt ;
#endif
break;
}
target = (uint64_t)read_address + branch_offset;
thread_data->code_cache_meta[basic_block].exit_branch_addr = write_p;
thread_data->code_cache_meta[basic_block].branch_taken_addr = target;
thread_data->code_cache_meta[basic_block].branch_skipped_addr = (uint64_t)read_address + 4;
*write_p = NOP_INSTRUCTION;
write_p++;
*write_p = NOP_INSTRUCTION;
write_p++;
a64_branch_save_context(&write_p);
cbz_branch = write_p++;
// TAKEN
a64_branch_jump(thread_data, &write_p, basic_block, target,
REPLACE_TARGET | INSERT_BRANCH);
switch(inst) {
case A64_CBZ_CBNZ:
// Compare and Branch on [Not] Zero to SKIPPED
a64_cbz_cbnz_helper(cbz_branch, op^1, (uint64_t)write_p, sf, rt);
break;
case A64_TBZ_TBNZ:
// Test bit and Branch on [Not] Zero to SKIPPED
a64_tbz_tbnz_helper(cbz_branch, op^1, (uint64_t)write_p, rt, bit);
break;
}
// SKIPPED
a64_branch_jump(thread_data, &write_p, basic_block, (uint64_t)read_address + 4,
REPLACE_TARGET | INSERT_BRANCH);
*o_write_p = write_p;
}
void a64_check_free_space(dbm_thread *thread_data, uint32_t **write_p,
uint32_t **data_p, uint32_t size, int cur_block) {
int basic_block;
if ((((uint64_t)*write_p) + size) >= (uint64_t)*data_p) {
basic_block = allocate_bb(thread_data);
thread_data->code_cache_meta[basic_block].actual_id = cur_block;
if ((uint32_t *)&thread_data->code_cache->blocks[basic_block] != *data_p) {
a64_b_helper(*write_p, (uint64_t)&thread_data->code_cache->blocks[basic_block]);
*write_p = (uint32_t *)&thread_data->code_cache->blocks[basic_block];
}
*data_p = (uint32_t *)&thread_data->code_cache->blocks[basic_block];
*data_p += BASIC_BLOCK_SIZE;
}
}
void pass1_a64(uint32_t *read_address, branch_type *bb_type) {
*bb_type = unknown;
while(*bb_type == unknown) {
a64_instruction instruction = a64_decode(read_address);
switch(instruction) {
case A64_B_BL:
*bb_type = uncond_imm_a64;
break;
case A64_CBZ_CBNZ:
*bb_type = cbz_a64;
break;
case A64_B_COND:
*bb_type = cond_imm_a64;
break;
case A64_TBZ_TBNZ:
*bb_type = tbz_a64;
break;
case A64_BR:
case A64_BLR:
case A64_RET:
*bb_type = uncond_branch_reg;
break;
case A64_INVALID:
return;
}
read_address++;
}
}
bool a64_scanner_deliver_callbacks(dbm_thread *thread_data, mambo_cb_idx cb_id, uint32_t **o_read_address,
a64_instruction inst, uint32_t **o_write_p, uint32_t **o_data_p,
int basic_block, cc_type type, bool allow_write, bool *stop) {
bool replaced = false;
#ifdef PLUGINS_NEW
if (global_data.free_plugin > 0) {
uint32_t *write_p = *o_write_p;
uint32_t *data_p = *o_data_p;
uint32_t *read_address = *o_read_address;
mambo_cond cond = AL;
if (inst == A64_B_COND) {
uint32_t tmp;
a64_B_cond_decode_fields(read_address, &tmp, &cond);
}
mambo_context ctx;
set_mambo_context_code(&ctx, thread_data, cb_id, type, basic_block, A64_INST, inst, cond, read_address, write_p, data_p, stop);
for (int i = 0; i < global_data.free_plugin; i++) {
if (global_data.plugins[i].cbs[cb_id] != NULL) {
ctx.code.write_p = write_p;
ctx.code.data_p = data_p;
ctx.plugin_id = i;
ctx.code.replace = false;
ctx.code.available_regs = ctx.code.pushed_regs;
global_data.plugins[i].cbs[cb_id](&ctx);
if (allow_write) {
if (replaced && (write_p != ctx.code.write_p || ctx.code.replace)) {
fprintf(stderr, "MAMBO API WARNING: plugin %d added code for overridden"
"instruction (%p).\n", i, read_address);
}
if (ctx.code.replace) {
if (cb_id == PRE_INST_C) {
replaced = true;
} else {
fprintf(stderr, "MAMBO API WARNING: plugin %d set replace_inst for "
"a disallowed event (at %p).\n", i, read_address);
}
}
assert(count_bits(ctx.code.pushed_regs) == ctx.code.plugin_pushed_reg_count);
if (allow_write && ctx.code.pushed_regs) {
emit_pop(&ctx, ctx.code.pushed_regs);
}
write_p = ctx.code.write_p;
data_p = ctx.code.data_p;
a64_check_free_space(thread_data, &write_p, &data_p, MIN_FSPACE, basic_block);
} else {
assert(ctx.code.write_p == write_p);
assert(ctx.code.data_p == data_p);
}
}
}
if (cb_id == PRE_BB_C) {
watched_functions_t *wf = &global_data.watched_functions;
for (int i = 0; i < wf->funcp_count; i++) {
if (read_address == wf->funcps[i].addr) {
_function_callback_wrapper(&ctx, wf->funcps[i].func);
if (ctx.code.replace) {
read_address = ctx.code.read_address;
}
write_p = ctx.code.write_p;
data_p = ctx.code.data_p;
a64_check_free_space(thread_data, &write_p, &data_p, MIN_FSPACE, basic_block);
}
}
}
*o_write_p = write_p;
*o_data_p = data_p;
*o_read_address = read_address;
}
#endif
return replaced;
}
void a64_inline_hash_lookup(dbm_thread *thread_data, int basic_block, uint32_t **o_write_p,
uint32_t *read_address, enum reg rn, bool link, bool set_meta) {
/*
* Indirect Branch LookUp
* ======== ====== ======
*
* STP X0, X1, [SP, #-16]!
* STP X2, [SP, #-16]! **
* MOV X1, rn ** rn = X1
* MOV LR, read_address + 4 ##
* MOV X0, #hash_table
* AND Xtmp, rn, #(hash_mask << 2)
* ADD X0, X0, Xtmp, LSL #2
* loop:
* LDR Xtmp, [X0], #16
* CBZ Xtmp, not_found
* SUB Xtmp, Xtmp, rn
* CBNZ Xtmp, loop
* LDR X0, [X0, #-8]
* LDR X2, [SP], #16 **
* BR X0
* not_found:
* MOV X0, rn
* MOV X1, #bb
* LDR X2, [SP], #16 **
* B dispatcher
*
* ** if rn is X0, X1 or (BLR LR)
* ## for BLR
*/
uint32_t *write_p = *o_write_p;
uint32_t *loop;
uint32_t *branch_to_not_found;
uint32_t reg_spc, reg_tmp;
bool use_x2 = false;
if ((rn == x0) || (rn == x1) || (link && rn == lr)) {
reg_spc = x1;
reg_tmp = x2;
use_x2 = true;
} else {
reg_spc = rn;
reg_tmp = x1;
}
if (set_meta) {
thread_data->code_cache_meta[basic_block].rn = reg_spc;
}
a64_push_pair_reg(x0, x1);
if (use_x2) {
a64_push_reg(x2);
if (rn != reg_spc) {
a64_logical_reg(&write_p, 1, 1, 0, 0, rn, 0, xzr, reg_spc);
write_p++;
}
}
if (link) {
// MOV LR, read_address+4
a64_copy_to_reg_64bits(&write_p, lr, (uint64_t)read_address + 4);
}
a64_copy_to_reg_64bits(&write_p, x0,
(uint64_t)&thread_data->entry_address.entries);
a64_logical_immed(&write_p, 1, 0, 1, 62, 18, reg_spc, reg_tmp);
write_p++;
a64_ADD_SUB_shift_reg(&write_p, 1, 0, 0, 0, reg_tmp, 0x2, x0, x0);
write_p++;
loop = write_p;
a64_LDR_STR_immed(&write_p, 3, 0, 1, 16, 1, x0, reg_tmp);
write_p++;
branch_to_not_found = write_p++;
a64_ADD_SUB_shift_reg(&write_p, 1, 1, 0, 0, reg_spc, 0, reg_tmp, reg_tmp);
write_p++;
a64_cbnz_helper(write_p, (uint64_t)loop, 1, reg_tmp);
write_p++;
a64_LDR_STR_immed(&write_p, 3, 0, 1, -8, 0, x0, x0);
write_p++;
if (use_x2) {
a64_pop_reg(x2);
}
a64_BR(&write_p, x0);
write_p++;
a64_cbz_helper(branch_to_not_found, (uint64_t)write_p, 1, reg_tmp);
a64_logical_reg(&write_p, 1, 1, 0, 0, reg_spc, 0, xzr, x0);
write_p++;
a64_copy_to_reg_64bits(&write_p, x1, basic_block);
if (use_x2) {
a64_pop_reg(x2);
}
a64_b_helper(write_p, (uint64_t)thread_data->dispatcher_addr);
write_p++;
*o_write_p = write_p;
}
size_t scan_a64(dbm_thread *thread_data, uint32_t *read_address,
int basic_block, cc_type type, uint32_t *write_p) {
bool stop = false;
uint32_t *start_scan = read_address, *bb_entry = read_address;
uint32_t *data_p;
uint32_t *start_address;
enum reg spilled_reg;
uint64_t imm;
uint32_t immlo, immhi, imm14, imm16, imm19, imm26;
uint32_t CRn, CRm, Rd, Rn, Rt;
uint32_t b5, b40, cond, hw, o0, op, op1, op2, opc, R, sf, V;
uint64_t branch_offset;
uint64_t PC_relative_address;
uint64_t size;
uint64_t target;
bool TPIDR_EL0;
if (write_p == NULL) {
write_p = (uint32_t *) &thread_data->code_cache->blocks[basic_block];
}
start_address = write_p;
if (type == mambo_bb) {
data_p = write_p + BASIC_BLOCK_SIZE;
} else { // mambo_trace
data_p = (uint32_t *)&thread_data->code_cache->traces + (TRACE_CACHE_SIZE / 4);
thread_data->code_cache_meta[basic_block].free_b = 0;
}
/*
* On context switches registers X0 and X1 are used to store the target
* address and the Basic Block number respectively. Before
* overwriting the values of these two registers they are pushed to the
* Stack. This means that at the start of every Basic Block X0 and X1 have
* to be popped from the Stack. The same is true for trace entries, however
* trace fragments do not need a pop instruction.
*/
if (type != mambo_trace) {
a64_pop_pair_reg(x0, x1);
}
#ifdef DBM_TRACES
branch_type bb_type;
pass1_a64(read_address, &bb_type);
if (type == mambo_bb && bb_type != uncond_branch_reg && bb_type != unknown) {
a64_push_pair_reg(x1, x30);
a64_copy_to_reg_64bits(&write_p, x1, (int)basic_block);
a64_bl_helper(write_p, thread_data->trace_head_incr_addr);
write_p++;
a64_pop_pair_reg(x1, x30);
}
#endif
a64_scanner_deliver_callbacks(thread_data, PRE_FRAGMENT_C, &read_address, -1,
&write_p, &data_p, basic_block, type, true, &stop);
a64_scanner_deliver_callbacks(thread_data, PRE_BB_C, &read_address, -1,
&write_p, &data_p, basic_block, type, true, &stop);
while(!stop) {
debug("A64 scan read_address: %p, w: : %p, bb: %d\n", read_address, write_p, basic_block);
a64_instruction inst = a64_decode(read_address);
debug(" instruction enum: %d\n", (inst == A64_INVALID) ? -1 : inst);
debug(" instruction word: 0x%x\n", *read_address);
#ifdef PLUGINS_NEW
bool skip_inst = a64_scanner_deliver_callbacks(thread_data, PRE_INST_C, &read_address, inst,
&write_p, &data_p, basic_block, type, true, &stop);
if (!skip_inst) {
#endif
switch (inst){
case A64_CBZ_CBNZ:
a64_branch_imm_reg(thread_data, &write_p, basic_block, inst, read_address);
stop = true;
break;
case A64_B_COND:
a64_B_cond_decode_fields(read_address, &imm19, &cond);
branch_offset = sign_extend64(19, imm19) << 2;
target = (uint64_t)read_address + branch_offset;
#ifdef DBM_LINK_COND_IMM
// Mark this as the beggining of code emulating B.cond
thread_data->code_cache_meta[basic_block].exit_branch_type = cond_imm_a64;
thread_data->code_cache_meta[basic_block].exit_branch_addr = write_p;
thread_data->code_cache_meta[basic_block].branch_taken_addr = target;
thread_data->code_cache_meta[basic_block].branch_skipped_addr = (uint64_t)read_address + 4;
thread_data->code_cache_meta[basic_block].branch_condition = cond;
thread_data->code_cache_meta[basic_block].branch_cache_status = 0;
#endif
a64_branch_jump_cond(thread_data, &write_p, basic_block, target, read_address, cond);
stop = true;
break;
case A64_SVC:
a64_push_pair_reg(x29, x30);
a64_copy_to_reg_64bits(&write_p, x29, (uint64_t)read_address + 4);
a64_bl_helper(write_p, thread_data->syscall_wrapper_addr);
write_p++;
a64_pop_pair_reg(x0, x1);
a64_scanner_deliver_callbacks(thread_data, POST_BB_C, &bb_entry, -1,
&write_p, &data_p, basic_block, type, false, &stop);
// set the correct address for the PRE_BB_C event
read_address++;
bb_entry = read_address;
a64_scanner_deliver_callbacks(thread_data, PRE_BB_C, &read_address, -1,
&write_p, &data_p, basic_block, type, true, &stop);
read_address--;
break;
case A64_MRS_MSR_REG:
/*
* The R variable defines if the instruction is MSR (R = 0) or
* MRS (R = 1)
* Page 617 MRS and 620 MSR
*
* MRS
* Move System Register allows the PE to read an AArch64 System
* register into a general-purpose register.
*
* MSR (immediate)
* Move immediate value to Special Register moves an immediate
* value to selected bits of the PSTATE, namely D, A, I, F, and
* SP. For more information, see PSTATE.
*
* MSR (register)
* Move general-purpose register to System Register allows the PE
* to write an AArch64 System register from a general-purpose
* register.
*
* TPIDR_EL0 (page 2032)
* op0 op1 CRn CRm op2
* 11 011 1101 0000 010
*/
a64_MRS_MSR_reg_decode_fields(read_address, &R, &o0, &op1, &CRn, &CRm, &op2, &Rt);
TPIDR_EL0 = (o0 == 1) && (op1 == 3) && (CRn == 13) && (CRm == 0) && (op2 == 2);
if (TPIDR_EL0) {
if (Rt == x0) {
spilled_reg = x1;
} else {
spilled_reg = x0;
}
a64_push_reg(spilled_reg);
a64_copy_to_reg_64bits(&write_p, spilled_reg, (uint64_t)&thread_data->tls);
if (R == 0) { // MSR
a64_LDR_STR_immed(&write_p, 3, 0, 0, 0, 0, spilled_reg, Rt);
write_p++;
} else { // MRS
a64_LDR_STR_immed(&write_p, 3, 0, 1, 0, 0, spilled_reg, Rt);
write_p++;
}
a64_pop_reg(spilled_reg);
break;
} else {
a64_copy();
}
break;
case A64_TBZ_TBNZ:
a64_branch_imm_reg(thread_data, &write_p, basic_block, inst, read_address);
stop = true;
break;
case A64_B_BL:
a64_B_BL_decode_fields(read_address, &op, &imm26);
if (op == 1) { // Branch Link
a64_copy_to_reg_64bits(&write_p, lr, (uint64_t)read_address + 4);
}
branch_offset = sign_extend64(26, imm26) << 2;
target = (uint64_t)read_address + branch_offset;
#ifdef DBM_LINK_UNCOND_IMM
thread_data->code_cache_meta[basic_block].exit_branch_type = uncond_imm_a64;
thread_data->code_cache_meta[basic_block].exit_branch_addr = write_p;
thread_data->code_cache_meta[basic_block].branch_taken_addr = target;
*write_p = NOP_INSTRUCTION; // Reserves space for linking branch.
write_p++;
#endif
a64_branch_save_context(&write_p);
a64_branch_jump(thread_data, &write_p, basic_block, target,
REPLACE_TARGET | INSERT_BRANCH);
stop = true;
//while(1);
break;
case A64_BR:
case A64_BLR:
case A64_RET:
a64_BR_decode_fields(read_address, &Rn);
#ifdef DBM_INLINE_HASH
a64_check_free_space(thread_data, &write_p, &data_p, 88, basic_block);
#endif
thread_data->code_cache_meta[basic_block].exit_branch_type = uncond_branch_reg;
thread_data->code_cache_meta[basic_block].exit_branch_addr = write_p;
thread_data->code_cache_meta[basic_block].rn = Rn;
#ifndef DBM_INLINE_HASH
a64_branch_save_context(&write_p);
// MOV X0, Rn (Alias of ORR X0, Rn, XZR)
a64_logical_reg(&write_p, 1, 1, 0, 0, Rn, 0, xzr, x0);
write_p++;
if (inst == A64_BLR) {
// MOV LR, read_address+4
a64_copy_to_reg_64bits(&write_p, lr, (uint64_t)read_address + 4);
}
a64_branch_jump(thread_data, &write_p, basic_block, 0, INSERT_BRANCH);
#else
a64_inline_hash_lookup(thread_data, basic_block, &write_p, read_address, Rn, (inst == A64_BLR), true);
#endif
stop = true;
break;
case A64_LDR_LIT:
/*
* LDR (literal) calculates an address from the PC value and an
* immediate offset, loads a word from memory, and writes it to a
* register.
*
* LOAD LITERAL
* ----------------------------------------------------------------
* opc V Instruction Variant
* ----------------------------------------------------------------
* 00 0 LDR (literal) 32-bit variant on page C6-527
* 01 0 LDR (literal) 64-bit variant on page C6-527
* 10 0 LDRSW (literal) -
* 11 0 PRFM (literal) -
*
* 00 1 LDR (literal, SIMD&FP) 32-bit variant on page C7-1027
* 01 1 LDR (literal, SIMD&FP) 64-bit variant on page C7-1027
* 10 1 LDR (literal, SIMD&FP) 128-bit variant on page C7-1027
*/
a64_LDR_lit_decode_fields(read_address, &opc, &V, &imm19, &Rt);
uint64_t offset = sign_extend64(19, imm19) << 2;
PC_relative_address = (uint64_t)read_address + offset;
if (V== 0) {
switch(opc) {
case 0: // LDR literal 32-bit variant
a64_copy_to_reg_64bits(&write_p, Rt, PC_relative_address);
a64_LDR_STR_unsigned_immed(&write_p, 2, V, 1, 0, Rt, Rt);
write_p++;
break;
case 1: // LDR literal 64-bit variant
a64_copy_to_reg_64bits(&write_p, Rt, PC_relative_address);
a64_LDR_STR_unsigned_immed(&write_p, 3, V, 1, 0, Rt, Rt);
write_p++;
break;
case 2: // LDR Signed Word (literal)
a64_copy_to_reg_64bits(&write_p, Rt, PC_relative_address);
a64_LDR_STR_unsigned_immed(&write_p, 2, V, 2, 0, Rt, Rt);
write_p++;
break;
case 3: // PRFM Prefetch
a64_push_reg(x0);
a64_copy_to_reg_64bits(&write_p, x0, PC_relative_address);
a64_LDR_STR_unsigned_immed(&write_p, 3, V, 2, 0, x0, Rt);
write_p++;
a64_pop_reg(x0);
break;
}
} else if (V == 1) {
switch(opc) {
case 0: // LDR (literal, SIMD&FP) 32-bit variant
size = 2;
opc = 1;
break;
case 1: // LDR (literal, SIMD&FP) 64-bit variant
size = 3;
opc = 1;
break;
case 2: // LDR (literal, SIMD&FP) 128-bit variant
size = 0;
opc = 3;
break;
default:
printf("unallocated encoding\n");
while(1);
}
a64_push_reg(x0);
a64_copy_to_reg_64bits(&write_p, x0, PC_relative_address);
a64_LDR_STR_unsigned_immed(&write_p, size, V, opc, 0, x0, Rt);
write_p++;
a64_pop_reg(x0);
}
break;
case A64_ADR:
/*
* The ADR instruction needs to be translated as a MOV instruction.
* Otherwise it will point to the wrong address (somewhere
* in the code cache).
*/
a64_ADR_decode_fields(read_address, &op, &immlo, &immhi, &Rd);
imm = (immhi << 2) | immlo;
if (op == 0){ // ADR
imm = sign_extend64(21, imm);
PC_relative_address = (uint64_t)read_address;
} else { // ADRP
imm = sign_extend64(21, imm) << 12;
PC_relative_address = (uint64_t)read_address & ~(0xFFF);
}
PC_relative_address += imm;
a64_copy_to_reg_64bits(&write_p, Rd, PC_relative_address);
break;
case A64_HVC:
case A64_BRK:
case A64_HINT:
case A64_CLREX:
case A64_DSB:
case A64_DMB:
case A64_ISB:
case A64_SYS:
case A64_LDX_STX:
case A64_LDP_STP:
case A64_LDR_STR_IMMED:
case A64_LDR_STR_REG:
case A64_LDR_STR_UNSIGNED_IMMED:
case A64_LDX_STX_MULTIPLE:
case A64_LDX_STX_MULTIPLE_POST:
case A64_LDX_STX_SINGLE:
case A64_LDX_STX_SINGLE_POST:
case A64_ADD_SUB_IMMED:
case A64_BFM:
case A64_EXTR:
case A64_LOGICAL_IMMED:
case A64_MOV_WIDE:
case A64_ADD_SUB_EXT_REG:
case A64_ADD_SUB_SHIFT_REG:
case A64_ADC_SBC:
case A64_CCMP_CCMN_IMMED:
case A64_CCMP_CCMN_REG:
case A64_COND_SELECT:
case A64_DATA_PROC_REG1:
case A64_DATA_PROC_REG2:
case A64_DATA_PROC_REG3:
case A64_LOGICAL_REG:
case A64_SIMD_ACROSS_LANE:
case A64_SIMD_COPY:
case A64_SIMD_EXTRACT:
case A64_SIMD_MODIFIED_IMMED:
case A64_SIMD_PERMUTE:
case A64_SIMD_SCALAR_COPY:
case A64_SIMD_SCALAR_PAIRWISE:
case A64_SIMD_SCALAR_SHIFT_IMMED:
case A64_SIMD_SCALAR_THREE_DIFF:
case A64_SIMD_SCALAR_THREE_SAME:
case A64_SIMD_SHIFT_IMMED:
case A64_SIMD_TABLE_LOOKUP:
case A64_SIMD_THREE_DIFF:
case A64_SIMD_THREE_SAME:
case A64_SIMD_SCALAR_TWO_REG:
case A64_SIMD_SCALAR_X_INDEXED:
case A64_SIMD_TWO_REG:
case A64_SIMD_X_INDEXED:
case A64_CRYPTO_AES:
case A64_CRYPTO_SHA_REG3:
case A64_CRYPTO_SHA_REG2:
case A64_FCMP:
case A64_FCCMP:
case A64_FCSEL:
case A64_FLOAT_REG1:
case A64_FLOAT_REG2:
case A64_FLOAT_REG3:
case A64_FMOV_IMMED:
case A64_FLOAT_CVT_FIXED:
case A64_FLOAT_CVT_INT:
a64_copy();
break;
case A64_INVALID:
if (read_address != start_scan) {
// Branch to lookup_or_stub(thread_data, (uintptr_t)read_address);
a64_branch_save_context(&write_p);
a64_branch_jump(thread_data, &write_p, basic_block, (uint64_t)read_address,
REPLACE_TARGET | INSERT_BRANCH);
stop = true;
debug("WARN: deferred scanning because of unknown instruction at: %p\n", read_address);
} else {
fprintf(stderr, "\nMAMBO: Unknown A64 instruction: %d (0x%x) at %p\n"
"Copying it unmodified, but future problems are possible\n"
"Report crashes at https://github.com/beehive-lab/mambo\n\n",
inst, *read_address, read_address);
a64_copy();
}
break;
default:
fprintf(stderr, "Unhandled A64 instruction: %d at %p\n", inst, read_address);
while(1);
exit(EXIT_FAILURE);
}
#ifdef PLUGINS_NEW
} // if (!skip_inst)
#endif
if (data_p <= write_p) {
fprintf(stderr, "%d, inst: %p, :write: %p\n", inst, data_p, write_p);
while(1);
}
if (!stop) {
a64_check_free_space(thread_data, &write_p, &data_p, MIN_FSPACE, basic_block);
}
#ifdef PLUGINS_NEW
a64_scanner_deliver_callbacks(thread_data, POST_INST_C, &read_address, inst, &write_p, &data_p, basic_block, type, !stop, &stop);
#endif
read_address++;
} // while(!stop)
a64_scanner_deliver_callbacks(thread_data, POST_BB_C, &bb_entry, -1,
&write_p, &data_p, basic_block, type, false, &stop);
a64_scanner_deliver_callbacks(thread_data, POST_FRAGMENT_C, &start_scan, -1,
&write_p, &data_p, basic_block, type, false, &stop);
return ((write_p - start_address + 1) * sizeof(*write_p));
}
#endif // __aarch64__
|
the_stack_data/89699.c
|
# include <stdlib.h>
# include <stdio.h>
# include <math.h>
#define R8EPSILON 2.220446049250313E-016
inline double r8_abs (double x) { return x < 0 ? -x : x; }
int abwe1 ( int n, int m, double eps, double coef2,
int even, double b[], double *x, double *w ) {
/*
Purpose:
ABWE1 calculates a Kronrod abscissa and weight.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 August 2010
Author:
Original FORTRAN77 version by Robert Piessens, Maria Branders.
C version by John Burkardt.
Reference:
Robert Piessens, Maria Branders,
A Note on the Optimal Addition of Abscissas to Quadrature Formulas
of Gauss and Lobatto,
Mathematics of Computation,
Volume 28, Number 125, January 1974, pages 135-139.
Parameters:
Input, int N, the order of the Gauss rule.
Input, int M, the value of ( N + 1 ) / 2.
Input, double EPS, the requested absolute accuracy of the
abscissas.
Input, double COEF2, a value needed to compute weights.
Input, int EVEN, is TRUE if N is even.
Input, double B[M+1], the Chebyshev coefficients.
Input/output, double *X; on input, an estimate for
the abscissa, and on output, the computed abscissa.
Output, double *W, the weight.
*/
double ai;
double b0;
double b1;
double b2;
double d0;
double d1;
double d2;
double delta;
double dif;
double f;
double fd;
int i;
int iter;
int k;
int ka;
double yy;
if ( *x == 0.0 ) ka = 1;
else ka = 0;
/* Iterative process for the computation of a Kronrod abscissa. */
for ( iter = 1; iter <= 50; iter++ ) {
b1 = 0.0;
b2 = b[m];
yy = 4.0 * (*x) * (*x) - 2.0;
d1 = 0.0;
if ( even ) {
ai = m + m + 1;
d2 = ai * b[m];
dif = 2.0;
} else {
ai = m + 1;
d2 = 0.0;
dif = 1.0;
}
for ( k = 1; k <= m; k++ ) {
ai = ai - dif;
i = m - k + 1;
b0 = b1;
b1 = b2;
d0 = d1;
d1 = d2;
b2 = yy * b1 - b0 + b[i-1];
if ( !even ) i = i + 1;
d2 = yy * d1 - d0 + ai * b[i-1];
}
if ( even ) {
f = ( *x ) * ( b2 - b1 );
fd = d2 + d1;
} else {
f = 0.5 * ( b2 - b0 );
fd = 4.0 * ( *x ) * d2;
}
/* Newton correction. */
delta = f / fd;
*x = *x - delta;
if ( ka == 1 ) break;
if ( r8_abs ( delta ) <= eps ) ka = 1;
}
/* Catch non-convergence. */
if ( ka != 1 ) return 0;
/* Computation of the weight. */
d0 = 1.0;
d1 = *x;
ai = 0.0;
for ( k = 2; k <= n; k++ ) {
ai = ai + 1.0;
d2 = ( ( ai + ai + 1.0 ) * ( *x ) * d1 - ai * d0 ) / ( ai + 1.0 );
d0 = d1;
d1 = d2;
}
*w = coef2 / ( fd * d2 );
return 1;
}
int abwe2 ( int n, int m, double eps, double coef2, int even,
double b[], double *x, double *w1, double *w2 ) {
/*
Purpose:
ABWE2 calculates a Gaussian abscissa and two weights.
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
30 April 2013
Author:
Original FORTRAN77 version by Robert Piessens, Maria Branders.
C version by John Burkardt.
Reference:
Robert Piessens, Maria Branders,
A Note on the Optimal Addition of Abscissas to Quadrature Formulas
of Gauss and Lobatto,
Mathematics of Computation,
Volume 28, Number 125, January 1974, pages 135-139.
Parameters:
Input, int N, the order of the Gauss rule.
Input, int M, the value of ( N + 1 ) / 2.
Input, double EPS, the requested absolute accuracy of the
abscissas.
Input, double COEF2, a value needed to compute weights.
Input, int EVEN, is TRUE if N is even.
Input, double B[M+1], the Chebyshev coefficients.
Input/output, double *X; on input, an estimate for
the abscissa, and on output, the computed abscissa.
Output, double *W1, the Gauss-Kronrod weight.
Output, double *W2, the Gauss weight.
*/
double ai;
double an;
double delta;
int i;
int iter;
int k;
int ka;
double p0;
double p1;
double p2;
double pd0;
double pd1;
double pd2;
double yy;
if ( *x == 0.0 ) ka = 1;
else ka = 0;
/* Iterative process for the computation of a Gaussian abscissa. */
for ( iter = 1; iter <= 50; iter++ ) {
p0 = 1.0;
p1 = *x;
pd0 = 0.0;
pd1 = 1.0;
/* When N is 1, we need to initialize P2 and PD2 to avoid problems with DELTA. */
if ( n <= 1 ) {
if ( R8EPSILON < r8_abs ( *x ) ) {
p2 = ( 3.0 * ( *x ) * ( *x ) - 1.0 ) / 2.0;
pd2 = 3.0 * ( *x );
} else {
p2 = 3.0 * ( *x );
pd2 = 3.0;
}
}
ai = 0.0;
for ( k = 2; k <= n; k++ ) {
ai = ai + 1.0;
p2 = ( ( ai + ai + 1.0 ) * (*x) * p1 - ai * p0 ) / ( ai + 1.0 );
pd2 = ( ( ai + ai + 1.0 ) * ( p1 + (*x) * pd1 ) - ai * pd0 )
/ ( ai + 1.0 );
p0 = p1;
p1 = p2;
pd0 = pd1;
pd1 = pd2;
}
/* Newton correction. */
delta = p2 / pd2;
*x = *x - delta;
if ( ka == 1 ) break;
if ( r8_abs ( delta ) <= eps ) ka = 1;
}
/* Catch non-convergence. */
if ( ka != 1 ) return 0;
/* Computation of the weight. */
an = n;
*w2 = 2.0 / ( an * pd2 * p0 );
p1 = 0.0;
p2 = b[m];
yy = 4.0 * (*x) * (*x) - 2.0;
for ( k = 1; k <= m; k++ ) {
i = m - k + 1;
p0 = p1;
p1 = p2;
p2 = yy * p1 - p0 + b[i-1];
}
if ( even ) *w1 = *w2 + coef2 / ( pd2 * (*x) * ( p2 - p1 ) );
else *w1 = *w2 + 2.0 * coef2 / ( pd2 * ( p2 - p0 ) );
return 1;
}
int kronrod ( int n, double eps, double x[], double w1[], double w2[] ) {
/******************************************************************************/
/*
Purpose:
KRONROD adds N+1 points to an N-point Gaussian rule.
Discussion:
This subroutine calculates the abscissas and weights of the 2N+1
point Gauss Kronrod quadrature formula which is obtained from the
N point Gauss quadrature formula by the optimal addition of N+1 points.
The optimally added points are called Kronrod abscissas. The
abscissas and weights for both the Gauss and Gauss Kronrod rules
are calculated for integration over the interval [-1,+1].
Since the quadrature formula is symmetric with respect to the origin,
only the nonnegative abscissas are calculated.
Note that the code published in Mathematics of Computation
omitted the definition of the variable which is here called COEF2.
Storage:
Given N, let M = ( N + 1 ) / 2.
The Gauss-Kronrod rule will include 2*N+1 points. However, by symmetry,
only N + 1 of them need to be listed.
The arrays X, W1 and W2 contain the nonnegative abscissas in decreasing
order, and the weights of each abscissa in the Gauss-Kronrod and
Gauss rules respectively. This means that about half the entries
in W2 are zero.
For instance, if N = 3, the output is:
I X W1 W2
1 0.960491 0.104656 0.000000
2 0.774597 0.268488 0.555556
3 0.434244 0.401397 0.000000
4 0.000000 0.450917 0.888889
and if N = 4, (notice that 0 is now a Kronrod abscissa)
the output is
I X W1 W2
1 0.976560 0.062977 0.000000
2 0.861136 0.170054 0.347855
3 0.640286 0.266798 0.000000
4 0.339981 0.326949 0.652145
5 0.000000 0.346443 0.000000
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
03 August 2010
Author:
Original FORTRAN77 version by Robert Piessens, Maria Branders.
C version by John Burkardt.
Reference:
Robert Piessens, Maria Branders,
A Note on the Optimal Addition of Abscissas to Quadrature Formulas
of Gauss and Lobatto,
Mathematics of Computation,
Volume 28, Number 125, January 1974, pages 135-139.
Parameters:
Input, int N, the order of the Gauss rule.
Input, double EPS, the requested absolute accuracy of the
abscissas.
Output, double X[N+1], the abscissas.
Output, double W1[N+1], the weights for
the Gauss-Kronrod rule.
Output, double W2[N+1], the weights for
the Gauss rule.
*/
double ak;
double an;
double *b;
double bb;
double c;
double coef;
double coef2;
double d;
int even;
int i;
int k;
int l;
int ll;
int m;
double s;
double *tau;
double x1;
double xx;
double y;
b = ( double * ) malloc ( (((n+1)/2)+1) * sizeof ( double ) );
tau = ( double * ) malloc ( ( (n+1)/2 ) * sizeof ( double ) );
m = ( n + 1 ) / 2;
even = ( 2 * m == n );
d = 2.0;
an = 0.0;
for ( k = 1; k <= n; k++ ) {
an = an + 1.0;
d = d * an / ( an + 0.5 );
}
/* Calculation of the Chebyshev coefficients of the orthogonal polynomial. */
tau[0] = ( an + 2.0 ) / ( an + an + 3.0 );
b[m-1] = tau[0] - 1.0;
ak = an;
for ( l = 1; l < m; l++ ) {
ak = ak + 2.0;
tau[l] = ( ( ak - 1.0 ) * ak
- an * ( an + 1.0 ) ) * ( ak + 2.0 ) * tau[l-1]
/ ( ak * ( ( ak + 3.0 ) * ( ak + 2.0 )
- an * ( an + 1.0 ) ) );
b[m-l-1] = tau[l];
for ( ll = 1; ll <= l; ll++ ) {
b[m-l-1] = b[m-l-1] + tau[ll-1] * b[m-l+ll-1];
}
}
b[m] = 1.0;
/* Calculation of approximate values for the abscissas. */
bb = sin ( 1.570796 / ( an + an + 1.0 ) );
x1 = sqrt ( 1.0 - bb * bb );
s = 2.0 * bb * x1;
c = sqrt ( 1.0 - s * s );
coef = 1.0 - ( 1.0 - 1.0 / an ) / ( 8.0 * an * an );
xx = coef * x1;
/* Coefficient needed for weights, COEF2 = 2^(2*n+1) * n! * n! / (2n+1)! */
coef2 = 2.0 / ( double ) ( 2 * n + 1 );
for ( i = 1; i <= n; i++ ) {
coef2 = coef2 * 4.0 * ( double ) ( i ) / ( double ) ( n + i );
}
/* Calculation of K-th abscissa (Kronrod) and corresponding weight. */
for ( k = 1; k <= n; k = k + 2 ) {
if (!abwe1 ( n, m, eps, coef2, even, b, &xx, w1+k-1 )) return 0;
w2[k-1] = 0.0;
x[k-1] = xx;
y = x1;
x1 = y * c - bb * s;
bb = y * s + bb * c;
if ( k == n ) xx = 0.0;
else xx = coef * x1;
/* Calculation of K+1 abscissa (Gaussian) and corresponding weights. */
if (!abwe2 ( n, m, eps, coef2, even, b, &xx, w1+k, w2+k )) return 0;
x[k] = xx;
y = x1;
x1 = y * c - bb * s;
bb = y * s + bb * c;
xx = coef * x1;
}
/* If N is even, compute the abcissa at the origin. */
if ( even ) {
xx = 0.0;
if (!abwe1 ( n, m, eps, coef2, even, b, &xx, w1+n )) return 0;
w2[n] = 0.0;
x[n] = xx;
}
free ( b );
free ( tau );
return 1;
}
void kronrod_adjust ( double a, double b, int n, double x[], double w1[], double w2[] ) {
/*
Purpose:
KRONROD_ADJUST adjusts a Gauss-Kronrod rule from [-1,+1] to [A,B].
Licensing:
This code is distributed under the GNU LGPL license.
Modified:
23 August 2015
Author:
John Burkardt
Parameters:
Input, double A, B, the endpoints of the new interval.
Input, int N, the order of the rule.
Input/output, double X[N+1], W1[N+1], W2[N+1], the abscissas
and weights.
*/
int i;
for ( i = 0; i < n + 1; i++ )
{
x[i] = ( ( 1.0 - x[i] ) * a
+ ( 1.0 + x[i] ) * b )
/ 2.0;
w1[i] = ( ( b - a ) / 2.0 ) * w1[i];
w2[i] = ( ( b - a ) / 2.0 ) * w2[i];
}
return;
}
|
the_stack_data/173576880.c
|
/* this is the driver for c_ptr_test.f03 */
typedef struct services
{
int compId;
void *globalServices;
}services_t;
typedef struct comp
{
void *myServices;
void (*setServices)(struct comp *self, services_t *myServices);
void *myPort;
}comp_t;
/* prototypes for f90 functions */
void sub0(comp_t *self, services_t *myServices);
int main(int argc, char **argv)
{
services_t servicesObj;
comp_t myComp;
servicesObj.compId = 17;
servicesObj.globalServices = 0; /* NULL; */
myComp.myServices = &servicesObj;
myComp.setServices = 0; /* NULL; */
myComp.myPort = 0; /* NULL; */
sub0(&myComp, &servicesObj);
return 0;
}/* end main() */
|
the_stack_data/68057.c
|
// Assignment: Homework #1 (P-Machine)
// Students: Nicole Freites & Shivani Kumar
#include <stdio.h>
#include <stdlib.h>
#define MAX_DATA_STACK_HEIGHT 1000
#define MAX_CODE_LENGTH 500
typedef struct instruction{
int op; // opcode
int l; // L
int m; // M
}instruction;
int stack[MAX_DATA_STACK_HEIGHT]; // globally declaring stack
// This function finds a variable in a different activation record some L levels down
int base(int l, int base) // l stands for L in the instruction format
{
int b1; // Find base L levels down
b1 = base;
while(l > 0)
{
b1 = stack[b1 - 1];
l--;
}
return b1;
}
// Function to print the stack.
void printStack(int sp, int ar[])
{
int activationRecordIndex = 0;
for(int j = MAX_DATA_STACK_HEIGHT - 1; j >= sp; j--)
{
printf("%d ", stack[j]);
// Prints the line to separate the activation records if the sp stored
// in the activation array is the same as the current index.
if (ar[activationRecordIndex] == j)
{
printf("| ");
activationRecordIndex++;
}
}
printf("\n");
}
int main()
{
// Initialization of the pointer that will store the instructions from the input file.
instruction *code = calloc(MAX_CODE_LENGTH, sizeof(instruction));
// Initial values for PM/0 CPU registers
int sp = MAX_DATA_STACK_HEIGHT;
int bp = sp - 1;
int pc = 0;
instruction ir;
// Initialization of array that stores sp at a given operation in order to
// separate the activation records during the print function.
int activationRecord[MAX_CODE_LENGTH];
int arIndex = 0;
// Used to keep track of the index of the array of instructions.
int index = 0;
printf("Line\tOP\tL\tM\n");
// Load data while the end of the file is not reached.
while(!feof(stdin))
{
// Reads in the OP, L, and M components and stores it in a pointer.
scanf("%d %d %d", &code[index].op, &code[index].l, &code[index].m);
// Based on the OP component, the following will print the operations in order given by the user.
switch(code[index].op)
{
case 1:
printf(" %d\tlit\t0\t%d\n", index, code[index].m);
break;
case 2:
printf(" %d\topr\t0\t%d\n", index, code[index].m);
break;
case 3:
printf(" %d\tlod\t%d\t%d\n", index, code[index].l, code[index].m);
break;
case 4:
printf(" %d\tsto\t%d\t%d\n", index, code[index].l, code[index].m);
break;
case 5:
printf(" %d\tcal\t%d\t%d\n", index, code[index].l, code[index].m);
break;
case 6:
printf(" %d\tinc\t0\t%d\n", index, code[index].m);
break;
case 7:
printf(" %d\tjmp\t0\t%d\n", index, code[index].m);
break;
case 8:
printf(" %d\tjpc\t0\t%d\n", index, code[index].m);
break;
case 9:
printf(" %d\tsio\t0\t1\n", index);
break;
case 10:
printf(" %d\tsio\t0\t2\n", index);
break;
case 11:
printf(" %d\tsio\t0\t3\n", index);
break;
}
index++;
}
// Flag to signal that the program is finished. If set to zero, the program has ended.
int haltFlag = 1;
index = 0;
printf("\n\n\t\tpc\tbp\tsp\tstack\n");
printf("Initial values\t%d\t%d\t%d\n", pc, bp, sp);
while(haltFlag == 1)
{
// Fetch cycle.
ir = code[pc];
pc = pc + 1;
// Execute cycle.
switch(ir.op)
{
// LIT: pushes constant value (literal) M onto the stack
case 1:
sp = sp - 1;
stack[sp] = ir.m;
printf("%d lit %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// OPR: operation to be performed on the data at the top of stack
case 2:
switch(ir.m)
{
// RET: continues execution at previous activation record.
case 0:
sp = bp + 1;
pc = stack[sp - 4];
bp = stack[sp - 3];
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// NEG: the value in current position of stack will turn negative.
case 1:
stack[sp] = stack[sp] * -1;
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// ADD: sets position on stack to the previous value and next value added together.
case 2:
sp = sp + 1;
stack[sp] = stack[sp] + stack[sp - 1];
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// SUB: sets position on stack to the previous value and next value subtracted together.
case 3:
sp = sp + 1;
stack[sp] = stack[sp] - stack[sp - 1];
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// MUL: sets position on stack to the previous value and next value multiplied together.
case 4:
sp = sp + 1;
stack[sp] = stack[sp] * stack[sp - 1];
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// DIV: sets position on stack to the previous value and next value divided.
case 5:
sp = sp + 1;
stack[sp] = (stack[sp] / stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// ODD: determines if the current value on the stack is even or odd.
// Stores 1 if true, 0 if false.
case 6:
stack[sp] = stack[sp] % 2;
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// MOD: stores the remainder of the previous value and next value divided.
case 7:
sp = sp + 1;
stack[sp] = stack[sp] % stack[sp - 1];
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// EQL: determines if the previous value and current value on the stack are equal.
// Stores 1 if true, 0 if false.
case 8:
sp = sp + 1;
stack[sp] = (stack[sp] == stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// NEQ: determines if the previous value and current value on the stack are not equal.
// Stores 1 if true, 0 if false.
case 9:
sp = sp + 1;
stack[sp] = (stack[sp] != stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// LSS: determines if the current value on the stack is less than the previous value.
// Stores 1 if true, 0 if false.
case 10:
sp = sp + 1;
stack[sp] = (stack[sp] < stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// LEQ: determines if the current value on the stack is less than or equal to the previous value.
// Stores 1 if true, 0 if false.
case 11:
sp = sp + 1;
stack[sp] = (stack[sp] <= stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// GTR: determines if the current value on the stack is greater than the previous value.
// Stores 1 if true, 0 if false.
case 12:
sp = sp + 1;
stack[sp] = (stack[sp] > stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// GEQ: determines if the current value on the stack is greater than or equal to the previous value.
// Stores 1 if true, 0 if false.
case 13:
sp = sp + 1;
stack[sp] = (stack[sp] >= stack[sp - 1]);
printf("%d opr %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
}
break;
// LOD: loads value to top of stack from stack location at offset M
case 3:
sp = sp - 1;
stack[sp] = stack[base(code[sp].l, bp) - code[sp].m];
printf("%d lod %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// STO: stores value to top of stack from stack location at offset M
case 4:
stack[base(ir.l, bp) - ir.m] = stack[sp];
sp = sp + 1;
printf("%d sto %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// CAL: calls procedure at code index M
case 5:
stack[sp - 1] = 0; // space to return value
stack[sp - 2] = base(ir.l,bp); // static link
stack[sp - 3] = bp; // dynamic link
stack[sp - 4] = pc; // return address
bp = sp - 1;
pc = ir.m;
printf("%d cal %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
// Stores current sp value onto activation record array.
activationRecord[arIndex] = sp;
arIndex = arIndex + 1;
printStack(sp, activationRecord);
index = pc;
break;
// INC: allocates M locals
case 6:
sp = sp - ir.m;
printf("%d inc %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// JMP: jumps to instruction M
case 7:
pc = ir.m;
printf("%d jmp %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// JPC: jump to instruction M if top stack element is 0
case 8:
if((stack[sp]) == 0)
{
pc = ir.m;
}
sp = sp + 1;
printf("%d jpc %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// SIO: writes the top stack element to the screen
case 9:
printf("%d", stack[sp]);
sp = sp + 1;
printf("%d sio %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// SIO: read in input from the user and stores input on top of the stack
case 10:
sp = sp - 1;
scanf("%d", &stack[sp]);
printf("%d sio %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
index = pc;
break;
// SIO: end of program
case 11:
haltFlag = 0; // set Halt Flag to zero
printf("%d sio %d %d\t%d\t%d\t%d\t", index, ir.l, ir.m, pc, bp, sp);
printStack(sp, activationRecord);
break;
}
}
// Frees the code array.
free(code);
code = NULL;
return 0;
}
|
the_stack_data/527342.c
|
/* TEST_OUTPUT:
---
fail_compilation/test22935.c(18): Error: array index 5 is out of bounds `[0..4]`
---
*/
// https://issues.dlang.org/show_bug.cgi?id=22935
typedef unsigned long size_t;
struct S { char a; char text[4]; };
//int tmp = __builtin_offsetof(struct S, text[0]);
int tmp = ((unsigned long)((char *)&((struct S *)0)->text[0] - (char *)0));
_Static_assert((unsigned long)((char *)&((struct S *)0)->text[0] - (char *)0) == 1, "1");
_Static_assert((unsigned long)((char *)&((struct S *)0)->text[2] - (char *)0) == 3, "2");
_Static_assert((unsigned long)((char *)&((struct S *)4)->text[2] - (char *)0) == 7, "3");
int tmp2 = ((unsigned long)((char *)&((struct S *)0)->text[5] - (char *)0));
|
the_stack_data/500404.c
|
/*
* Utility functions for processing 3D images that have been deconvolved using a
* compressed sensing approach.
*
* Note that these routines are designed to work on double precision images where
* we don't have to worry about two adjacent pixels having identical values.
*
* Hazen 02/18
*/
/* Include */
#include <stdlib.h>
#include <stdio.h>
/* Function Declarations */
int isMaxima(double *, int, int, int, int, int, int);
int label(double *, int *, double, int, int, int, int);
void labelImage(double *, int *, double, int, int, int, int, int, int, int);
void moments(double *, double *, int *, int, int, int, int);
/* Functions */
/*
* isMaxima(image, ci, cj, ck, z_size, y_size, x_size)
*
* Returns 1 if the image at (ci,cj,ck) is greater than
* all of the surrounding pixels, otherwise 0 is returned.
*
* image - The image.
* ci - x index.
* cj - y index.
* ck - z index.
* x_size - Image size in x.
* y_size - Image size in y.
* z_size - Image size in z.
*
* Returns 1/0 if the point is a maxima, or not.
*/
int isMaxima(double *image, int ci, int cj, int ck, int x_size, int y_size, int z_size)
{
int i,j,k,ti,tj,tk;
double cur;
cur = image[ci * (y_size * z_size) + cj * z_size + ck];
for(i=-1;i<2;i++){
ti = ci + i;
if ((ti >= 0) && (ti < x_size)){
for(j=-1;j<2;j++){
tj = cj + j;
if ((tj >= 0) && (tj < y_size)){
for(k=-1;k<2;k++){
tk = ck + k;
if ((tk >= 0) && (tk < z_size)){
if ((ti != 0) || (tj != 0) || (tk != 0)){
if (cur < image[ti * (y_size * z_size) + tj * z_size + tk]){
return 0;
}
}
}
}
}
}
}
}
return 1;
}
/*
* label(image, labels, threshold, margin, z_size, y_size, x_size)
*
* Finds the locations of all the local maxima in an image and
* gives them and any surrounding pixels of lesser value, but
* greater than threshold the same label.
*
* image - The image to label.
* labels - An array with the same dimensions as image to record the labels.
* threshold - Minimum intensity threshold.
* margin - Number of pixels around the edge (in x, y) to ignore.
* x_size - Image size in x (slowest axis).
* y_size - Image size in y (second slowest axis).
* z_size - Image size in z (fast axis).
*
* Returns the number of unique labels.
*/
int label(double *image, int *labels, double threshold, int margin, int x_size, int y_size, int z_size)
{
int i,j,k,t;
int cur_label;
cur_label = 1;
for(i=margin;i<(x_size-margin);i++){
for(j=margin;j<(y_size-margin);j++){
for(k=0;k<z_size;k++){
t = i*(y_size*z_size)+j*z_size+k;
if(image[t] > threshold){
if(isMaxima(image,i,j,k,x_size,y_size,z_size)){
labelImage(image,labels,threshold,cur_label,i,j,k,x_size,y_size,z_size);
cur_label += 1;
}
}
}
}
}
cur_label -= 1;
return cur_label;
}
/*
* labelImage(image, labels, threshold, cur_label, ci, cj, ck, z_size, y_size, x_size)
*
* This is called recursively to do the actual labeling.
*
* image - The image to label.
* labels - An array with the same dimensions as image to record the labels.
* threshold - Minimum intensity threshold.
* cur_label - The current label.
* ci - x index.
* cj - y index.
* ck - z index.
* x_size - Image size in x.
* y_size - Image size in y.
* z_size - Image size in z.
*/
void labelImage(double *image, int *labels, double threshold, int cur_label, int ci, int cj, int ck, int x_size, int y_size, int z_size)
{
int i,j,k,t,ti,tj,tk;
double cur;
// Label current position.
t = ci*(y_size*z_size) + cj*z_size + ck;
labels[t] = cur_label;
cur = image[t];
// Check surrounding positions.
for(i=-1;i<2;i++){
ti = ci + i;
if ((ti >= 0) && (ti < x_size)){
for(j=-1;j<2;j++){
tj = cj + j;
if ((tj >= 0) && (tj < y_size)){
for(k=-1;k<2;k++){
tk = ck + k;
if ((tk >= 0) && (tk < z_size)){
t = ti*(y_size*z_size) + tj*z_size + tk;
if ((image[t] > threshold) && (image[t] < cur) && (labels[t] == 0)){
labelImage(image,labels,threshold,cur_label,ti,tj,tk,x_size,y_size,z_size);
}
}
}
}
}
}
}
}
/*
* moments(image, peaks, labels, counts, z_size, y_size, x_size)
*
* Compute the zeroth and first moments of each labeled section
* of the image, i.e. sum and center of mass. The results are
* stored in the peak array as [total1, cx1, cy1, cz1, total2, cx2, ..]
*
* image - The image to label.
* peaks - The array to hold the results in, of size [number of labels, 4]
* labels - An array with the same dimensions as image to record the labels.
* counts - The number of labels.
* x_size - Image size in x.
* y_size - Image size in y.
* z_size - Image size in z.
*/
void moments(double *image, double *peaks, int *labels, int counts, int x_size, int y_size, int z_size)
{
int i,j,k,l,t;
for(i=0;i<x_size;i++){
for(j=0;j<y_size;j++){
for(k=0;k<z_size;k++){
t = i*(y_size*z_size) + j*z_size + k;
if(labels[t]>0){
l = labels[t]-1;
peaks[4*l] += image[t];
peaks[4*l+1] += image[t]*(double)i;
peaks[4*l+2] += image[t]*(double)j;
peaks[4*l+3] += image[t]*(double)k;
}
}
}
}
for(i=0;i<counts;i++){
if(peaks[4*i]>0){
peaks[4*i+1] = peaks[4*i+1]/peaks[4*i];
peaks[4*i+2] = peaks[4*i+2]/peaks[4*i];
peaks[4*i+3] = peaks[4*i+3]/peaks[4*i];
}
}
}
/*
* The MIT License
*
* Copyright (c) 2016 Zhuang Lab, Harvard University
* Copyright (c) 2018 Babcock Lab, Harvard University
*
* 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.
*/
|
the_stack_data/237642655.c
|
/*Program to accept today's date and print tomorrow's date.*/
typedef struct
{
unsigned int day;
unsigned int month;
unsigned int year;
} date;
typedef union
{
date today;
date tommorow;
} dates;
void main()
{
dates D;
unsigned int m; //m is the number of days in a month
clrscr();
printf("Enter today's date-\n");
printf("Day : ");scanf("%u",&D.today.day);
printf("Month : ");scanf("%u",&D.today.month);
printf("Year : ");scanf("%u",&D.today.year);
D.today.day++; //tommorow and today are stored at the same location
switch(D.today.month)
{
case 1 :
case 3 :
case 5 :
case 7 :
case 8 :
case 10:
case 12:m=31;
break;
case 2 :m=29;
break;
case 4 :
case 6 :
case 9 :
case 11:
default :m=30;
}
if(D.tommorow.day>m)
{
D.tommorow.month+=D.tommorow.day/m; //to find the change of month
D.tommorow.day%=m;
}
if(D.tommorow.month>12)
{
D.tommorow.year+=D.tommorow.month/12; //to find the change of year
D.tommorow.month%=12;
}
printf("\nTommorow's date-\n"
"%u-%u-%u\n",D.tommorow.day,D.tommorow.month,D.tommorow.year);
printf("\nPress any key....");
getch();
}
/*OUTPUT
Enter today's date-
Day : 31
Month : 12
Year : 2019
Tommorow's date-
1-1-2020
Press any key....
*/
|
the_stack_data/175142652.c
|
/*No programa do Silvio Santos, havia um quadro chamado Qual o Preço?, no qual o Silvio mostrava um produto do mercantil e a pessoa que chegasse mais próximo do preço real ganhava.
Implemente u programa que recebe o valor do produto e o valor do chute dos jogadores. O jogador que chegar mais perto ganha. Temos dois jogadores.
Se ambos ficarem à mesma distancia do valor, então houve empate.
A primeira linha será informado o valor do produto e os chutes jogadores na ordem. A saída deve ser primeiro se o chute do primeiro jogador for o mais próximo do valor do produto ou segundo se o chute do segundo jogador for o mais próximo do valor do produto ou empate caso ambos ficarem à mesma distancia*/
#include <stdio.h>
int main(){
float chute1, chute2, valor, prox1, prox2;
scanf("%f %f %f", &valor, &chute1, &chute2);
prox1 = ((valor - chute1) < 0)? (valor - chute1) * -1: valor - chute1;
prox2 = ((valor - chute2) < 0)? (valor - chute2) * -1: valor - chute2;
if(prox1 == prox2){
printf("empate");
}else if(prox1 < prox2){
printf("primeiro");
}else{
printf("segundo");
}
}
|
the_stack_data/146128.c
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NO 5
#define LEN 30
int main(void)
{
char *arr[NO]; // array of char pointers
char name[LEN], *temp=NULL;
int i, j;
printf("\n Enter Names : \n");
for(i=0; i<NO; i++)
{
printf("\n Enter names[%d]", i);
scanf("%s", name);
// allocating memory
arr[i]= (char*) malloc(sizeof(char) * (strlen(name)+1) );
//copy name into array
strcpy(arr[i], name);
}
printf("\n Names are :: \n");
for(i=0; i<NO; i++)
{
printf("\n &arr[%d] %u arr[%d] %u arr[%d] %-10s *arr[%d] %c", i, &arr[i], i, arr[i], i, arr[i], i, *arr[i]);
}
// asc sorting
for(i=0; i<NO; i++)
{
for(j=i+1; j<NO; j++)
{
//if(strcmp(arr[i], arr[j])>0) // asc sort
if(strcmp(arr[i], arr[j])<0) // desc sort
{
temp=arr[i];
arr[i]= arr[j];
arr[j]=temp;
}
}
}
printf("\n Names after desc Sort :: \n");
for(i=0; i<NO; i++)
{
printf("\n &arr[%d] %u arr[%d] %u arr[%d] %-10s *arr[%d] %c", i, &arr[i], i, arr[i], i, arr[i], i, *arr[i]);
}
for(i=0; i<NO; i++)
{
free(arr[i]);
arr[i]=NULL;
}
printf("\n memory is freed....");
return 0;
}
|
the_stack_data/1139171.c
|
struct s { int i; };
int main(void) {
struct s *p = 0, *q;
int j = 0;
again:
q = p, p = &((struct s){ j++ });
if (j < 2) goto again;
return p == q && q->i == 1;
}
|
the_stack_data/61075557.c
|
#include<stdio.h>
int insertElement(int arr[], int elements, int key, int size)
{
if (elements >= size)
return elements;
arr[elements] = key;
return (elements + 1);
}
int main()
{
int array[20] = { 31, 27, 3, 54, 67, 31 };
int size = sizeof(array) / sizeof(array[0]);
int elements = 6;
int i, key = 32;
printf("n Before Insertion: ");
for (i = 0; i < elements; i++)
printf("%d ", array[i]);
elements = insertElement(array, elements, key, size);
printf("n After Insertion: ");
for (i = 0; i < elements; i++)
printf("%d ",array[i]);
return 0;
}
|
the_stack_data/88511.c
|
#include <assert.h>
int main() {
float i=0x0102;
char *p=(char *)&i;
// printf("Bytes of i: %d, %d, %d, %d\n",
// p[0], p[1], p[2], p[3]);
printf("Bytes of i: %d, %d\n", p[0], p[1]);
assert(p[0]==0);
assert(p[1]==0);
// assert(0);
}
|
the_stack_data/1258406.c
|
//refazer.
#include<stdio.h>
#define tamanho 10
void main(){
int vetor[tamanho], m1, m2, m3;
for(int i=0; i<tamanho; i++){
printf("Informe o valor da posicao %d: ", i+1);
scanf("%d", &vetor[i]);
}
//printf("%d %d %d\n", m1,m2,m3);
for(int i=0, aux; i<tamanho; i++){
for(int j=0;j<tamanho; j++){
if(vetor[i] < vetor[j]){
aux=vetor[i];
vetor[i] = vetor[j];
vetor[j] = aux;
}
}
}
for(int i=0; i<3; i++){
printf("%d ", vetor[i]);
}
printf("\n");
}
|
the_stack_data/87507.c
|
#include<stdio.h>
#include<math.h>
int main()
{
double x=1;
int y=1;
x=sin(4);
y=(int)(cos(0.5));
printf("\nx: %f\ty:\t%f\n",y,x);
return 0;
}
|
the_stack_data/111077448.c
|
/*
* Derived from:
* http://www.kernel.org/pub/linux/libs/klibc/
*/
/*
* strlcat.c
*/
#include <string.h>
size_t strlcat(char *dst, const char *src, size_t size)
{
size_t bytes = 0;
char *q = dst;
const char *p = src;
char ch;
while (bytes < size && *q) {
q++;
bytes++;
}
if (bytes == size) {
return (bytes + strlen(src));
}
while ((ch = *p++)) {
if (bytes + 1 < size) {
*q++ = ch;
}
bytes++;
}
*q = '\0';
return bytes;
}
|
the_stack_data/1199925.c
|
/* dummy file compiled to extract head path information from clang */
int main() { return 0; }
|
the_stack_data/168892141.c
|
#include <stdio.h>
#include <stdlib.h>
#define N 3
int main(){
int start, move;
int nopts[N+2]; //array of top of stacks
int option[N+2][N+2]; //array of stacks of options
int i, candidate;
move = start = 0;
nopts[start]= 1;
while (nopts[start] >0) //while dummy stack is not empty
{
if(nopts[move]>0)
{
move++;
nopts[move]=0; //initialize new move
if(move==N+1) //solution found!
{
for(i=1;i<move;i++)
printf("%2i",option[i][nopts[i]]);
printf("\n");
}
else if(move == 1){
for(candidate = N; candidate >=1; candidate --)
{
nopts[move]++;
option[move][nopts[move]] = candidate;
printf("nopts[move] %i candidate %i:\n", nopts[move], candidate);
}
}
else{
for(candidate=N;candidate>=1;candidate--)
{
for(i=move-1;i>=1;i--)
if(candidate==option[i][nopts[i]]) break;
if(!(i>=1))
option[move][++nopts[move]] = candidate;
}
}
}
else
{
move--;
nopts[move]--;
}
}
}
|
the_stack_data/67041.c
|
#ifndef lint
static const char yysccsid[] = "@(#)yaccpar 1.9 (Berkeley) 02/21/93";
#endif
#include <stdlib.h>
#include <string.h>
#define YYBYACC 1
#define YYMAJOR 1
#define YYMINOR 9
#define YYPATCH 20070509
#define YYEMPTY (-1)
#define yyclearin (yychar = YYEMPTY)
#define yyerrok (yyerrflag = 0)
#define YYRECOVERING (yyerrflag != 0)
extern int yyparse(void);
static int yygrowstack(void);
#define YYPREFIX "yy"
#line 2 "yacc.y"
#include <stdio.h>
#line 27 "y.tab.c"
#define NOUN 257
#define PRONOUN 258
#define VERB 259
#define ADVERB 260
#define ADJECTIVE 261
#define PREPOSITION 262
#define CONJUNCTION 263
#define YYERRCODE 256
short yylhs[] = { -1,
0, 1, 1, 2,
};
short yylen[] = { 2,
3, 1, 1, 1,
};
short yydefred[] = { 0,
2, 3, 0, 0, 0, 4, 1,
};
short yydgoto[] = { 3,
4, 7,
};
short yysindex[] = { -257,
0, 0, 0, -256, -255, 0, 0,
};
short yyrindex[] = { 0,
0, 0, 0, 0, 0, 0, 0,
};
short yygindex[] = { 0,
0, 0,
};
#define YYTABLESIZE 3
short yytable[] = { 1,
2, 6, 5,
};
short yycheck[] = { 257,
258, 257, 259,
};
#define YYFINAL 3
#ifndef YYDEBUG
#define YYDEBUG 0
#endif
#define YYMAXTOKEN 263
#if YYDEBUG
char *yyname[] = {
"end-of-file",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,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,"NOUN","PRONOUN","VERB","ADVERB",
"ADJECTIVE","PREPOSITION","CONJUNCTION",
};
char *yyrule[] = {
"$accept : sentence",
"sentence : subject VERB object",
"subject : NOUN",
"subject : PRONOUN",
"object : NOUN",
};
#endif
#ifndef YYSTYPE
typedef int YYSTYPE;
#endif
#if YYDEBUG
#include <stdio.h>
#endif
/* define the initial stack-sizes */
#ifdef YYSTACKSIZE
#undef YYMAXDEPTH
#define YYMAXDEPTH YYSTACKSIZE
#else
#ifdef YYMAXDEPTH
#define YYSTACKSIZE YYMAXDEPTH
#else
#define YYSTACKSIZE 10000
#define YYMAXDEPTH 10000
#endif
#endif
#define YYINITSTACKSIZE 500
int yydebug;
int yynerrs;
int yyerrflag;
int yychar;
short *yyssp;
YYSTYPE *yyvsp;
YYSTYPE yyval;
YYSTYPE yylval;
/* variables for the parser stack */
static short *yyss;
static short *yysslim;
static YYSTYPE *yyvs;
static int yystacksize;
#line 19 "yacc.y"
extern FILE *yyin;
main(){
do{
yyparse();
}while(!feof(yyin));
}
yyerror(s)
char *s;
{
fprintf(stderr,"%s\n",s);
}
#line 141 "y.tab.c"
/* allocate initial stack or double stack size, up to YYMAXDEPTH */
static int yygrowstack(void)
{
int newsize, i;
short *newss;
YYSTYPE *newvs;
if ((newsize = yystacksize) == 0)
newsize = YYINITSTACKSIZE;
else if (newsize >= YYMAXDEPTH)
return -1;
else if ((newsize *= 2) > YYMAXDEPTH)
newsize = YYMAXDEPTH;
i = yyssp - yyss;
newss = (yyss != 0)
? (short *)realloc(yyss, newsize * sizeof(*newss))
: (short *)malloc(newsize * sizeof(*newss));
if (newss == 0)
return -1;
yyss = newss;
yyssp = newss + i;
newvs = (yyvs != 0)
? (YYSTYPE *)realloc(yyvs, newsize * sizeof(*newvs))
: (YYSTYPE *)malloc(newsize * sizeof(*newvs));
if (newvs == 0)
return -1;
yyvs = newvs;
yyvsp = newvs + i;
yystacksize = newsize;
yysslim = yyss + newsize - 1;
return 0;
}
#define YYABORT goto yyabort
#define YYREJECT goto yyabort
#define YYACCEPT goto yyaccept
#define YYERROR goto yyerrlab
int
yyparse(void)
{
register int yym, yyn, yystate;
#if YYDEBUG
register const char *yys;
if ((yys = getenv("YYDEBUG")) != 0)
{
yyn = *yys;
if (yyn >= '0' && yyn <= '9')
yydebug = yyn - '0';
}
#endif
yynerrs = 0;
yyerrflag = 0;
yychar = YYEMPTY;
if (yyss == NULL && yygrowstack()) goto yyoverflow;
yyssp = yyss;
yyvsp = yyvs;
*yyssp = yystate = 0;
yyloop:
if ((yyn = yydefred[yystate]) != 0) goto yyreduce;
if (yychar < 0)
{
if ((yychar = yylex()) < 0) yychar = 0;
#if YYDEBUG
if (yydebug)
{
yys = 0;
if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
if (!yys) yys = "illegal-symbol";
printf("%sdebug: state %d, reading %d (%s)\n",
YYPREFIX, yystate, yychar, yys);
}
#endif
}
if ((yyn = yysindex[yystate]) && (yyn += yychar) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yychar)
{
#if YYDEBUG
if (yydebug)
printf("%sdebug: state %d, shifting to state %d\n",
YYPREFIX, yystate, yytable[yyn]);
#endif
if (yyssp >= yysslim && yygrowstack())
{
goto yyoverflow;
}
*++yyssp = yystate = yytable[yyn];
*++yyvsp = yylval;
yychar = YYEMPTY;
if (yyerrflag > 0) --yyerrflag;
goto yyloop;
}
if ((yyn = yyrindex[yystate]) && (yyn += yychar) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yychar)
{
yyn = yytable[yyn];
goto yyreduce;
}
if (yyerrflag) goto yyinrecovery;
yyerror("syntax error");
#ifdef lint
goto yyerrlab;
#endif
yyerrlab:
++yynerrs;
yyinrecovery:
if (yyerrflag < 3)
{
yyerrflag = 3;
for (;;)
{
if ((yyn = yysindex[*yyssp]) && (yyn += YYERRCODE) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE)
{
#if YYDEBUG
if (yydebug)
printf("%sdebug: state %d, error recovery shifting\
to state %d\n", YYPREFIX, *yyssp, yytable[yyn]);
#endif
if (yyssp >= yysslim && yygrowstack())
{
goto yyoverflow;
}
*++yyssp = yystate = yytable[yyn];
*++yyvsp = yylval;
goto yyloop;
}
else
{
#if YYDEBUG
if (yydebug)
printf("%sdebug: error recovery discarding state %d\n",
YYPREFIX, *yyssp);
#endif
if (yyssp <= yyss) goto yyabort;
--yyssp;
--yyvsp;
}
}
}
else
{
if (yychar == 0) goto yyabort;
#if YYDEBUG
if (yydebug)
{
yys = 0;
if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
if (!yys) yys = "illegal-symbol";
printf("%sdebug: state %d, error recovery discards token %d (%s)\n",
YYPREFIX, yystate, yychar, yys);
}
#endif
yychar = YYEMPTY;
goto yyloop;
}
yyreduce:
#if YYDEBUG
if (yydebug)
printf("%sdebug: state %d, reducing by rule %d (%s)\n",
YYPREFIX, yystate, yyn, yyrule[yyn]);
#endif
yym = yylen[yyn];
if (yym)
yyval = yyvsp[1-yym];
else
memset(&yyval, 0, sizeof yyval);
switch (yyn)
{
case 1:
#line 10 "yacc.y"
{ printf("Sentence is valid.\n"); }
break;
#line 326 "y.tab.c"
}
yyssp -= yym;
yystate = *yyssp;
yyvsp -= yym;
yym = yylhs[yyn];
if (yystate == 0 && yym == 0)
{
#if YYDEBUG
if (yydebug)
printf("%sdebug: after reduction, shifting from state 0 to\
state %d\n", YYPREFIX, YYFINAL);
#endif
yystate = YYFINAL;
*++yyssp = YYFINAL;
*++yyvsp = yyval;
if (yychar < 0)
{
if ((yychar = yylex()) < 0) yychar = 0;
#if YYDEBUG
if (yydebug)
{
yys = 0;
if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
if (!yys) yys = "illegal-symbol";
printf("%sdebug: state %d, reading %d (%s)\n",
YYPREFIX, YYFINAL, yychar, yys);
}
#endif
}
if (yychar == 0) goto yyaccept;
goto yyloop;
}
if ((yyn = yygindex[yym]) && (yyn += yystate) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yystate)
yystate = yytable[yyn];
else
yystate = yydgoto[yym];
#if YYDEBUG
if (yydebug)
printf("%sdebug: after reduction, shifting from state %d \
to state %d\n", YYPREFIX, *yyssp, yystate);
#endif
if (yyssp >= yysslim && yygrowstack())
{
goto yyoverflow;
}
*++yyssp = yystate;
*++yyvsp = yyval;
goto yyloop;
yyoverflow:
yyerror("yacc stack overflow");
yyabort:
return (1);
yyaccept:
return (0);
}
|
the_stack_data/40707.c
|
#include<stdio.h>
int main()
{
int a[10],i,pos,n;
printf("Enter size");
scanf("%d",&n);
printf("Enter elements in Array");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter position");
scanf("%d",&pos);
for(i=pos;i<n;i++)
{
a[i-1]=a[i];
n=n-1;
}
printf("Array after deletion");
for(i=0;i<n-1;i++)
{
printf("%d",&a[i]);
}
}
|
the_stack_data/1007718.c
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2012-2019 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <math.h>
extern long i;
double
sinfrob16 (double d)
{
i++;
d = sin (d);
i++;
return d;
}
double
sinblah16 (double d)
{
i++;
d = sin (d);
i++;
return d;
}
|
the_stack_data/242330828.c
|
/* Generated by CIL v. 1.7.0 */
/* print_CIL_Input is false */
struct _IO_FILE;
struct timeval;
extern void signal(int sig , void *func ) ;
extern float strtof(char const *str , char const *endptr ) ;
typedef struct _IO_FILE FILE;
extern int atoi(char const *s ) ;
extern double strtod(char const *str , char const *endptr ) ;
extern int fclose(void *stream ) ;
extern void *fopen(char const *filename , char const *mode ) ;
extern void abort() ;
extern void exit(int status ) ;
extern int raise(int sig ) ;
extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ;
extern int strcmp(char const *a , char const *b ) ;
extern int rand() ;
extern unsigned long strtoul(char const *str , char const *endptr , int base ) ;
void RandomFunc(unsigned char input[1] , unsigned char output[1] ) ;
extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ;
extern int gettimeofday(struct timeval *tv , void *tz , ...) ;
extern int printf(char const *format , ...) ;
int main(int argc , char *argv[] ) ;
void megaInit(void) ;
extern unsigned long strlen(char const *s ) ;
extern long strtol(char const *str , char const *endptr , int base ) ;
extern unsigned long strnlen(char const *s , unsigned long maxlen ) ;
extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ;
struct timeval {
long tv_sec ;
long tv_usec ;
};
extern void *malloc(unsigned long size ) ;
extern int scanf(char const *format , ...) ;
void megaInit(void)
{
{
}
}
void RandomFunc(unsigned char input[1] , unsigned char output[1] )
{
unsigned char state[1] ;
unsigned char local1 ;
{
state[0UL] = (input[0UL] & 914778474UL) << (unsigned char)7;
local1 = 0UL;
while (local1 < (unsigned char)0) {
if (state[0UL] > local1) {
state[local1] = state[0UL] << (((state[local1] >> (unsigned char)1) & (unsigned char)7) | 1UL);
state[local1] = state[0UL] << (((state[local1] >> (unsigned char)4) & (unsigned char)7) | 1UL);
} else {
state[local1] = state[0UL] | state[local1];
state[local1] ^= state[0UL];
}
if (state[0UL] > local1) {
state[local1] = state[0UL] >> (((state[0UL] >> (unsigned char)3) & (unsigned char)7) | 1UL);
state[0UL] = state[local1] >> ((state[local1] & (unsigned char)7) | 1UL);
} else {
state[0UL] = state[local1] >> (((state[local1] >> (unsigned char)2) & (unsigned char)7) | 1UL);
state[local1] ^= state[0UL];
}
local1 ++;
}
output[0UL] = (state[0UL] & 218093449UL) << (unsigned char)7;
}
}
int main(int argc , char *argv[] )
{
unsigned char input[1] ;
unsigned char output[1] ;
int randomFuns_i5 ;
unsigned char randomFuns_value6 ;
int randomFuns_main_i7 ;
{
megaInit();
if (argc != 2) {
printf("Call this program with %i arguments\n", 1);
exit(-1);
} else {
}
randomFuns_i5 = 0;
while (randomFuns_i5 < 1) {
randomFuns_value6 = (unsigned char )strtoul(argv[randomFuns_i5 + 1], 0, 10);
input[randomFuns_i5] = randomFuns_value6;
randomFuns_i5 ++;
}
RandomFunc(input, output);
if (output[0] == (unsigned char)42) {
printf("You win!\n");
} else {
}
randomFuns_main_i7 = 0;
while (randomFuns_main_i7 < 1) {
printf("%u\n", output[randomFuns_main_i7]);
randomFuns_main_i7 ++;
}
}
}
|
the_stack_data/79285.c
|
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *next;
}node;
void insert(node **h, int n)
{
node *p;
p = (node *)malloc(sizeof(node));
if(p!=NULL)
{
p->info = n;
p->next = NULL;
if(*(h)==NULL)
*(h) = p;
else
{
p->next = *(h);
*(h) = p;
}
}
else
printf("Not Enough Memory Available \n");
}
void del_max(node *j)
{
node *t = j,*l = j,*s,*w=j;
int max;
max = t->info;
t = t->next;
while(t!=NULL)
{
if(max<(t->info))
{
max = t->info;
s = t;
}
t = t->next;
}
if(s==j)
j = j->next;
else
{
while(l!=s)
{
l = l->next;
}
if(s->next == NULL)
l->next = NULL;
else
l->next = l->next->next;
}
free(s);
while(j!=NULL)
{
printf("%d",(j->info));
j = j->next;
}
}
void main()
{
node *head = NULL;
int num; char ch;
do
{
printf("Enter the element \n");
scanf("%d",&num);
insert(&head,num);
printf("Do you want to continue y/n \n");
fflush(stdin);
scanf("%c",&ch);
}while(ch=='y'||ch=='Y');
del_max(head);
}
|
the_stack_data/154828251.c
|
#include <stdio.h>
int main(){
printf( "FAIL\n" );
return 0;
}
|
the_stack_data/277817.c
|
/**
* _strstr - locates a substring in given string
* @haystack: memory area pointed to.
* @needle: constant byte to fill memory with.
* Return: pointer to beginning of located substring
* or NULL if not found.
*/
char *_strstr(char *haystack, char *needle)
{
int flag, sentence, word;
if (needle[0] == '\0')
return (haystack);
flag = 0;
for (sentence = 0; haystack[sentence] != '\0'; sentence++)
{
for (word = 0; needle[word] != '\0'; word++)
{
if (haystack[sentence + word] != needle[word])
{
flag = 0;
break;
}
flag = 1;
}
if (flag)
return (haystack + sentence);
}
return ('\0');
}
|
the_stack_data/72011590.c
|
/*-
* Copyright (c) 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Dieter Baron and Thomas Klausner.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
//#include <config.h>
#include "getopt.h"
#include <stdlib.h>
#include <string.h>
//#include <stdafx.h>
#ifdef _WIN32
/* Windows needs warnx(). We change the definition though:
* 1. (another) global is defined, opterrmsg, which holds the error message
* 2. errors are always printed out on stderr w/o the program name
* Note that opterrmsg always gets set no matter what opterr is set to. The
* error message will not be printed if opterr is 0 as usual.
*/
#include <stdio.h>
#include <stdarg.h>
extern char opterrmsg[128];
char opterrmsg[128]; /* last error message is stored here */
static void warnx(int print_error, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if (fmt != NULL)
_vsnprintf_s(opterrmsg, 128, _TRUNCATE, fmt, ap);
else
opterrmsg[0]='\0';
va_end(ap);
if (print_error) {
fprintf(stderr, opterrmsg);
fprintf(stderr, "\n");
}
}
#endif /*_WIN32*/
/* not part of the original file */
#ifndef _DIAGASSERT
#define _DIAGASSERT(X)
#endif
#if HAVE_CONFIG_H && !HAVE_GETOPT_LONG && !HAVE_DECL_OPTIND
#define REPLACE_GETOPT
#endif
int opterr = 1; /* if error message should be printed */
int optind = 1; /* index into parent argv vector */
int optopt = '?'; /* character checked for validity */
int optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#if !HAVE_GETOPT_LONG
#define IGNORE_FIRST (*options == '-' || *options == '+')
#define PRINT_ERROR ((opterr) && ((*options != ':') \
|| (IGNORE_FIRST && options[1] != ':')))
#define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
#define PERMUTE (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
/* XXX: GNU ignores PC if *options == '-' */
#define IN_ORDER (!IS_POSIXLY_CORRECT && *options == '-')
/* return values */
#define BADCH (int)'?'
#define BADARG ((IGNORE_FIRST && options[1] == ':') \
|| (*options == ':') ? (int)':' : (int)'?')
#define INORDER (int)1
#define EMSG ""
static int getopt_internal(int, char * const *, const char *);
static int gcd(int, int);
static void permute_args(int, int, int, char * const *);
static char *place = EMSG; /* option letter processing */
/* XXX: set optreset to 1 rather than these two */
static int nonopt_start = -1; /* first non option argument (for permute) */
static int nonopt_end = -1; /* first option after non options (for permute) */
/* Error messages */
static const char recargchar[] = "option requires an argument -- %c";
static const char recargstring[] = "option requires an argument -- %s";
static const char ambig[] = "ambiguous option -- %.*s";
static const char noarg[] = "option doesn't take an argument -- %.*s";
static const char illoptchar[] = "unknown option -- %c";
static const char illoptstring[] = "unknown option -- %s";
/*
* Compute the greatest common divisor of a and b.
*/
static int
gcd(int a, int b)
{
int c;
c = a % b;
while (c != 0) {
a = b;
b = c;
c = a % b;
}
return b;
}
/*
* Exchange the block from nonopt_start to nonopt_end with the block
* from nonopt_end to opt_end (keeping the same order of arguments
* in each block).
*/
static void
permute_args(int panonopt_start, int panonopt_end,
int opt_end, char * const *nargv)
{
int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
char *swap;
_DIAGASSERT(nargv != NULL);
/*
* compute lengths of blocks and number and size of cycles
*/
nnonopts = panonopt_end - panonopt_start;
nopts = opt_end - panonopt_end;
ncycle = gcd(nnonopts, nopts);
cyclelen = (opt_end - panonopt_start) / ncycle;
for (i = 0; i < ncycle; i++) {
cstart = panonopt_end+i;
pos = cstart;
for (j = 0; j < cyclelen; j++) {
if (pos >= panonopt_end)
pos -= nnonopts;
else
pos += nopts;
swap = nargv[pos];
/* LINTED const cast */
((char **) nargv)[pos] = nargv[cstart];
/* LINTED const cast */
((char **)nargv)[cstart] = swap;
}
}
}
/*
* getopt_internal --
* Parse argc/argv argument vector. Called by user level routines.
* Returns -2 if -- is found (can be long option or end of options marker).
*/
static int
getopt_internal(int nargc, char * const *nargv, const char *options)
{
char *oli; /* option letter list index */
int optchar;
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(options != NULL);
optarg = NULL;
/*
* XXX Some programs (like rsyncd) expect to be able to
* XXX re-initialize optind to 0 and have getopt_long(3)
* XXX properly function again. Work around this braindamage.
*/
if (optind == 0)
optind = 1;
if (optreset)
nonopt_start = nonopt_end = -1;
start:
if (optreset || !*place) { /* update scanning pointer */
optreset = 0;
if (optind >= nargc) { /* end of argument vector */
place = EMSG;
if (nonopt_end != -1) {
/* do permutation, if we have to */
permute_args(nonopt_start, nonopt_end,
optind, nargv);
optind -= nonopt_end - nonopt_start;
}
else if (nonopt_start != -1) {
/*
* If we skipped non-options, set optind
* to the first of them.
*/
optind = nonopt_start;
}
nonopt_start = nonopt_end = -1;
return -1;
}
if ((*(place = nargv[optind]) != '-')
|| (place[1] == '\0')) { /* found non-option */
place = EMSG;
if (IN_ORDER) {
/*
* GNU extension:
* return non-option as argument to option 1
*/
optarg = nargv[optind++];
return INORDER;
}
if (!PERMUTE) {
/*
* if no permutation wanted, stop parsing
* at first non-option
*/
return -1;
}
/* do permutation */
if (nonopt_start == -1)
nonopt_start = optind;
else if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end,
optind, nargv);
nonopt_start = optind -
(nonopt_end - nonopt_start);
nonopt_end = -1;
}
optind++;
/* process next argument */
goto start;
}
if (nonopt_start != -1 && nonopt_end == -1)
nonopt_end = optind;
if (place[1] && *++place == '-') { /* found "--" */
place++;
return -2;
}
}
if ((optchar = (int)*place++) == (int)':' ||
(oli = (char *) strchr(options + (IGNORE_FIRST ? 1 : 0),
optchar)) == NULL) {
/* option letter unknown or ':' */
if (!*place)
++optind;
#ifndef _WIN32
if (PRINT_ERROR)
warnx(illoptchar, optchar);
#else
warnx(PRINT_ERROR, illoptchar, optchar);
#endif
optopt = optchar;
return BADCH;
}
if (optchar == 'W' && oli[1] == ';') { /* -W long-option */
/* XXX: what if no long options provided (called by getopt)? */
if (*place)
return -2;
if (++optind >= nargc) { /* no arg */
place = EMSG;
#ifndef _WIN32
if (PRINT_ERROR)
warnx(recargchar, optchar);
#else
warnx(PRINT_ERROR, recargchar, optchar);
#endif
optopt = optchar;
return BADARG;
} else /* white space */
place = nargv[optind];
/*
* Handle -W arg the same as --arg (which causes getopt to
* stop parsing).
*/
return -2;
}
if (*++oli != ':') { /* doesn't take argument */
if (!*place)
++optind;
} else { /* takes (optional) argument */
optarg = NULL;
if (*place) /* no white space */
optarg = place;
/* XXX: disable test for :: if PC? (GNU doesn't) */
else if (oli[1] != ':') { /* arg not optional */
if (++optind >= nargc) { /* no arg */
place = EMSG;
#ifndef _WIN32
if (PRINT_ERROR)
warnx(recargchar, optchar);
#else
warnx(PRINT_ERROR, recargchar, optchar);
#endif
optopt = optchar;
return BADARG;
} else
optarg = nargv[optind];
}
place = EMSG;
++optind;
}
/* dump back option letter */
return optchar;
}
/*
* getopt --
* Parse argc/argv argument vector.
*
* [eventually this will replace the real getopt]
*/
int
getopt(int nargc, char * const *nargv, const char *options)
{
int retval;
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(options != NULL);
if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
++optind;
/*
* We found an option (--), so if we skipped non-options,
* we have to permute.
*/
if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end, optind,
nargv);
optind -= nonopt_end - nonopt_start;
}
nonopt_start = nonopt_end = -1;
retval = -1;
}
return retval;
}
/*
* getopt_long --
* Parse argc/argv argument vector.
*/
int
getopt_long(int nargc,
char * const *nargv,
const char *options,
const struct option *long_options,
int *idx)
{
int retval;
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(options != NULL);
_DIAGASSERT(long_options != NULL);
/* idx may be NULL */
if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
char *current_argv, *has_equal;
size_t current_argv_len;
int i, match;
current_argv = place;
match = -1;
optind++;
place = EMSG;
if (*current_argv == '\0') { /* found "--" */
/*
* We found an option (--), so if we skipped
* non-options, we have to permute.
*/
if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end,
optind, nargv);
optind -= nonopt_end - nonopt_start;
}
nonopt_start = nonopt_end = -1;
return -1;
}
if ((has_equal = strchr(current_argv, '=')) != NULL) {
/* argument found (--option=arg) */
current_argv_len = has_equal - current_argv;
has_equal++;
} else
current_argv_len = strlen(current_argv);
for (i = 0; long_options[i].name; i++) {
/* find matching long option */
if (strncmp(current_argv, long_options[i].name,
current_argv_len))
continue;
if (strlen(long_options[i].name) ==
(unsigned)current_argv_len) {
/* exact match */
match = i;
break;
}
if (match == -1) /* partial match */
match = i;
else {
/* ambiguous abbreviation */
#ifndef _WIN32
if (PRINT_ERROR)
warnx(ambig, (int)current_argv_len,
current_argv);
#else
warnx(PRINT_ERROR, ambig, (int)current_argv_len,
current_argv);
#endif
optopt = 0;
return BADCH;
}
}
if (match != -1) { /* option found */
if (long_options[match].has_arg == no_argument
&& has_equal) {
#ifndef _WIN32
if (PRINT_ERROR)
warnx(noarg, (int)current_argv_len,
current_argv);
#else
warnx(PRINT_ERROR, noarg, (int)current_argv_len,
current_argv);
#endif
/*
* XXX: GNU sets optopt to val regardless of
* flag
*/
if (long_options[match].flag == NULL)
optopt = long_options[match].val;
else
optopt = 0;
return BADARG;
}
if (long_options[match].has_arg == required_argument ||
long_options[match].has_arg == optional_argument) {
if (has_equal)
optarg = has_equal;
else if (long_options[match].has_arg ==
required_argument) {
/*
* optional argument doesn't use
* next nargv
*/
optarg = nargv[optind++];
}
}
if ((long_options[match].has_arg == required_argument)
&& (optarg == NULL)) {
/*
* Missing argument; leading ':'
* indicates no error should be generated
*/
#ifndef _WIN32
if (PRINT_ERROR)
warnx(recargstring, current_argv);
#else
warnx(PRINT_ERROR, recargstring, current_argv);
#endif
/*
* XXX: GNU sets optopt to val regardless
* of flag
*/
if (long_options[match].flag == NULL)
optopt = long_options[match].val;
else
optopt = 0;
--optind;
return BADARG;
}
} else { /* unknown option */
#ifndef _WIN32
if (PRINT_ERROR)
warnx(illoptstring, current_argv);
#else
warnx(PRINT_ERROR, illoptstring, current_argv);
#endif
optopt = 0;
return BADCH;
}
if (long_options[match].flag) {
*long_options[match].flag = long_options[match].val;
retval = 0;
} else
retval = long_options[match].val;
if (idx)
*idx = match;
}
return retval;
}
#endif /* !GETOPT_LONG */
|
the_stack_data/62638130.c
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
int main(int argc, char *argv[])
{
int n = atoi(argv[1]);
uint64_t at = 1;
printf("%d\n",n);
for (int i=n-1; i>=0; --i) {
printf("%d\n",(int) at);
at = (UINT64_C(25214903917)*at+UINT64_C(11)) % (UINT64_C(1)<<48);
}
return 0;
}
|
the_stack_data/4997.c
|
/*
* --- Revised 3-Clause BSD License ---
* Copyright Semtech Corporation 2020. 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 Semtech 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 SEMTECH CORPORATION. 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.
*/
#if defined(CFG_lgw1)
#if (!defined(CFG_ral_lgw) && !defined(CFG_ral_master_slave)) || (defined(CFG_ral_lgw) && defined(CFG_ral_master_slave))
#error Exactly one of the two params must be set: CFG_ral_lgw CFG_ral_master_slave
#endif
#include "s2conf.h"
#include "tc.h"
#include "timesync.h"
#include "sys.h"
#include "sx130xconf.h"
#include "ral.h"
#include "lgw/loragw_reg.h"
#include "lgw/loragw_hal.h"
#if defined(CFG_sx1302)
#include "lgw/loragw_sx1302.h"
#endif // defined(CFG_sx1302)
#define RAL_MAX_RXBURST 10
#define FSK_BAUD 50000
#define FSK_FDEV 25 // [kHz]
#define FSK_PRMBL_LEN 5
static const u2_t SF_MAP[] = {
[SF12 ]= DR_LORA_SF12,
[SF11 ]= DR_LORA_SF11,
[SF10 ]= DR_LORA_SF10,
[SF9 ]= DR_LORA_SF9,
[SF8 ]= DR_LORA_SF8,
[SF7 ]= DR_LORA_SF7,
[FSK ]= DR_UNDEFINED,
[SFNIL]= DR_UNDEFINED,
};
static const u1_t BW_MAP[] = {
[BW125]= BW_125KHZ,
[BW250]= BW_250KHZ,
[BW500]= BW_500KHZ,
[BWNIL]= BW_UNDEFINED
};
static int to_sf (int lgw_sf) {
for( u1_t sf=SF12; sf<=FSK; sf++ )
if( SF_MAP[sf] == lgw_sf )
return sf;
return SFNIL;
}
static int to_bw (int lgw_bw) {
for( u1_t bw=BW125; bw<=BW500; bw++ )
if( BW_MAP[bw] == lgw_bw )
return bw;
return BWNIL;
}
rps_t ral_lgw2rps (struct lgw_pkt_rx_s* p) {
return p->modulation == MOD_LORA
? rps_make(to_sf(p->datarate), to_bw(p->bandwidth))
: FSK;
}
void ral_rps2lgw (rps_t rps, struct lgw_pkt_tx_s* p) {
assert(rps != RPS_ILLEGAL);
if( rps_sf(rps) == FSK ) {
p->modulation = MOD_FSK;
p->datarate = FSK_BAUD;
p->f_dev = FSK_FDEV;
p->preamble = FSK_PRMBL_LEN;
} else {
p->modulation = MOD_LORA;
p->datarate = SF_MAP[rps_sf(rps)];
p->bandwidth = BW_MAP[rps_bw(rps)];
}
}
int ral_rps2bw (rps_t rps) {
assert(rps != RPS_ILLEGAL);
return BW_MAP[rps_bw(rps)];
}
int ral_rps2sf (rps_t rps) {
assert(rps != RPS_ILLEGAL);
return SF_MAP[rps_sf(rps)];
}
// Make a clock sync measurement:
// pps_en w/o checking on latches PPS xticks
// last_xtime read and update last xticks to form a continuous 64 bit time
// timesync return measured data - isochronous times for MCU/SX130X and opt. latched PPS
// Return:
// Measure of quality (absolute value) - caller uses this to weed out bad measurements
// In this impl. we return the time the measurement took - smallest values are best values
//
int ral_getTimesync (u1_t pps_en, sL_t* last_xtime, timesync_t* timesync) {
u4_t pps_xticks;
if( pps_en ) {
// First read last latched value - interval between time syncs needs to be >1s so that a PPS could have happened.
// Read last latched value - when PPS occurred. If no PPS happened this returns
// the time when LGW_GPS_EN was set to 1.
lgw_get_trigcnt(&pps_xticks);
#if defined(CFG_sx1302)
sx1302_gps_enable(false);
#else
lgw_reg_w(LGW_GPS_EN, 0); // PPS latch holds current
#endif
}
ustime_t t0 = rt_getTime();
u4_t xticks = 0;
#if defined(CFG_sx1302)
lgw_get_instcnt(&xticks);
#else
lgw_get_trigcnt(&xticks);
#endif
ustime_t t1 = rt_getTime();
sL_t d = (s4_t)(xticks - *last_xtime);
if( d < 0 ) {
LOG(MOD_SYN|CRITICAL, "SX130X time sync roll over - no update for a long time!");
d += (sL_t)1<<32;
}
timesync->xtime = *last_xtime += d;
timesync->ustime = (t0+t1)/2;
if( pps_en ) {
// PPS latch will hold now current xticks
#if defined(CFG_sx1302)
sx1302_gps_enable(true);
#else
lgw_reg_w(LGW_GPS_EN, 1);
#endif
timesync->pps_xtime = timesync->xtime + (s4_t)(pps_xticks - xticks);
} else {
// Signal no PPS
timesync->pps_xtime = 0;
}
return (int)(t1-t0);
}
#if defined(CFG_ral_lgw)
static u1_t pps_en;
static s2_t txpowAdjust; // scaled by TXPOW_SCALE
static sL_t last_xtime;
static tmr_t rxpollTmr;
static tmr_t syncTmr;
// ATTR_FASTCODE
static void synctime (tmr_t* tmr) {
timesync_t timesync;
int quality = ral_getTimesync(pps_en, &last_xtime, ×ync);
ustime_t delay = ts_updateTimesync(0, quality, ×ync);
rt_setTimer(&syncTmr, rt_micros_ahead(delay));
}
u1_t ral_altAntennas (u1_t txunit) {
return 0;
}
int ral_tx (txjob_t* txjob, s2ctx_t* s2ctx, int nocca) {
struct lgw_pkt_tx_s pkt_tx;
memset(&pkt_tx, 0, sizeof(pkt_tx));
if( txjob->preamble == 0 ) {
if( txjob->txflags & TXFLAG_BCN ) {
pkt_tx.tx_mode = ON_GPS;
pkt_tx.preamble = 10;
} else {
pkt_tx.tx_mode = TIMESTAMPED;
pkt_tx.preamble = 8;
}
} else {
pkt_tx.preamble = txjob->preamble;
}
rps_t rps = s2e_dr2rps(s2ctx, txjob->dr);
ral_rps2lgw(rps, &pkt_tx);
pkt_tx.freq_hz = txjob->freq;
pkt_tx.count_us = txjob->xtime;
pkt_tx.rf_chain = 0;
pkt_tx.rf_power = (float)(txjob->txpow - txpowAdjust) / TXPOW_SCALE;
pkt_tx.coderate = CR_LORA_4_5;
pkt_tx.invert_pol = true;
pkt_tx.no_crc = !txjob->addcrc;
pkt_tx.no_header = false;
pkt_tx.size = txjob->len;
memcpy(pkt_tx.payload, &s2ctx->txq.txdata[txjob->off], pkt_tx.size);
// NOTE: nocca not possible to implement with current libloragw API
#if defined(CFG_sx1302)
int err = lgw_send(&pkt_tx);
#else
int err = lgw_send(&pkt_tx);
#endif
if( err != LGW_HAL_SUCCESS ) {
if( err != LGW_LBT_ISSUE ) {
LOG(MOD_RAL|ERROR, "lgw_send failed");
return RAL_TX_FAIL;
}
return RAL_TX_NOCA;
}
return RAL_TX_OK;
}
int ral_txstatus (u1_t txunit) {
u1_t status;
#if defined(CFG_sx1302)
int err = lgw_status(txunit, TX_STATUS, &status);
#else
int err = lgw_status(txunit, TX_STATUS, &status);
#endif
if (err != LGW_HAL_SUCCESS) {
LOG(MOD_RAL|ERROR, "lgw_status failed");
return TXSTATUS_IDLE;
}
if( status == TX_SCHEDULED )
return TXSTATUS_SCHEDULED;
if( status == TX_EMITTING )
return TXSTATUS_EMITTING;
return TXSTATUS_IDLE;
}
void ral_txabort (u1_t txunit) {
#if defined(CFG_sx1302)
lgw_abort_tx(txunit);
#else
lgw_abort_tx();
#endif
}
//ATTR_FASTCODE
static void rxpolling (tmr_t* tmr) {
int rounds = 0;
while(rounds++ < RAL_MAX_RXBURST) {
struct lgw_pkt_rx_s pkt_rx;
int n = lgw_receive(1, &pkt_rx);
if( n < 0 || n > 1 ) {
LOG(MOD_RAL|ERROR, "lgw_receive error: %d", n);
break;
}
if( n==0 ) {
break;
}
LOG(XDEBUG, "RX mod=%s f=%d bw=%d sz=%d dr=%d %H", pkt_rx.modulation == 0x10 ? "LORA" : "FSK", pkt_rx.freq_hz, (int[]){0,500,250,125}[pkt_rx.bandwidth], pkt_rx.size, pkt_rx.datarate, pkt_rx.size, pkt_rx.payload);
rxjob_t* rxjob = !TC ? NULL : s2e_nextRxjob(&TC->s2ctx);
if( rxjob == NULL ) {
LOG(ERROR, "SX130X RX frame dropped - out of space");
break; // Allow to flush RX jobs
}
if( pkt_rx.status != STAT_CRC_OK ) {
LOG(XDEBUG, "Dropped frame without CRC or with broken CRC");
continue; // silently ignore bad CRC
}
if( pkt_rx.size > MAX_RXFRAME_LEN ) {
// This should not happen since caller provides
// space for max frame length - 255 bytes
LOG(MOD_RAL|ERROR, "Frame size (%d) exceeds offered buffer (%d)", pkt_rx.size, MAX_RXFRAME_LEN);
continue;
}
memcpy(&TC->s2ctx.rxq.rxdata[rxjob->off], pkt_rx.payload, pkt_rx.size);
rxjob->len = pkt_rx.size;
rxjob->freq = pkt_rx.freq_hz;
rxjob->xtime = ts_xticks2xtime(pkt_rx.count_us, last_xtime);
#if defined(CFG_sx1302)
rxjob->rssi = (u1_t)-pkt_rx.rssis;
#else
rxjob->rssi = (u1_t)-pkt_rx.rssic;
#endif
rxjob->snr = (s1_t)(pkt_rx.snr*4);
rps_t rps = ral_lgw2rps(&pkt_rx);
rxjob->dr = s2e_rps2dr(&TC->s2ctx, rps);
if( rxjob->dr == DR_ILLEGAL ) {
LOG(MOD_RAL|ERROR, "Unable to map to an up DR: %R", rps);
continue;
}
s2e_addRxjob(&TC->s2ctx, rxjob);
}
s2e_flushRxjobs(&TC->s2ctx);
rt_setTimer(tmr, rt_micros_ahead(RX_POLL_INTV));
}
int ral_config (str_t hwspec, u4_t cca_region, char* json, int jsonlen, chdefl_t* upchs) {
if( strcmp(hwspec, "sx1301/1") != 0 ) {
LOG(MOD_RAL|ERROR, "Unsupported hwspec=%s", hwspec);
return 0;
}
ujdec_t D;
uj_iniDecoder(&D, json, jsonlen);
if( uj_decode(&D) ) {
LOG(MOD_RAL|ERROR, "Parsing of sx130x channel setup JSON failed");
return 0;
}
if( uj_null(&D) ) {
LOG(MOD_RAL|ERROR, "sx130x_conf is null but a hw setup IS required - no fallbacks");
return 0;
}
uj_enterArray(&D);
int ok=0, slaveIdx;
while( (slaveIdx = uj_nextSlot(&D)) >= 0 ) {
dbuf_t json = uj_skipValue(&D);
if( slaveIdx == 0 ) {
struct sx130xconf sx130xconf;
int status = 0;
if( (status = !sx130xconf_parse_setup(&sx130xconf, -1, hwspec, json.buf, json.bufsize) << 0) ||
(status = !sx130xconf_challoc(&sx130xconf, upchs) << 1) ||
(status = !sys_runRadioInit(sx130xconf.device) << 2) ||
(status = !sx130xconf_start(&sx130xconf, cca_region) << 3) ) {
LOG(MOD_RAL|ERROR, "ral_config failed with status 0x%02x", status);
} else {
// Radio started
txpowAdjust = sx130xconf.txpowAdjust;
pps_en = sx130xconf.pps;
last_xtime = ts_newXtimeSession(0);
rt_yieldTo(&rxpollTmr, rxpolling);
rt_yieldTo(&syncTmr, synctime);
ok = 1;
}
}
}
uj_exitArray(&D);
uj_assertEOF(&D);
return ok;
}
// Lora gateway library is run locally - no subprocesses needed.
void ral_ini() {
last_xtime = 0;
rt_iniTimer(&rxpollTmr, rxpolling);
rt_iniTimer(&syncTmr, synctime);
}
void ral_stop() {
lgw_stop();
last_xtime = 0;
rt_clrTimer(&rxpollTmr);
rt_clrTimer(&syncTmr);
}
#endif // defined(CFG_ral_lgw)
#endif // defined(CFG_lgw1)
|
the_stack_data/906304.c
|
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// シグナルハンドラ <1>
void handler(int sig) { printf("received signal: %d\n", sig); }
int main(int argc, char *argv[]) {
// プロセスIDを表示 <2>
pid_t pid = getpid();
printf("pid: %d\n", pid);
// シグナルハンドラ登録
signal(SIGUSR1, handler); // <3>
// waitしているが、誰もnotifyしないので止まったままのはず <4>
pthread_mutex_lock(&mutex);
if (pthread_cond_wait(&cond, &mutex) != 0) {
perror("pthread_cond_wait");
exit(1);
}
printf("sprious wake up\n");
pthread_mutex_unlock(&mutex);
return 0;
}
|
the_stack_data/140766358.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <errno.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
struct timespec tp;
#define log_error(msg, ...) \
do { \
clock_gettime(CLOCK_MONOTONIC, &tp); \
if (errno > 0) { \
fprintf(stderr, "[%ld.%ld] [ERROR](%s:%d) "msg" [%s:%d]\n", \
tp.tv_sec, tp.tv_nsec, __FILE__, __LINE__, ##__VA_ARGS__, \
strerror(errno), errno); \
} \
else { \
fprintf(stderr, "[%ld.%ld] [ERROR](%s:%d)"msg"\n", \
tp.tv_sec, tp.tv_nsec, __FILE__, __LINE__, ##__VA_ARGS__); \
} \
fflush(stdout); \
} while (0)
#define exit_error(...) \
do { log_error(__VA_ARGS__); exit(EXIT_FAILURE); } while (0)
#define log_debug(msg, ...) \
do { \
clock_gettime(CLOCK_MONOTONIC, &tp); \
fprintf(stdout, "[%ld.%ld] [DEBUG] "msg"\n", \
tp.tv_sec, tp.tv_nsec, ##__VA_ARGS__); \
fflush(stdout); \
} while (0)
#define NUM_PRODUCERS 4
#define NUM_CONSUMERS 2
#define MAX_EVENTS_SIZE 1024
typedef struct thread_info {
pthread_t thread_id;
int rank;
int epfd;
} thread_info_t;
static void do_task() {
return;
}
static void *consumer_routine(void *data) {
struct thread_info *c = (struct thread_info *)data;
struct epoll_event *events;
int epfd = c->epfd;
int nfds = -1;
int i = -1;
int ret = -1;
uint64_t v;
int num_done = 0;
events = calloc(MAX_EVENTS_SIZE, sizeof(struct epoll_event));
if (events == NULL) exit_error("calloc epoll events\n");
for (;;) {
nfds = epoll_wait(epfd, events, MAX_EVENTS_SIZE, 1000);
for (i = 0; i < nfds; i++) {
if (events[i].events & EPOLLIN) {
log_debug("[consumer-%d] got event from fd-%d",
c->rank, events[i].data.fd);
ret = read(events[i].data.fd, &v, sizeof(v));
if (ret < 0) {
log_error("[consumer-%d] failed to read eventfd", c->rank);
continue;
}
close(events[i].data.fd);
do_task();
log_debug("[consumer-%d] tasks done: %d", c->rank, ++num_done);
}
}
}
}
// infinite constant workload
static void *producer_routine(void *data) {
struct thread_info *p = (struct thread_info *)data;
struct epoll_event event;
int epfd = p->epfd;
int efd = -1;
int ret = -1;
int interval = 1;
log_debug("[producer-%d] issues 1 task per %d second", p->rank, interval);
while (1) {
efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (efd == -1) exit_error("eventfd create: %s", strerror(errno));
event.data.fd = efd;
event.events = EPOLLIN | EPOLLET;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, efd, &event);
if (ret != 0) exit_error("epoll_ctl");
ret = write(efd, &(uint64_t){1}, sizeof(uint64_t));
if (ret != 8) log_error("[producer-%d] failed to write eventfd", p->rank);
sleep(interval);
}
}
// instant spike workload
static void *producer_routine_spike(void *data) {
struct thread_info *p = (struct thread_info *)data;
struct epoll_event event;
int epfd = p->epfd;
int efd = -1;
int ret = -1;
int num_task = 1000000;
log_debug("[producer-%d] will issue %d tasks", p->rank, num_task);
for (int i = 0; i < num_task; i++) {
efd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
if (efd == -1) exit_error("eventfd create: %s", strerror(errno));
event.data.fd = efd;
event.events = EPOLLIN | EPOLLET;
ret = epoll_ctl(epfd, EPOLL_CTL_ADD, efd, &event);
if (ret != 0) exit_error("epoll_ctl");
ret = write(efd, &(uint64_t){1}, sizeof(uint64_t));
if (ret != 8) log_error("[producer-%d] failed to write eventfd", p->rank);
}
return (void *)0;
}
int main(int argc, char *argv[]) {
struct thread_info *p_list = NULL, *c_list = NULL;
int epfd = -1;
int ret = -1, i = -1;
// create epoll fd
epfd = epoll_create1(EPOLL_CLOEXEC);
if (epfd == -1) exit_error("epoll_create1: %s", strerror(errno));
// start consumers (as task worker)
c_list = calloc(NUM_CONSUMERS, sizeof(struct thread_info));
if (!c_list) exit_error("calloc");
for (i = 0; i < NUM_CONSUMERS; i++) {
c_list[i].rank = i;
c_list[i].epfd = epfd;
ret = pthread_create(&c_list[i].thread_id, NULL, consumer_routine, &c_list[i]);
if (ret != 0) exit_error("pthread_create");
}
// start producers (as test load)
p_list = calloc(NUM_PRODUCERS, sizeof(struct thread_info));
if (!p_list) exit_error("calloc");
for (i = 0; i < NUM_PRODUCERS; i++) {
p_list[i].rank = i;
p_list[i].epfd = epfd;
ret = pthread_create(&p_list[i].thread_id, NULL, producer_routine, &p_list[i]);
if (ret != 0) exit_error("pthread_create");
}
// join and exit
for (i = 0; i < NUM_PRODUCERS; i++) {
ret = pthread_join(p_list[i].thread_id, NULL);
if (ret != 0) exit_error("pthread_join");
}
for (i = 0; i < NUM_CONSUMERS; i++) {
ret = pthread_join(c_list[i].thread_id, NULL);
if (ret != 0) exit_error("pthread_join");
}
free(p_list);
free(c_list);
return EXIT_SUCCESS;
}
|
the_stack_data/13594.c
|
/**
******************************************************************************
* @file stm32f3xx_ll_opamp.c
* @author MCD Application Team
* @brief OPAMP LL module driver
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under BSD 3-Clause license,
* the "License"; You may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
* opensource.org/licenses/BSD-3-Clause
*
******************************************************************************
*/
#if defined(USE_FULL_LL_DRIVER)
/* Includes ------------------------------------------------------------------*/
#include "stm32f3xx_ll_opamp.h"
#ifdef USE_FULL_ASSERT
#include "stm32_assert.h"
#else
#define assert_param(expr) ((void)0U)
#endif
/** @addtogroup STM32F3xx_LL_Driver
* @{
*/
#if defined (OPAMP1) || defined (OPAMP2) || defined (OPAMP3) || defined (OPAMP4)
/** @addtogroup OPAMP_LL OPAMP
* @{
*/
/* Private types -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private constants ---------------------------------------------------------*/
/* Private macros ------------------------------------------------------------*/
/** @addtogroup OPAMP_LL_Private_Macros
* @{
*/
/* Check of parameters for configuration of OPAMP hierarchical scope: */
/* OPAMP instance. */
#define IS_LL_OPAMP_FUNCTIONAL_MODE(__FUNCTIONAL_MODE__) \
( ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_STANDALONE) \
|| ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_FOLLOWER) \
|| ((__FUNCTIONAL_MODE__) == LL_OPAMP_MODE_PGA) \
)
/* Note: Comparator non-inverting inputs parameters are the same on all */
/* OPAMP instances. */
/* However, comparator instance kept as macro parameter for */
/* compatibility with other STM32 families. */
#define IS_LL_OPAMP_INPUT_NONINVERTING(__OPAMPX__, __INPUT_NONINVERTING__) \
( ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO0) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO1) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO2) \
|| ((__INPUT_NONINVERTING__) == LL_OPAMP_INPUT_NONINVERT_IO3) \
)
/* Note: Comparator non-inverting inputs parameters are the same on all */
/* OPAMP instances. */
/* However, comparator instance kept as macro parameter for */
/* compatibility with other STM32 families. */
#define IS_LL_OPAMP_INPUT_INVERTING(__OPAMPX__, __INPUT_INVERTING__) \
( ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_IO0) \
|| ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_IO1) \
|| ((__INPUT_INVERTING__) == LL_OPAMP_INPUT_INVERT_CONNECT_NO) \
)
/**
* @}
*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @addtogroup OPAMP_LL_Exported_Functions
* @{
*/
/** @addtogroup OPAMP_LL_EF_Init
* @{
*/
/**
* @brief De-initialize registers of the selected OPAMP instance
* to their default reset values.
* @note If comparator is locked, de-initialization by software is
* not possible.
* The only way to unlock the comparator is a device hardware reset.
* @param OPAMPx OPAMP instance
* @retval An ErrorStatus enumeration value:
* - SUCCESS: OPAMP registers are de-initialized
* - ERROR: OPAMP registers are not de-initialized
*/
ErrorStatus LL_OPAMP_DeInit(OPAMP_TypeDef* OPAMPx)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_OPAMP_ALL_INSTANCE(OPAMPx));
/* Note: Hardware constraint (refer to description of this function): */
/* OPAMP instance must not be locked. */
if (LL_OPAMP_IsLocked(OPAMPx) == 0U)
{
LL_OPAMP_WriteReg(OPAMPx, CSR, 0x00000000U);
}
else
{
/* OPAMP instance is locked: de-initialization by software is */
/* not possible. */
/* The only way to unlock the OPAMP is a device hardware reset. */
status = ERROR;
}
return status;
}
/**
* @brief Initialize some features of OPAMP instance.
* @note This function reset bit of calibration mode to ensure
* to be in functional mode, in order to have OPAMP parameters
* (inputs selection, ...) set with the corresponding OPAMP mode
* to be effective.
* @param OPAMPx OPAMP instance
* @param OPAMP_InitStruct Pointer to a @ref LL_OPAMP_InitTypeDef structure
* @retval An ErrorStatus enumeration value:
* - SUCCESS: OPAMP registers are initialized
* - ERROR: OPAMP registers are not initialized
*/
ErrorStatus LL_OPAMP_Init(OPAMP_TypeDef *OPAMPx, LL_OPAMP_InitTypeDef *OPAMP_InitStruct)
{
ErrorStatus status = SUCCESS;
/* Check the parameters */
assert_param(IS_OPAMP_ALL_INSTANCE(OPAMPx));
assert_param(IS_LL_OPAMP_FUNCTIONAL_MODE(OPAMP_InitStruct->FunctionalMode));
assert_param(IS_LL_OPAMP_INPUT_NONINVERTING(OPAMPx, OPAMP_InitStruct->InputNonInverting));
/* Note: OPAMP inverting input can be used with OPAMP in mode standalone */
/* or PGA with external capacitors for filtering circuit. */
/* Otherwise (OPAMP in mode follower), OPAMP inverting input is */
/* not used (not connected to GPIO pin). */
if (OPAMP_InitStruct->FunctionalMode != LL_OPAMP_MODE_FOLLOWER)
{
assert_param(IS_LL_OPAMP_INPUT_INVERTING(OPAMPx, OPAMP_InitStruct->InputInverting));
}
/* Note: Hardware constraint (refer to description of this function): */
/* OPAMP instance must not be locked. */
if (LL_OPAMP_IsLocked(OPAMPx) == 0U)
{
/* Configuration of OPAMP instance : */
/* - Functional mode */
/* - Input non-inverting */
/* - Input inverting */
/* Note: Bit OPAMP_CSR_CALON reset to ensure to be in functional mode. */
if (OPAMP_InitStruct->FunctionalMode != LL_OPAMP_MODE_FOLLOWER)
{
MODIFY_REG(OPAMPx->CSR,
OPAMP_CSR_CALON
| OPAMP_CSR_VMSEL
| OPAMP_CSR_VPSEL
,
OPAMP_InitStruct->FunctionalMode
| OPAMP_InitStruct->InputNonInverting
| OPAMP_InitStruct->InputInverting
);
}
else
{
MODIFY_REG(OPAMPx->CSR,
OPAMP_CSR_CALON
| OPAMP_CSR_VMSEL
| OPAMP_CSR_VPSEL
,
LL_OPAMP_MODE_FOLLOWER
| OPAMP_InitStruct->InputNonInverting
);
}
}
else
{
/* Initialization error: OPAMP instance is locked. */
status = ERROR;
}
return status;
}
/**
* @brief Set each @ref LL_OPAMP_InitTypeDef field to default value.
* @param OPAMP_InitStruct pointer to a @ref LL_OPAMP_InitTypeDef structure
* whose fields will be set to default values.
* @retval None
*/
void LL_OPAMP_StructInit(LL_OPAMP_InitTypeDef *OPAMP_InitStruct)
{
/* Set OPAMP_InitStruct fields to default values */
OPAMP_InitStruct->FunctionalMode = LL_OPAMP_MODE_FOLLOWER;
OPAMP_InitStruct->InputNonInverting = LL_OPAMP_INPUT_NONINVERT_IO0;
/* Note: Parameter discarded if OPAMP in functional mode follower, */
/* set anyway to its default value. */
OPAMP_InitStruct->InputInverting = LL_OPAMP_INPUT_INVERT_CONNECT_NO;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#endif /* OPAMP1 || OPAMP2 || OPAMP3 || OPAMP4 */
/**
* @}
*/
#endif /* USE_FULL_LL_DRIVER */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
the_stack_data/159515279.c
|
#include <stdio.h>
int main(void) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
printf("A = %d, B = %d, C = %d\n", a, b, c);
printf("A = %10d, B = %10d, C = %10d\n", a, b, c);
printf("A = %010d, B = %010d, C = %010d\n", a, b, c);
printf("A = %-10d, B = %-10d, C = %-10d\n", a, b, c);
return 0;
}
|
the_stack_data/85854.c
|
#include <stdio.h>
int main() {
float x,y,z;
printf("Entre com as 3 dimensões: ");
scanf("%f %f %f",&x,&y,&z);
if( x+y>z && x+z>y && z+y>x ){
if( x==y && y==z ){
printf("Equilatero\n");
}else if( x==y || y==z || x==z ){
printf("Isóceles\n");
}else{
printf("Escaleno\n");
}
}else{
printf("Não é triangulo\n");
}
return 0;
}
|
the_stack_data/48574032.c
|
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if(!strcmp(argv, "start", 5) || !strncmp(argv, "stop", 4))
return 1;
if(!fork()) {
setsid();
execvp("/usr/local/share/mysql/mysql.server", argv);
}
return 0;
}
|
the_stack_data/90764331.c
|
/* Disciplina: Computacao Concorrente */
/* Prof.: Silvana Rossetto */
/* Laboratório: 1 */
/* Codigo: "Hello World" usando threads em C com passagem de um argumento */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NTHREADS 10
//funcao executada pelas threads
void *PrintHello (void *arg) {
int idThread = *(int *) arg;
printf("Hello World da thread: %d\n", idThread);
free(arg);
pthread_exit(NULL);
}
//funcao principal do programa
int main() {
pthread_t tid_sistema[NTHREADS];
int t;
int *arg; //receberá o argumento para a thread
//int tid[NTHREADS];
for(t=0; t<NTHREADS; t++) {
//printf("--Aloca e preenche argumento com o identificador da thread na aplicacao %d\n", t);
arg = malloc(sizeof(int));
if (arg == NULL) {
printf("--ERRO: malloc()\n"); exit(-1);
}
*arg = t;
printf("--Argumento alocado para a thread %d no endereço %p:\n", *arg, arg);
printf("--Cria a thread %d\n", t);
//tid[t] = t;
//if (pthread_create(&tid_sistema[t], NULL, PrintHello, (void*) &tid[t])) {
if (pthread_create(&tid_sistema[t], NULL, PrintHello, (void*) arg)) {
//if (pthread_create(&tid_sistema[t], NULL, PrintHello, (void*) &t)) { //!!pode gerar erros!!
printf("--ERRO: pthread_create()\n"); exit(-1);
}
}
printf("--Thread principal terminou\n");
pthread_exit(NULL);
}
|
the_stack_data/104169.c
|
#include<stdio.h>
void main(){
char s[100];
int i,alphabet=0,used[26]={0};
printf("Enter the sentence : \n");
gets(s);
for(i=0;s[i]!='\0';i++){
if('a'<=s[i] && s[i]<='z'){
alphabet=alphabet+!used[s[i]-'a'];
used[s[i]-'a']=1;
}
else if('A'<=s[i] && s[i]<='Z'){
alphabet=alphabet+!used[s[i]-'A'];
used[s[i]-'A']=1;
}
}
printf("\n");
if(alphabet==26){
printf("PANAGRAM EXISTS");
}
else{
printf("PANAGRAM DOESN'T EXISTS");
}
}
|
the_stack_data/1055603.c
|
/* This testcase is part of GDB, the GNU debugger.
Copyright 2015-2017 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include <stddef.h>
#include <stdint.h>
typedef void (*testcase_ftype)(void);
/* Each function checks the correctness of the instruction being
relocated due to a fast tracepoint. Call function pass if it is
correct, otherwise call function fail. GDB sets a breakpoints on
pass and fail in order to check the correctness. */
static void
pass (void)
{
}
static void
fail (void)
{
}
#if (defined __x86_64__ || defined __i386__)
#ifdef SYMBOL_PREFIX
#define SYMBOL(str) SYMBOL_PREFIX #str
#else
#define SYMBOL(str) #str
#endif
/* Make sure we can relocate a CALL instruction. CALL instructions are
5 bytes long so we can always set a fast tracepoints on them.
JMP set_point0
f:
MOV $1, %[ok]
JMP end
set_point0:
CALL f ; tracepoint here.
end:
*/
static void
can_relocate_call (void)
{
int ok = 0;
asm (" .global " SYMBOL (set_point0) "\n"
" jmp " SYMBOL (set_point0) "\n"
"0:\n"
" mov $1, %[ok]\n"
" jmp 1f\n"
SYMBOL (set_point0) ":\n"
" call 0b\n"
"1:\n"
: [ok] "=r" (ok));
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate a JMP instruction. We need the JMP
instruction to be 5 bytes long in order to set a fast tracepoint on
it. To do this, we emit the opcode directly.
JMP next ; tracepoint here.
next:
MOV $1, %[ok]
*/
static void
can_relocate_jump (void)
{
int ok = 0;
asm (" .global " SYMBOL (set_point1) "\n"
SYMBOL (set_point1) ":\n"
".byte 0xe9\n" /* jmp */
".byte 0x00\n"
".byte 0x00\n"
".byte 0x00\n"
".byte 0x00\n"
" mov $1, %[ok]\n"
: [ok] "=r" (ok));
if (ok == 1)
pass ();
else
fail ();
}
#elif (defined __aarch64__)
/* Make sure we can relocate a B instruction.
B set_point0
set_ok:
MOV %[ok], #1
B end
set_point0:
B set_ok ; tracepoint here.
MOV %[ok], #0
end
*/
static void
can_relocate_b (void)
{
int ok = 0;
asm (" b set_point0\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point0:\n"
" b 0b\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok));
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate a B.cond instruction.
MOV x0, #8
TST x0, #8 ; Clear the Z flag.
B set_point1
set_ok:
MOV %[ok], #1
B end
set_point1:
B.NE set_ok ; tracepoint here.
MOV %[ok], #0
end
*/
static void
can_relocate_bcond_true (void)
{
int ok = 0;
asm (" mov x0, #8\n"
" tst x0, #8\n"
" b set_point1\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point1:\n"
" b.ne 0b\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0", "cc");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate a CBZ instruction.
MOV x0, #0
B set_point2
set_ok:
MOV %[ok], #1
B end
set_point2:
CBZ x0, set_ok ; tracepoint here.
MOV %[ok], #0
end
*/
static void
can_relocate_cbz (void)
{
int ok = 0;
asm (" mov x0, #0\n"
" b set_point2\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point2:\n"
" cbz x0, 0b\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate a CBNZ instruction.
MOV x0, #8
B set_point3
set_ok:
MOV %[ok], #1
B end
set_point3:
CBNZ x0, set_ok ; tracepoint here.
MOV %[ok], #0
end
*/
static void
can_relocate_cbnz (void)
{
int ok = 0;
asm (" mov x0, #8\n"
" b set_point3\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point3:\n"
" cbnz x0, 0b\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate a TBZ instruction.
MOV x0, #8
MVN x0, x0 ; Clear bit 3.
B set_point4
set_ok:
MOV %[ok], #1
B end
set_point4:
TBZ x0, #3, set_ok ; tracepoint here.
MOV %[ok], #0
end
*/
static void
can_relocate_tbz (void)
{
int ok = 0;
asm (" mov x0, #8\n"
" mvn x0, x0\n"
" b set_point4\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point4:\n"
" tbz x0, #3, 0b\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate a TBNZ instruction.
MOV x0, #8 ; Set bit 3.
B set_point5
set_ok:
MOV %[ok], #1
B end
set_point5:
TBNZ x0, #3, set_ok ; tracepoint here.
MOV %[ok], #0
end
*/
static void
can_relocate_tbnz (void)
{
int ok = 0;
asm (" mov x0, #8\n"
" b set_point5\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point5:\n"
" tbnz x0, #3, 0b\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate an ADR instruction with a positive offset.
set_point6:
ADR x0, target ; tracepoint here.
BR x0 ; jump to target
MOV %[ok], #0
B end
target:
MOV %[ok], #1
end
*/
static void
can_relocate_adr_forward (void)
{
int ok = 0;
asm ("set_point6:\n"
" adr x0, 0f\n"
" br x0\n"
" mov %[ok], #0\n"
" b 1f\n"
"0:\n"
" mov %[ok], #1\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate an ADR instruction with a negative offset.
B set_point7
target:
MOV %[ok], #1
B end
set_point7:
ADR x0, target ; tracepoint here.
BR x0 ; jump to target
MOV %[ok], #0
end
*/
static void
can_relocate_adr_backward (void)
{
int ok = 0;
asm ("b set_point7\n"
"0:\n"
" mov %[ok], #1\n"
" b 1f\n"
"set_point7:\n"
" adr x0, 0b\n"
" br x0\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0");
if (ok == 1)
pass ();
else
fail ();
}
/* Make sure we can relocate an ADRP instruction.
set_point8:
ADRP %[addr], set_point8 ; tracepoint here.
ADR %[pc], set_point8
ADR computes the address of the given label. While ADRP gives us its
page, on a 4K boundary. We can check ADRP executed normally by
making sure the result of ADR and ADRP are equivalent, except for the
12 lowest bits which should be cleared.
*/
static void
can_relocate_adrp (void)
{
uintptr_t page;
uintptr_t pc;
asm ("set_point8:\n"
" adrp %[page], set_point8\n"
" adr %[pc], set_point8\n"
: [page] "=r" (page), [pc] "=r" (pc));
if (page == (pc & ~0xfff))
pass ();
else
fail ();
}
/* Make sure we can relocate an LDR instruction, where the memory to
read is an offset from the current PC.
B set_point9
data:
.word 0x0cabba9e
set_point9:
LDR %[result], data ; tracepoint here.
*/
static void
can_relocate_ldr (void)
{
uint32_t result = 0;
asm ("b set_point9\n"
"0:\n"
" .word 0x0cabba9e\n"
"set_point9:\n"
" ldr %w[result], 0b\n"
: [result] "=r" (result));
if (result == 0x0cabba9e)
pass ();
else
fail ();
}
/* Make sure we can relocate a B.cond instruction and condition is false. */
static void
can_relocate_bcond_false (void)
{
int ok = 0;
asm (" mov x0, #8\n"
" tst x0, #8\n" /* Clear the Z flag. */
"set_point10:\n" /* Set tracepoint here. */
" b.eq 0b\n" /* Condition is false. */
" mov %[ok], #1\n"
" b 1f\n"
"0:\n"
" mov %[ok], #0\n"
"1:\n"
: [ok] "=r" (ok)
:
: "0", "cc");
if (ok == 1)
pass ();
else
fail ();
}
static void
foo (void)
{
}
/* Make sure we can relocate a BL instruction. */
static void
can_relocate_bl (void)
{
asm ("set_point11:\n"
" bl foo\n"
" bl pass\n"); /* Test that LR is updated correctly. */
}
#endif
/* Functions testing relocations need to be placed here. GDB will read
n_testcases to know how many fast tracepoints to place. It will look
for symbols in the form of 'set_point\[0-9\]+' so each functions
needs one, starting at 0. */
static testcase_ftype testcases[] = {
#if (defined __x86_64__ || defined __i386__)
can_relocate_call,
can_relocate_jump
#elif (defined __aarch64__)
can_relocate_b,
can_relocate_bcond_true,
can_relocate_cbz,
can_relocate_cbnz,
can_relocate_tbz,
can_relocate_tbnz,
can_relocate_adr_forward,
can_relocate_adr_backward,
can_relocate_adrp,
can_relocate_ldr,
can_relocate_bcond_false,
can_relocate_bl,
#endif
};
static size_t n_testcases = (sizeof (testcases) / sizeof (testcase_ftype));
int
main ()
{
int i = 0;
for (i = 0; i < n_testcases; i++)
testcases[i] ();
return 0;
}
|
the_stack_data/231393379.c
|
//
// Created by Michał Osadnik on 25/03/2018.
//
#include <stdlib.h>
int main() {
int a [5];
a[6] = 10;
return -1;
}
|
the_stack_data/117327908.c
|
int foo = 1;
|
the_stack_data/565303.c
|
#include<stdio.h>
int main(void){
int num = 4;
int den = 3;
float ratio;
char symbol;
ratio = (float)num/den; // converting the result to a flutuant point
symbol = (char)num/den;
printf("%.2f\n", ratio);
printf("%c\n", symbol);
return 0;
}
|
the_stack_data/37636576.c
|
#include <stdlib.h>
#define N 26
int main() {
unsigned char lower[N];
for (size_t i = 0; i < N; i++) {
lower[i] = i + 'a';
}
return EXIT_SUCCESS;
}
|
the_stack_data/182952013.c
|
// Copyright (c) 2017, Linaro Limited.
#ifdef BUILD_MODULE_DGRAM
// Zephyr includes
#include <net/net_context.h>
#include <net/net_pkt.h>
#include <net/udp.h>
#if defined(CONFIG_NET_L2_BT)
#include <bluetooth/bluetooth.h>
#endif
// ZJS includes
#include "zjs_buffer.h"
#include "zjs_callbacks.h"
#include "zjs_net_config.h"
#include "zjs_util.h"
static jerry_value_t zjs_dgram_socket_prototype;
typedef struct dgram_handle {
struct net_context *udp_sock;
zjs_callback_id message_cb_id;
zjs_callback_id error_cb_id;
} dgram_handle_t;
#define CHECK(x) \
ret = (x); \
if (ret < 0) { \
ERR_PRINT("Error in " #x ": %d\n", ret); \
return zjs_error(#x); \
}
// FIXME: Quick hack to allow context into the regular CHECK while fixing build
// for call sites without JS binding context
#define CHECK_ALT(x) \
ret = (x); \
if (ret < 0) { \
ERR_PRINT("Error in " #x ": %d\n", ret); \
return zjs_error_context(#x, 0, 0); \
}
#define GET_STR(jval, buf) \
{ \
jerry_size_t str_sz = sizeof(buf); \
zjs_copy_jstring(jval, buf, &str_sz); \
}
// Parse textual address of given address family (IPv4/IPv6) and numeric
// port and fill in sockaddr. Returns ZJS_UNDEFINED if everything is OK,
// or error instance otherwise.
static jerry_value_t get_addr(sa_family_t family,
const jerry_value_t addr,
const jerry_value_t port,
struct sockaddr *sockaddr)
{
// requires: addr must be a string value, and port must be a number value
int ret;
// We employ the fact that port and address offsets are the same for IPv4&6
struct sockaddr_in *sockaddr_in = (struct sockaddr_in *)sockaddr;
sockaddr_in->sin_family = family;
sockaddr_in->sin_port = htons((int)jerry_get_number_value(port));
jerry_size_t str_len = 40;
char addr_str[str_len];
zjs_copy_jstring(addr, addr_str, &str_len);
CHECK_ALT(net_addr_pton(family, addr_str, &sockaddr_in->sin_addr));
return ZJS_UNDEFINED;
}
static void zjs_dgram_free_cb(void *native)
{
dgram_handle_t *handle = (dgram_handle_t *)native;
DBG_PRINT("zjs_dgram_free_cb: %p\n", handle);
if (!handle) {
return;
}
if (handle->udp_sock) {
int ret = net_context_put(handle->udp_sock);
if (ret < 0) {
ERR_PRINT("dgram: net_context_put: err: %d\n", ret);
}
}
zjs_remove_callback(handle->message_cb_id);
zjs_remove_callback(handle->error_cb_id);
zjs_free(handle);
}
static const jerry_object_native_info_t dgram_type_info = {
.free_cb = zjs_dgram_free_cb
};
// Copy data from Zephyr net_pkt chain into linear buffer
static char *net_pkt_gather(struct net_pkt *pkt, char *to)
{
struct net_buf *tmp = pkt->frags;
int header_len = net_pkt_appdata(pkt) - tmp->data;
net_buf_pull(tmp, header_len);
while (tmp) {
memcpy(to, tmp->data, tmp->len);
to += tmp->len;
tmp = net_pkt_frag_del(pkt, NULL, tmp);
}
return to;
}
// Zephyr "packet received" callback
static void udp_received(struct net_context *context,
struct net_pkt *net_pkt,
int status,
void *user_data)
{
DBG_PRINT("udp_received: %p, buf=%p, st=%d, appdatalen=%d, udata=%p\n",
context, net_pkt, status, net_pkt_appdatalen(net_pkt), user_data);
dgram_handle_t *handle = user_data;
if (handle->message_cb_id == -1)
return;
int recv_len = net_pkt_appdatalen(net_pkt);
sa_family_t family = net_pkt_family(net_pkt);
char addr_str[40];
void *addr;
if (family == AF_INET) {
addr = &NET_IPV4_HDR(net_pkt)->src;
} else {
addr = &NET_IPV6_HDR(net_pkt)->src;
}
net_addr_ntop(family, addr, addr_str, sizeof(addr_str));
zjs_buffer_t *buf;
ZVAL_MUTABLE buf_js = zjs_buffer_create(recv_len, &buf);
ZVAL rinfo = zjs_create_object();
if (buf) {
struct net_udp_hdr placeholder;
struct net_udp_hdr *hdr = net_udp_get_hdr(net_pkt, &placeholder);
zjs_obj_add_number(rinfo, "port", ntohs(hdr->src_port));
zjs_obj_add_string(rinfo, "family",
family == AF_INET ? "IPv4" : "IPv6");
zjs_obj_add_string(rinfo, "address", addr_str);
net_pkt_gather(net_pkt, buf->buffer);
net_pkt_unref(net_pkt);
} else {
// can't pass object with error flag as a JS arg
jerry_value_clear_error_flag(&buf_js);
}
jerry_value_t args[2] = { buf_js, rinfo };
zjs_signal_callback(handle->message_cb_id, args, sizeof(args));
}
static ZJS_DECL_FUNC(zjs_dgram_createSocket)
{
// args: address family
ZJS_VALIDATE_ARGS(Z_STRING);
int ret;
char type_str[8];
GET_STR(argv[0], type_str);
sa_family_t family;
if (strequal(type_str, "udp4"))
family = AF_INET;
else if (strequal(type_str, "udp6"))
family = AF_INET6;
else
return zjs_error("invalid argument");
struct net_context *udp_sock;
CHECK(net_context_get(family, SOCK_DGRAM, IPPROTO_UDP, &udp_sock));
jerry_value_t sockobj = zjs_create_object();
jerry_set_prototype(sockobj, zjs_dgram_socket_prototype);
dgram_handle_t *handle = zjs_malloc(sizeof(dgram_handle_t));
if (!handle)
return zjs_error("out of memory");
handle->udp_sock = udp_sock;
handle->message_cb_id = -1;
handle->error_cb_id = -1;
jerry_set_object_native_pointer(sockobj, handle, &dgram_type_info);
// Can't call this here due to bug in Zephyr - called in .bind() instead
//CHECK(net_context_recv(udp_sock, udp_received, K_NO_WAIT, handle));
return sockobj;
}
static ZJS_DECL_FUNC(zjs_dgram_sock_on)
{
// args: event name, callback
ZJS_VALIDATE_ARGS(Z_STRING, Z_FUNCTION Z_NULL);
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
jerry_size_t str_sz = 32;
char event[str_sz];
zjs_copy_jstring(argv[0], event, &str_sz);
zjs_callback_id *cb_slot;
if (strequal(event, "message"))
cb_slot = &handle->message_cb_id;
else if (strequal(event, "error"))
cb_slot = &handle->error_cb_id;
else
return zjs_error("unsupported event type");
zjs_remove_callback(*cb_slot);
if (!jerry_value_is_null(argv[1]))
*cb_slot = zjs_add_callback(argv[1], this, handle, NULL);
return ZJS_UNDEFINED;
}
// Zephyr "packet sent" callback
static void udp_sent(struct net_context *context, int status, void *token,
void *user_data)
{
DBG_PRINT("udp_sent: %p, st=%d udata=%p\n", context, status, user_data);
if (user_data) {
ZVAL_MUTABLE rval = ZJS_UNDEFINED;
if (status != 0) {
char errbuf[8];
snprintf(errbuf, sizeof(errbuf), "%d", status);
rval = zjs_standard_error(NetworkError, errbuf, 0, 0);
// We need error object, not error value (JrS doesn't allow to
// pass the latter as a func argument).
jerry_value_clear_error_flag(&rval);
}
zjs_callback_id id = zjs_add_callback_once((jerry_value_t)user_data,
ZJS_UNDEFINED, NULL, NULL);
zjs_signal_callback(id, &rval, sizeof(rval));
}
}
static ZJS_DECL_FUNC(zjs_dgram_sock_send)
{
// NOTE: really argv[1] and argv[2] (offset and length) are supposed to be
// optional, which would require improvements to ZJS_VALIDATE_ARGS,
// but for now I'll leave them as required, as they were here before
// args: buffer, offset, length, port, address[, callback]
ZJS_VALIDATE_ARGS(Z_BUFFER, Z_NUMBER, Z_NUMBER, Z_NUMBER, Z_STRING,
Z_OPTIONAL Z_FUNCTION);
int ret;
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
zjs_buffer_t *buf = zjs_buffer_find(argv[0]);
int offset = (int)jerry_get_number_value(argv[1]);
int len = (int)jerry_get_number_value(argv[2]);
if (offset + len > buf->bufsize) {
return zjs_error("offset/len beyond buffer end");
}
sa_family_t family = net_context_get_family(handle->udp_sock);
struct sockaddr sockaddr_buf;
jerry_value_t err = get_addr(family, argv[4], argv[3], &sockaddr_buf);
if (err != ZJS_UNDEFINED)
return err;
struct net_pkt *send_buf = net_pkt_get_tx(handle->udp_sock, K_NO_WAIT);
if (!send_buf) {
return zjs_error("no netbuf");
}
if (!net_pkt_append(send_buf, len, buf->buffer + offset, K_NO_WAIT)) {
return zjs_error("no data netbuf");
}
void *user_data = NULL;
if (argc > 5) {
user_data = (void *)argv[5];
}
CHECK(net_context_sendto(send_buf, &sockaddr_buf, sizeof(sockaddr_buf),
udp_sent, K_NO_WAIT, NULL, user_data));
return ZJS_UNDEFINED;
}
static ZJS_DECL_FUNC(zjs_dgram_sock_bind)
{
// NOTE: really argv[0] and argv[1] are supposed to be optional, but
// leaving them as they were here for now
// args: port, address
ZJS_VALIDATE_ARGS(Z_NUMBER, Z_STRING);
int ret;
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
sa_family_t family = net_context_get_family(handle->udp_sock);
struct sockaddr sockaddr_buf;
jerry_value_t err = get_addr(family, argv[1], argv[0], &sockaddr_buf);
if (err != ZJS_UNDEFINED)
return err;
CHECK(net_context_bind(handle->udp_sock, &sockaddr_buf,
sizeof(sockaddr_buf)));
// See comment in createSocket() why this is called here
CHECK(net_context_recv(handle->udp_sock, udp_received, K_NO_WAIT, handle));
return ZJS_UNDEFINED;
}
static ZJS_DECL_FUNC(zjs_dgram_sock_close)
{
ZJS_GET_HANDLE(this, dgram_handle_t, handle, dgram_type_info);
zjs_dgram_free_cb((void *)handle);
return ZJS_UNDEFINED;
}
static void zjs_dgram_cleanup(void *native)
{
jerry_release_value(zjs_dgram_socket_prototype);
}
static const jerry_object_native_info_t dgram_module_type_info = {
.free_cb = zjs_dgram_cleanup
};
static jerry_value_t zjs_dgram_init()
{
zjs_net_config_default();
// create socket prototype object
zjs_native_func_t array[] = {
{ zjs_dgram_sock_on, "on" },
{ zjs_dgram_sock_send, "send" },
{ zjs_dgram_sock_bind, "bind" },
{ zjs_dgram_sock_close, "close" },
{ NULL, NULL }
};
zjs_dgram_socket_prototype = zjs_create_object();
zjs_obj_add_functions(zjs_dgram_socket_prototype, array);
// create module object
jerry_value_t dgram_obj = zjs_create_object();
zjs_obj_add_function(dgram_obj, "createSocket", zjs_dgram_createSocket);
// Set up cleanup function for when the object gets freed
jerry_set_object_native_pointer(dgram_obj, NULL, &dgram_module_type_info);
return dgram_obj;
}
JERRYX_NATIVE_MODULE(dgram, zjs_dgram_init)
#endif // BUILD_MODULE_DGRAM
|
the_stack_data/198581268.c
|
/* Copyright 2011-2017 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
int i1;
char gap1[32];
int i2;
char gap2[32];
int i3;
char gap3[32];
int i4;
void
trigger (void)
{
i1 = 1;
i2 = 2;
i3 = 3;
i4 = 4;
}
int
main ()
{
trigger ();
return 0;
}
|
the_stack_data/181393123.c
|
#include <stdio.h>
#include <string.h>
/*
* Objective: "Find the largest palindrome made from the product of two 3-digit numbers."
*/
static int is_palindrome(int n);
void problem_4()
{
int a, b, c, max = 0;
for (a = 100; a < 1000; a++) {
for (b = 100; b < 1000; b++) {
c = a * b;
if (is_palindrome(c) == 1 && c > max) {
max = c;
}
}
}
printf("Problem 4: %d\n", max);
}
static int is_palindrome(int n)
{
char str[6];
int len;
sprintf(str, "%d", n);
len = strlen(str);
for (int i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
return 0;
}
}
return 1;
}
|
the_stack_data/92329074.c
|
#include <stdio.h>
int main()
{
char product[10];
float value, newValue, discount;
printf("Product: ");
gets(product);
printf("%s value R$: ", product);
scanf("%f", &value);
printf("Discount amount (%%): ");
scanf("%f", &discount);
discount = discount / 100;
newValue = value - ( value * discount);
printf("\nOlder value: R$%.2f", value);
printf("\nNew value: R$%.2f\n", newValue);
}
|
the_stack_data/1172481.c
|
#include <stdio.h>
float area(int a, int b) {
return (a * b) / 2.0;
}
void main() {
FILE *input = fopen("input4.txt", "r");
FILE *output = fopen("output4.txt", "w");
int i;
int length[4][2];
//while(fscanf(input, "%d, %d", &length[n][m], &length[n][m]) != EOF);
//should use this with malloc
printf("Input (input4.txt) : \n");
for (i = 0; i < 4; i++) {
fscanf(input, "%d %d", &length[i][0], &length[i][1]);
// print the datas
fprintf(stdout, "%d %d\n", length[i][0], length[i][1]);
}
printf("\nOutput (output4.txt) : \n");
for (i = 0; i < 4; i++) {
// print the output datas
fprintf(stdout, "Adjacent : %d, Opposite : %d, Area of triangle : %.1f\n", length[i][0], length[i][1], area(length[i][0], length[i][1]));
// output the data to text file ("output.txt")
fprintf(output, "Adjacent : %d, Opposite : %d, Area of triangle : %.1f\n", length[i][0], length[i][1], area(length[i][0], length[i][1]));
}
fclose(input);
fclose(output);
}
|
the_stack_data/15763887.c
|
#include <stdio.h>
// what
/* abcee */
typedef enum {
T_Le = 256, T_Ge, T_Eq, T_Ne, T_And, T_Or, T_IntConstant,
T_StringConstant, T_Identifier, T_Void, T_Int, T_While,
T_If, T_Else, T_Return, T_Break, T_Continue, T_Print,
T_ReadInt
} TokenType;
static void print_token(int token) {
static char* token_strs[] = {
"T_Le", "T_Ge", "T_Eq", "T_Ne", "T_And", "T_Or", "T_IntConstant",
"T_StringConstant", "T_Identifier", "T_Void", "T_Int", "T_While",
"T_If", "T_Else", "T_Return", "T_Break", "T_Continue", "T_Print",
"T_ReadInt"
};
if (token < 256) {
printf("%-20c", token);
} else {
printf("%-20s", token_strs[token-256]);
}
}
int main(int argc,char **argv ){ //d d ddd
/* a
b
c
*/
char token = "";
int n;
while (scanf("%d",&n))
print_token(n);
return 0;
}
|
the_stack_data/818404.c
|
#include <stdio.h>
void scilab_rt_hist3d_d2i0i0_(int in00, int in01, double matrixin0[in00][in01],
int scalarin0,
int scalarin1)
{
int i;
int j;
double val0 = 0;
for (i = 0; i < in00; ++i) {
for (j = 0; j < in01; ++j) {
val0 += matrixin0[i][j];
}
}
printf("%f", val0);
printf("%d", scalarin0);
printf("%d", scalarin1);
}
|
the_stack_data/12636999.c
|
/* Author : Gangadhar, Akshat
1. For the given network graph, write a program to
* implement Link state routing algorithm
* build a routing table for the given node. */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define INFINITY 999
#define MAX 100
int cost[MAX][MAX]; // cost matrix
int distance[MAX]; // distance from source
int visited[MAX] = {0};
int parent[MAX];
int source;
int n; // number of nodes
void initialize()
{
int i;
visited[source] = 1;
parent[source] = source;
for(i=0; i<n; i++)
{
distance[i] = cost[source][i];
if( cost[source][i] != INFINITY )
{
parent[i] = source;
}
}
}
/* Get minimum distant node not already in network */
int GetMin()
{
int minIdx = -1;
int minDist = INFINITY;
int i;
for(i=0; i<n; i++)
{
if( !visited[i] && minDist >= distance[i] )
{
minIdx = i;
minDist = distance[i];
}
}
return minIdx;
}
/* update distance for adjacent nodes */
void updateTable(int node)
{
int i;
for(i=0; i<n; i++)
{
if( cost[node][i] != INFINITY && distance[i] > distance[node]+cost[node][i] )
{
distance[i] = distance[node] + cost[node][i];
parent[i] = node;
}
}
}
void display()
{
int i;
int node;
printf("\nNode \t Distance from source \t Path \n");
for(i=0; i<n; i++)
{
printf("%d \t\t %d \t\t", i, distance[i]);
// node <- parent[node] <- parent[parent[node]] <- ... <- source
node = i;
printf("%d", node);
while( node != source)
{
printf(" <- %d", parent[node]);
node = parent[node];
}
printf("\n");
}
}
int main()
{
int i, j, node;
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("Enter the source node : ");
scanf("%d", &source);
printf("\nEnter the cost matrix: \n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &cost[i][j]);
}
}
initialize();
for(i=0; i<n-1; i++) // for all remaining vertices(since source is already visited)
{
node = GetMin();
visited[node] = 1;
updateTable(node);
}
display();
return 0;
}
/**************** OUTPUT-1 ******************************
Enter the number of nodes: 9
Enter the source node : 3
Enter the cost matrix:
0 4 999 999 999 999 999 8 999
4 0 8 999 999 999 999 11 999
999 8 0 7 999 4 999 999 2
999 999 7 0 9 14 999 999 999
999 999 999 9 0 10 999 999 999
999 999 4 14 10 0 2 999 999
999 999 999 999 999 2 0 1 6
8 11 999 999 999 999 1 0 7
999 999 2 999 999 999 6 7 0
Node Distance from source Path
0 19 0 <- 1 <- 2 <- 3
1 15 1 <- 2 <- 3
2 7 2 <- 3
3 0 3
4 9 4 <- 3
5 11 5 <- 2 <- 3
6 13 6 <- 5 <- 2 <- 3
7 14 7 <- 6 <- 5 <- 2 <- 3
8 9 8 <- 2 <- 3
*************************************************************/
|
the_stack_data/374308.c
|
//bin/mkdir -p "${TMPDIR:-/tmp}/${d:=$(realpath -s "${0%/*}")}/${n:=${0##*/}}" && exec \
//usr/bin/make -C "$_" -sf/dev/null --eval="!:${n%.*};./$<" VPATH="$d" CFLAGS=-std=c99 LDFLAGS=-lX11 "$@"
// vim:ft=c
//---
// SUMMARY: grab global key <C-S-k> -- press to exit
// USAGE: $ ./$0
// WARN: NumLock, CapsLock are counted toward modifiers table!
// => hotkey doesn't match and isn't reported when NumLock is enabled
//---
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>
int
main()
{
Display* dpy = XOpenDisplay(0);
Window root = DefaultRootWindow(dpy);
XEvent ev;
unsigned int modifiers = ControlMask | ShiftMask;
int keycode = XKeysymToKeycode(dpy, XK_K);
Window grab_window = root;
Bool owner_events = False;
int pointer_mode = GrabModeAsync;
int keyboard_mode = GrabModeAsync;
XGrabKey(dpy, keycode, modifiers, grab_window, owner_events, pointer_mode, keyboard_mode);
XSelectInput(dpy, root, KeyPressMask);
int running = 1;
while (running) {
XNextEvent(dpy, &ev);
switch (ev.type) {
case KeyPress: {
printf("Hot key pressed!\n");
XUngrabKey(dpy, keycode, modifiers, grab_window);
running = 0;
} break;
default: break;
}
}
XCloseDisplay(dpy);
return 0;
}
|
the_stack_data/218893873.c
|
/* Unicode to ASCII character lookup tables for the ${codepage_description} codepage
* Unknown are filled with the ASCII replacement character 0x1a
*/
|
the_stack_data/200143205.c
|
#include <stdio.h>
double power(double x, int n);
int main(void) {
printf("%f", power(3,4));
}
double power(double x, int n) {
if (n==0) {
return 1;
}
return x*power(x, n-1);
}
|
the_stack_data/732624.c
|
#include<stdio.h>
#include<stdlib.h>
#include<locale.h>
/*Calculates the tax. *
*Women pay 10% *
*Man pay 15% */
int main()
{
setlocale(LC_ALL, "Portuguese");
float salary, tax;
char sex;
printf("Enter your salary: ");
scanf("%f", &salary);
fflush(stdin);
printf("Enter your sex[M/W]: ");
sex = getchar();
switch(sex)
{
case 'm':
case 'M': tax = 0.15;
break;
case 'w':
case 'W': tax = 0.1;
break;
}
printf("The tax will be %.2f!!!", salary * tax);
printf("\n\n");
system("pause");
return 0;
}
|
the_stack_data/98576720.c
|
/* { dg-do compile } */
/* { dg-options "--param asan-instrumentation-with-call-threshold=1 -ffat-lto-objects" } */
int x;
void f(int *a, int *b) {
*a = 0;
asm volatile ("" ::: "memory");
x = *b;
}
/* { dg-final { scan-assembler "__asan_store4" } } */
/* { dg-final { scan-assembler-not "__asan_report_store4" } } */
/* { dg-final { scan-assembler "__asan_load4" } } */
/* { dg-final { scan-assembler-not "__asan_report_load4" } } */
|
the_stack_data/112594.c
|
// RUN: mkdir -p %t.dir && cd %t.dir
// RUN: cp %s rel.c
// RUN: %clang_cc1 -fprofile-instrument=clang -fprofile-compilation-dir=/nonsense -fcoverage-mapping -emit-llvm -mllvm -enable-name-compression=false rel.c -o - | FileCheck -check-prefix=CHECK-NONSENSE %s
// CHECK-NONSENSE: nonsense
void f() {}
|
the_stack_data/75138762.c
|
#include <stdio.h>
#include <unistd.h>
int main() {
printf("Running...\n");
for (;;) {
sleep(1);
}
printf("END\n");
return 0;
}
|
the_stack_data/642.c
|
/* origin: FreeBSD /usr/src/lib/msun/src/e_pow.c */
/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* pow(x,y) return x**y
*
* n
* Method: Let x = 2 * (1+f)
* 1. Compute and return log2(x) in two pieces:
* log2(x) = w1 + w2,
* where w1 has 53-24 = 29 bit trailing zeros.
* 2. Perform y*log2(x) = n+y' by simulating muti-precision
* arithmetic, where |y'|<=0.5.
* 3. Return x**y = 2**n*exp(y'*log2)
*
* Special cases:
* 1. (anything) ** 0 is 1
* 2. 1 ** (anything) is 1
* 3. (anything except 1) ** NAN is NAN
* 4. NAN ** (anything except 0) is NAN
* 5. +-(|x| > 1) ** +INF is +INF
* 6. +-(|x| > 1) ** -INF is +0
* 7. +-(|x| < 1) ** +INF is +0
* 8. +-(|x| < 1) ** -INF is +INF
* 9. -1 ** +-INF is 1
* 10. +0 ** (+anything except 0, NAN) is +0
* 11. -0 ** (+anything except 0, NAN, odd integer) is +0
* 12. +0 ** (-anything except 0, NAN) is +INF, raise divbyzero
* 13. -0 ** (-anything except 0, NAN, odd integer) is +INF, raise divbyzero
* 14. -0 ** (+odd integer) is -0
* 15. -0 ** (-odd integer) is -INF, raise divbyzero
* 16. +INF ** (+anything except 0,NAN) is +INF
* 17. +INF ** (-anything except 0,NAN) is +0
* 18. -INF ** (+odd integer) is -INF
* 19. -INF ** (anything) = -0 ** (-anything), (anything except odd integer)
* 20. (anything) ** 1 is (anything)
* 21. (anything) ** -1 is 1/(anything)
* 22. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer)
* 23. (-anything except 0 and inf) ** (non-integer) is NAN
*
* Accuracy:
* pow(x,y) returns x**y nearly rounded. In particular
* pow(integer,integer)
* always returns the correct integer provided it is
* representable.
*
* Constants :
* The hexadecimal values are the intended ones for the following
* constants. The decimal values may be used, provided that the
* compiler will convert from decimal to binary accurately enough
* to produce the hexadecimal values shown.
*/
#include <stdint.h>
/* Get two 32 bit ints from a double. */
#define EXTRACT_WORDS(hi,lo,d) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
(hi) = __u.i >> 32; \
(lo) = (uint32_t)__u.i; \
} while (0)
#define FORCE_EVAL(x) do { \
if (sizeof(x) == sizeof(float)) { \
volatile float __x; \
__x = (x); \
} else if (sizeof(x) == sizeof(double)) { \
volatile double __x; \
__x = (x); \
} else { \
volatile long double __x; \
__x = (x); \
} \
} while(0)
/* Set the more significant 32 bits of a double from an int. */
#define SET_HIGH_WORD(d,hi) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
__u.i &= 0xffffffff; \
__u.i |= (uint64_t)(hi) << 32; \
(d) = __u.f; \
} while (0)
/* Set the less significant 32 bits of a double from an int. */
#define SET_LOW_WORD(d,lo) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
__u.i &= 0xffffffff00000000ull; \
__u.i |= (uint32_t)(lo); \
(d) = __u.f; \
} while (0)
/* Get the more significant 32 bit int from a double. */
#define GET_HIGH_WORD(hi,d) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
(hi) = __u.i >> 32; \
} while (0)
/* Get the less significant 32 bit int from a double. */
#define GET_LOW_WORD(lo,d) \
do { \
union {double f; uint64_t i;} __u; \
__u.f = (d); \
(lo) = (uint32_t)__u.i; \
} while (0)
static const double
bp[] = {1.0, 1.5,},
dp_h[] = { 0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */
dp_l[] = { 0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */
two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */
huge = 1.0e300,
tiny = 1.0e-300,
/* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */
L1 = 5.99999999999994648725e-01, /* 0x3FE33333, 0x33333303 */
L2 = 4.28571428578550184252e-01, /* 0x3FDB6DB6, 0xDB6FABFF */
L3 = 3.33333329818377432918e-01, /* 0x3FD55555, 0x518F264D */
L4 = 2.72728123808534006489e-01, /* 0x3FD17460, 0xA91D4101 */
L5 = 2.30660745775561754067e-01, /* 0x3FCD864A, 0x93C9DB65 */
L6 = 2.06975017800338417784e-01, /* 0x3FCA7E28, 0x4A454EEF */
P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */
P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */
P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */
P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */
P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */
lg2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */
lg2_h = 6.93147182464599609375e-01, /* 0x3FE62E43, 0x00000000 */
lg2_l = -1.90465429995776804525e-09, /* 0xBE205C61, 0x0CA86C39 */
ovt = 8.0085662595372944372e-017, /* -(1024-log2(ovfl+.5ulp)) */
cp = 9.61796693925975554329e-01, /* 0x3FEEC709, 0xDC3A03FD =2/(3ln2) */
cp_h = 9.61796700954437255859e-01, /* 0x3FEEC709, 0xE0000000 =(float)cp */
cp_l = -7.02846165095275826516e-09, /* 0xBE3E2FE0, 0x145B01F5 =tail of cp_h*/
ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */
ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2*/
ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail*/
double my_sqrt(double x);
double my_fabs(double x);
double my_scalbn(double x, int n);
double my_pow(double x, double y)
{
double z,ax,z_h,z_l,p_h,p_l;
double y1,t1,t2,r,s,t,u,v,w;
int32_t i,j,k,yisint,n;
int32_t hx,hy,ix,iy;
uint32_t lx,ly;
EXTRACT_WORDS(hx, lx, x);
EXTRACT_WORDS(hy, ly, y);
ix = hx & 0x7fffffff;
iy = hy & 0x7fffffff;
/* x**0 = 1, even if x is NaN */
if ((iy|ly) == 0)
return 1.0;
/* 1**y = 1, even if y is NaN */
if (hx == 0x3ff00000 && lx == 0)
return 1.0;
/* NaN if either arg is NaN */
if (ix > 0x7ff00000 || (ix == 0x7ff00000 && lx != 0) ||
iy > 0x7ff00000 || (iy == 0x7ff00000 && ly != 0))
return x + y;
/* determine if y is an odd int when x < 0
* yisint = 0 ... y is not an integer
* yisint = 1 ... y is an odd int
* yisint = 2 ... y is an even int
*/
yisint = 0;
if (hx < 0) {
if (iy >= 0x43400000)
yisint = 2; /* even integer y */
else if (iy >= 0x3ff00000) {
k = (iy>>20) - 0x3ff; /* exponent */
if (k > 20) {
j = ly>>(52-k);
if ((j<<(52-k)) == ly)
yisint = 2 - (j&1);
} else if (ly == 0) {
j = iy>>(20-k);
if ((j<<(20-k)) == iy)
yisint = 2 - (j&1);
}
}
}
/* special value of y */
if (ly == 0) {
if (iy == 0x7ff00000) { /* y is +-inf */
if (((ix-0x3ff00000)|lx) == 0) /* (-1)**+-inf is 1 */
return 1.0;
else if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */
return hy >= 0 ? y : 0.0;
else /* (|x|<1)**+-inf = 0,inf */
return hy >= 0 ? 0.0 : -y;
}
if (iy == 0x3ff00000) { /* y is +-1 */
if (hy >= 0)
return x;
y = 1/x;
#if FLT_EVAL_METHOD!=0
{
union {double f; uint64_t i;} u = {y};
uint64_t i = u.i & -1ULL/2;
if (i>>52 == 0 && (i&(i-1)))
FORCE_EVAL((float)y);
}
#endif
return y;
}
if (hy == 0x40000000) /* y is 2 */
return x*x;
if (hy == 0x3fe00000) { /* y is 0.5 */
if (hx >= 0) /* x >= +0 */
return my_sqrt(x);
}
}
ax = my_fabs(x);
/* special value of x */
if (lx == 0) {
if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { /* x is +-0,+-inf,+-1 */
z = ax;
if (hy < 0) /* z = (1/|x|) */
z = 1.0/z;
if (hx < 0) {
if (((ix-0x3ff00000)|yisint) == 0) {
z = (z-z)/(z-z); /* (-1)**non-int is NaN */
} else if (yisint == 1)
z = -z; /* (x<0)**odd = -(|x|**odd) */
}
return z;
}
}
s = 1.0; /* sign of result */
if (hx < 0) {
if (yisint == 0) /* (x<0)**(non-int) is NaN */
return (x-x)/(x-x);
if (yisint == 1) /* (x<0)**(odd int) */
s = -1.0;
}
/* |y| is huge */
if (iy > 0x41e00000) { /* if |y| > 2**31 */
if (iy > 0x43f00000) { /* if |y| > 2**64, must o/uflow */
if (ix <= 0x3fefffff)
return hy < 0 ? huge*huge : tiny*tiny;
if (ix >= 0x3ff00000)
return hy > 0 ? huge*huge : tiny*tiny;
}
/* over/underflow if x is not close to one */
if (ix < 0x3fefffff)
return hy < 0 ? s*huge*huge : s*tiny*tiny;
if (ix > 0x3ff00000)
return hy > 0 ? s*huge*huge : s*tiny*tiny;
/* now |1-x| is tiny <= 2**-20, suffice to compute
log(x) by x-x^2/2+x^3/3-x^4/4 */
t = ax - 1.0; /* t has 20 trailing zeros */
w = (t*t)*(0.5 - t*(0.3333333333333333333333-t*0.25));
u = ivln2_h*t; /* ivln2_h has 21 sig. bits */
v = t*ivln2_l - w*ivln2;
t1 = u + v;
SET_LOW_WORD(t1, 0);
t2 = v - (t1-u);
} else {
double ss,s2,s_h,s_l,t_h,t_l;
n = 0;
/* take care subnormal number */
if (ix < 0x00100000) {
ax *= two53;
n -= 53;
GET_HIGH_WORD(ix,ax);
}
n += ((ix)>>20) - 0x3ff;
j = ix & 0x000fffff;
/* determine interval */
ix = j | 0x3ff00000; /* normalize ix */
if (j <= 0x3988E) /* |x|<sqrt(3/2) */
k = 0;
else if (j < 0xBB67A) /* |x|<sqrt(3) */
k = 1;
else {
k = 0;
n += 1;
ix -= 0x00100000;
}
SET_HIGH_WORD(ax, ix);
/* compute ss = s_h+s_l = (x-1)/(x+1) or (x-1.5)/(x+1.5) */
u = ax - bp[k]; /* bp[0]=1.0, bp[1]=1.5 */
v = 1.0/(ax+bp[k]);
ss = u*v;
s_h = ss;
SET_LOW_WORD(s_h, 0);
/* t_h=ax+bp[k] High */
t_h = 0.0;
SET_HIGH_WORD(t_h, ((ix>>1)|0x20000000) + 0x00080000 + (k<<18));
t_l = ax - (t_h-bp[k]);
s_l = v*((u-s_h*t_h)-s_h*t_l);
/* compute log(ax) */
s2 = ss*ss;
r = s2*s2*(L1+s2*(L2+s2*(L3+s2*(L4+s2*(L5+s2*L6)))));
r += s_l*(s_h+ss);
s2 = s_h*s_h;
t_h = 3.0 + s2 + r;
SET_LOW_WORD(t_h, 0);
t_l = r - ((t_h-3.0)-s2);
/* u+v = ss*(1+...) */
u = s_h*t_h;
v = s_l*t_h + t_l*ss;
/* 2/(3log2)*(ss+...) */
p_h = u + v;
SET_LOW_WORD(p_h, 0);
p_l = v - (p_h-u);
z_h = cp_h*p_h; /* cp_h+cp_l = 2/(3*log2) */
z_l = cp_l*p_h+p_l*cp + dp_l[k];
/* log2(ax) = (ss+..)*2/(3*log2) = n + dp_h + z_h + z_l */
t = (double)n;
t1 = ((z_h + z_l) + dp_h[k]) + t;
SET_LOW_WORD(t1, 0);
t2 = z_l - (((t1 - t) - dp_h[k]) - z_h);
}
/* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */
y1 = y;
SET_LOW_WORD(y1, 0);
p_l = (y-y1)*t1 + y*t2;
p_h = y1*t1;
z = p_l + p_h;
EXTRACT_WORDS(j, i, z);
if (j >= 0x40900000) { /* z >= 1024 */
if (((j-0x40900000)|i) != 0) /* if z > 1024 */
return s*huge*huge; /* overflow */
if (p_l + ovt > z - p_h)
return s*huge*huge; /* overflow */
} else if ((j&0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */ // FIXME: instead of abs(j) use unsigned j
if (((j-0xc090cc00)|i) != 0) /* z < -1075 */
return s*tiny*tiny; /* underflow */
if (p_l <= z - p_h)
return s*tiny*tiny; /* underflow */
}
/*
* compute 2**(p_h+p_l)
*/
i = j & 0x7fffffff;
k = (i>>20) - 0x3ff;
n = 0;
if (i > 0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */
n = j + (0x00100000>>(k+1));
k = ((n&0x7fffffff)>>20) - 0x3ff; /* new k for n */
t = 0.0;
SET_HIGH_WORD(t, n & ~(0x000fffff>>k));
n = ((n&0x000fffff)|0x00100000)>>(20-k);
if (j < 0)
n = -n;
p_h -= t;
}
t = p_l + p_h;
SET_LOW_WORD(t, 0);
u = t*lg2_h;
v = (p_l-(t-p_h))*lg2 + t*lg2_l;
z = u + v;
w = v - (z-u);
t = z*z;
t1 = z - t*(P1+t*(P2+t*(P3+t*(P4+t*P5))));
r = (z*t1)/(t1-2.0) - (w + z*w);
z = 1.0 - (r-z);
GET_HIGH_WORD(j, z);
j += n<<20;
if ((j>>20) <= 0) /* subnormal output */
z = my_scalbn(z,n);
else
SET_HIGH_WORD(z, j);
return s*z;
}
|
the_stack_data/696340.c
|
static int foo(void)
{
int i = 123;
float x = ~i;
return (x < 0);
}
/*
* check-name: eval-bool-zext-neg
* check-command: test-linearize -Wno-decl $file
*
* check-output-ignore
* check-output-returns: 1
*/
|
the_stack_data/57072.c
|
#include <stdio.h>
int judge(int num[],int n,int target){
if(n == 1){
if(num[target] == 1){
return 1;
}
else{
return 0;
}
}
else{
if(target == 1){
for(int now=0; now<=1; now++){
if(num[now]>0){
num[now]--;
}
else{
continue;
}
if(now == 1){
if(judge(num,n-1,0))
return 1;
if(judge(num,n-1,1))
return 1;
}
else{
if(judge(num,n-1,0))
return 1;
}
num[now]++;
}
}
else{
if(num[0]>0){
num[0]--;
}
else{
return 0;
}
if(judge(num,n-1,1))
return 1;
num[0]++;
}
}
return 0;
}
int main(){
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++){
int n;
scanf("%d",&n);
int in;
int num[2] = {0};
for(int j=1;j<=n;j++){
scanf("%d",&in);
if(in == 0){
num[0]++;
}
else{
num[1]++;
}
}
int ans = judge(num,n,1);
if(ans){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}
|
the_stack_data/70734.c
|
// Copyright 2020, General Electric Company. All rights reserved. See https://github.com/xcist/code/blob/master/LICENSE
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* global storage for large vectors */
#define MAX_FFT_SIZE 2*2048*16
#define POLY_ORDER 4
/*
** TWIDDLE FACTOR TABLES FOR NEW FFT ROUTINES
*/
double twiddle[3*MAX_FFT_SIZE/4];
int bit_rev = 1;
double freqWindow[MAX_FFT_SIZE];
double starterKernel[MAX_FFT_SIZE];
double *starterKernelFft;
double reconFilterFft[MAX_FFT_SIZE];
double viewFft[MAX_FFT_SIZE];
double *tempArr;
void make_par_starter (int interp , int fftsiz , float detsp , double *startk) {
double sampleSpacing;
int hfftsz, iloop;
/* Clear starter kernel */
for ( iloop = 0; iloop < fftsiz; iloop++ )
startk[iloop] = 0.0;
hfftsz = fftsiz / 2;
sampleSpacing = detsp / (double) interp;
startk[0] = M_PI / (8.0 * sampleSpacing);
for ( iloop = 1; iloop <= hfftsz; iloop += 2 ) {
startk[iloop] = -1.0 / (2.0 * M_PI * sampleSpacing * iloop * iloop);
startk[fftsiz - iloop] = startk[iloop];
}
for(iloop=0;iloop<fftsiz;iloop++) {
/* startk[iloop] = 2.0 * (double) interp * sampleSpacing * startk[iloop]; */
startk[iloop] = 2.0 * (double) 2.0 * sampleSpacing * startk[iloop];
}
return;
}
#ifdef M_PI
#define TWO_PI 2.0*M_PI
#else
#define TWO_PI 6.2831853071795862
#endif
#ifdef M_SQRT1_2
#define RSQRT2 M_SQRT1_2
#else
#define RSQRT2 0.70710678118654752440
#endif
/*
** rvfft.c -- Real valued, in-place, Cooley-Tukey
** radix-2 FFT routine
**
** Real input and output in array x
**
** Length is N = 2 ** m
**
** Decimation in time, cos/sin in innermost loop
**
** Output in order:
** [Re(0),Re(1), ... ,Re(N/2),Im(N/2-1), ... , Im(1)]
**
** The sine/cosine table for the twiddle factors is
** expected to be supplied in the following format:
**
** twiddle[0] = sin(0*2*pi/n)
** twiddle[1] = sin(1*2*pi/n)
** ...
** twiddle[n/2 - 1] = sin((n/2-1)*2*pi/n)
**
** This corresponds to the first half period of a sine wave.
**
** Based on Sorensen et al.: Real Valued FFT Algorithms
** IEEE Transactions on Acoustics, Speech, and Signal Processing
** Vol. ASSP-35, No. 6, June 1987
*/
void rvfft( double x[], int n, int m, int bitrev, int twiddleNSize, double twiddle[] ){
int i,j,k;
int n1,n2,n4;
int i1, i2, i3, i4;
int stage;
int skip;
int separation;
int cosStart;
int sinStart;
int twiddleRatio;
double xt;
double cc,ss;
double t1,t2;
/*
** CALCULATE THE RATIO OF TWIDDLE FACTOR TABLE
*/
twiddleRatio = twiddleNSize/n;
/*
** separation between the sin and cos tables
** is the transform length divided by 4
*/
separation = (n >> 2) * twiddleRatio;
/*
** CHECK TO SEE IF WE DO THE BIT REVERSAL
*/
n1 = n-1;
n2 = (n >> 1);
if (bitrev)
{
j = 0;
for (i=1; i < n1; i++)
{
k = n2;
while (k <=j )
{
j = j - k;
k = (k >> 1);
}
j += k;
if (i < j)
{
xt = x[j];
x[j] = x[i];
x[i] = xt;
}
}
}
/*
** PERFORM THE LENGTH 2 BUTTERFLIES
** STAGE 1
*/
for (i=0; i<n; i+=2)
{
xt = x[i];
x[i] = xt + x[i+1];
x[i+1] = xt - x[i+1];
}
/*
** PERFORM THE REST OF THE STAGES
** STAGE 2 -> STAGE M
*/
n2 = 1;
for (stage = 2; stage <= m; stage++)
{
n4 = n2;
n2 = (n4 << 1);
n1 = (n2 << 1);
skip = (n >> stage) * twiddleRatio;
for (i=0; i<n; i+=n1)
{
xt = x[i];
x[i] = xt + x[i+n2];
x[i+n2] = xt - x[i+n2];
x[i+n4+n2] = -x[i+n4+n2];
sinStart = skip;
cosStart = skip + separation;
/*
** NOTE: THE FIRST RUN THROUGH N4 = 1
*/
for (j = 1; j < n4; j++)
{
i1 = i + j;
i2 = i - j + n2;
i3 = i + j + n2;
i4 = i - j + n1;
cc = twiddle[cosStart];
ss = twiddle[sinStart];
sinStart += skip;
cosStart += skip;
t1 = x[i3]*cc + x[i4]*ss;
t2 = x[i3]*ss - x[i4]*cc;
x[i4] = x[i2] - t2;
x[i3] = -x[i2] - t2;
x[i2] = x[i1] - t1;
x[i1] = x[i1] + t1;
}
}
}
}
/*
** irvfft.c -- Real valued, in-place, split-radix
** IFFT routine
**
** Hermitian symmetric imput and real output in array x
**
** Length is n = 2 ** m
**
** Decimation in frequency, cos/sin in second loop
**
** Input order:
** [Re(0),Re(1), ... ,Re(N/2),Im(N/2-1), ... , Im(1)]
**
** The sine/cosine table for the twiddle factors are
** expected to be supplied in the following order:
**
** twiddle[0] = sin(0*2*pi/n)
** twiddle[1] = sin(1*2*pi/n)
** ...
** twiddle[3*n/4 - 1] = sin((3*n/4-1)*2*pi/n)
**
** This corresponds to the first 3/4 period of a sine wave.
**
** Based on Sorensen et al.: Real Valued FFT Algorithms
** IEEE Transactions on Acoustics, Speech, and Signal Processing
** Vol. ASSP-35, No. 6, June 1987
*/
void irvfft(double x[], int n, int m, int bitrev, double twiddle[]) {
int i,j,k;
int n2,n4,n8;
int i0,i1,i2,i3,i4,i5,i6,i7,i8;
int is,id;
int n1;
int sinStart, sin3Start;
int cosStart, cos3Start;
int startAngle;
int separation;
double ss1, ss3;
double cc1, cc3;
double t1,t2,t3,t4,t5;
double xt;
double r1;
double scale;
n2 = n << 1;
separation = n/4;
for (k = 1; k < m; k++)
{
is = 0;
id = n2;
n2 = n2 >> 1;
n4 = n2 >> 2;
n8 = n4 >> 1;
startAngle = n/n2;
do
{
for (i=is; i<n; i+=id)
{
i1 = i;
i2 = i1 + n4;
i3 = i2 + n4;
i4 = i3 + n4;
t1 = x[i1] - x[i3];
x[i1] = x[i1] + x[i3];
x[i2] = 2.0 * x[i2];
x[i3] = t1 - 2.0 * x[i4];
x[i4] = t1 + 2.0 * x[i4];
if (n4 != 1)
{
i1 += n8;
i2 += n8;
i3 += n8;
i4 += n8;
t1 = (x[i2] - x[i1]) * RSQRT2;
t2 = (x[i4] + x[i3]) * RSQRT2;
x[i1] = x[i1] + x[i2];
x[i2] = x[i4] - x[i3];
x[i3] = 2.0 * (-t2-t1);
x[i4] = 2.0 * (-t2+t1);
}
}
is = (id << 1) - n2;
id = (id << 2);
} while ( is < (n-1) );
sinStart = startAngle;
cosStart = sinStart + separation;
for (j=2; j <= n8; j++)
{
sin3Start = 3*sinStart;
cos3Start = sin3Start + separation;
cc1 = twiddle[cosStart];
ss1 = twiddle[sinStart];
cc3 = twiddle[cos3Start];
ss3 = twiddle[sin3Start];
sinStart = j * startAngle;
cosStart = sinStart + separation;
is = 0;
id = 2 * n2;
do
{
for (i=is; i<n; i+=id)
{
i1 = i + j - 1;
i2 = i1 + n4;
i3 = i2 + n4;
i4 = i3 + n4;
i5 = i + n4 - j + 1;
i6 = i5 + n4;
i7 = i6 + n4;
i8 = i7 + n4;
t1 = x[i1] - x[i6];
x[i1] = x[i1] + x[i6];
t2 = x[i5] - x[i2];
x[i5] = x[i2] + x[i5];
t3 = x[i8] + x[i3];
x[i6] = x[i8] - x[i3];
t4 = x[i4] + x[i7];
x[i2] = x[i4] - x[i7];
t5 = t1 - t4;
t1 = t1 + t4;
t4 = t2 - t3;
t2 = t2 + t3;
x[i3] = t5 * cc1 + t4 * ss1;
x[i7] = -t4 * cc1 + t5 * ss1;
x[i4] = t1 * cc3 - t2 * ss3;
x[i8] = t2 * cc3 + t1 * ss3;
}
is = 2 * id - n2;
id = 4 * id;
} while ( is < (n-1) );
}
}
/*
** LENGTH TWO BUTTERFLIES
*/
is = 0;
id = 4;
do
{
for ( i0 = is; i0 < n; i0+= id)
{
i1 = i0 + 1;
r1 = x[i0];
x[i0] = r1 + x[i1];
x[i1] = r1 - x[i1];
}
is = (id << 1) - 2;
id = (id << 2);
} while ( is < n );
/*
** CHECK TO SEE IF WE DO THE BIT REVERSAL
*/
n1 = n-1;
n2 = (n >> 1);
if (bitrev)
{
j = 0;
for (i=1; i < n1; i++)
{
k = n2;
while (k <=j )
{
j = j - k;
k = (k >> 1);
}
j += k;
if (i < j)
{
xt = x[j];
x[j] = x[i];
x[i] = xt;
}
}
}
/*
** SCALE BY 1/N
*/
scale = 1.0/n;
for (i=0; i<n; i++)
x[i] *= scale;
}
/**********************************
** Calculate twiddle factors
**********************************/
void initrealroots(double *roots, unsigned int size) {
int k;
*roots++ = 1.0;
for (k=1; k< 3*size/4; k++)
{
*roots++ = sin(TWO_PI/(double)size * (double)k);
}
}
void make_starter(int interp, int fftsiz, double detsp, double stoi, double startk[])
{
double alpha, numerator, denominator;
int hfftsz, iloop;
/* Clear starter kernel */
for ( iloop = 0; iloop < fftsiz; iloop++ )
startk[iloop] = 0.0;
hfftsz = fftsiz / 2;
alpha = detsp / (double) interp / stoi;
numerator = -2.0 * alpha * alpha / M_PI;
/*
printf ("----- half fft size = %d\n", hfftsz);
printf ("----- alpha = %e and numerator = %e\n", alpha, numerator);
*/
startk[0] = M_PI / 2.0;
for ( iloop = 1; iloop <= hfftsz; iloop += 2 )
{
denominator = sin( (double) iloop * alpha );
denominator *= denominator;
startk[iloop] = numerator / denominator;
startk[fftsiz - iloop] = startk[iloop];
/* printf ("----- iloop = %d startk = %e\n", iloop, startk[iloop]); */
}
}
void make_window (float fcutof[], int porder, float mpolyc[], int wintyp, int interp, int fftsiz, double mwindw[]) {
double rbase, rtemp;
int halfft, nramp, nstart, nend, iloop, polyloop;
/* Determine start and end array indices for basic window array */
halfft = fftsiz/2;
nstart = (int) ( fcutof[0] * (float) (halfft + 1) + 0.9999999);
if (nstart < 0) nstart = 0;
nend = (int) ( fcutof[1] * (float) (halfft + 1) + 0.9999999);
if (nend > halfft) nend = halfft;
nramp = nend - nstart;
/* Clear basic window array */
for ( iloop=0; iloop <fftsiz; iloop++)
mwindw[iloop] = 0.0;
/* Fill basic window array with ones up to and including the
element following the start index */
for ( iloop = 0; iloop <= nstart; iloop++)
mwindw[iloop] = 1.0;
rbase = M_PI / (double) nramp;
/*
printf ("** Value of window step increment = %f\n", rbase);
*/
/* If window type == SINC, calculate a sync basic window */
if (wintyp == 1)
for ( iloop = 1; iloop < nramp; iloop++ )
{
rtemp = rbase * (float) iloop;
mwindw[nstart + iloop] = sin(rtemp) / rtemp;
}
/* Else assume window type == HANNING */
else
for ( iloop = 0; iloop < nramp; iloop++ )
mwindw[nstart + iloop] = 0.5*(1.0 + cos(rbase * (float) iloop));
rbase = 2.0 / (double) (fftsiz / interp);
/* Calculate the polynomial window */
for ( iloop = 0; iloop < halfft; iloop++ )
{
rtemp = mpolyc[0];
for ( polyloop = 1; polyloop <= porder; polyloop++ )
rtemp = rtemp*rbase*iloop + mpolyc[polyloop];
mwindw[iloop] *= (double)(interp * interp) * rtemp;
}
/* copy left half of window to righ half */
for ( iloop = 1; iloop < halfft; iloop++ )
mwindw[halfft+iloop] = mwindw[halfft-iloop];
}
#ifdef WIN32
__declspec(dllexport)
#endif
void gemsrampcurved(float*sino_in, float *sino_out, int windowType,
int freqInterp, float dfov, float detSpacing,
float fpixf, float fmax, float flow, float polyCoefs[5],
int numRows, int numCols, int numViews, float SID, int isParallel) {
int numPtsToConvolve = numCols;
int numDets = numPtsToConvolve;
int ifftSize;
/* find smallest power of 2 >= to numDets */
for (ifftSize = 1; ifftSize<numDets; ifftSize = ifftSize * 2);
ifftSize = ifftSize * 2; /* float fft size to avoid aliasing
due to circular convolution */
ifftSize = ifftSize * freqInterp;
/* account for zero padding */
/* cutoff frequency calculations */
float sampleSizeAtIso = detSpacing;
float pixelSize = dfov / 512; /* ASSUME 512 image size */
float pixelCutoff = sampleSizeAtIso / pixelSize;
float cutoffs[2];
/* high cutoff */
if (fmax < fpixf*pixelCutoff)
cutoffs[1] = fmax;
else
cutoffs[1] = fpixf*pixelCutoff;
/* low cutoff */
cutoffs[0] = flow * cutoffs[1];
/* divide cutoff freq's by freqInterp factor to avoid aliasing
due to the high freq we may have injected by adding
zeros between points */
cutoffs[1] = cutoffs[1] / freqInterp;
cutoffs[0] = cutoffs[0] / freqInterp;
int fftSize = ifftSize / freqInterp;
int numConvolvedPts = numPtsToConvolve * freqInterp;
if (isParallel == 0) {
make_starter(freqInterp, ifftSize, detSpacing, SID, starterKernel);
} else {
make_par_starter(freqInterp, ifftSize, sampleSizeAtIso, starterKernel);
}
/*
** NEW FFT
** INIT REAL ROOTS FOR FFT ROUTINES
*/
initrealroots(twiddle, ifftSize);
int ifftSizeD2 = ifftSize/2;
int fftSizeD2 = fftSize/2;
/* generate frequency domain "window" function */
make_window(cutoffs, POLY_ORDER, polyCoefs, windowType, freqInterp, ifftSize, freqWindow);
int log2ifftSize = (int)( log((double)ifftSize) / log(2.0) + 0.0001 );
int log2fftSize = log2ifftSize - freqInterp/2;
starterKernelFft = &starterKernel[0];
rvfft(starterKernelFft, ifftSize, log2ifftSize,
bit_rev, ifftSize, twiddle);
/* multiply window and fft of starter kernel and scale
(scale factor is non-unity only for parallel beam case)
note that imaginary portion of fft should be 0
since starterKernel is symmetric
*/
int i, j;
int viewNum, rows;
for (i=0; i<= ifftSize/2; i++) {
reconFilterFft[i] = freqWindow[i] * starterKernelFft[i];
}
/* what is ifft? */
/*** 'FILTERing VIEW LOOP' ***/
/* loop through projections. viewNum is 0-based and relative
to first view to process.
*/
for (viewNum=0; viewNum<numViews; viewNum++)
{
for(rows = 0; rows < numRows; rows++)
{
memset(viewFft, '\0', ifftSize*sizeof(double));
for (i=0; i<numPtsToConvolve; i++)
viewFft[i] = (double) sino_in[viewNum*numRows*numCols + rows*numCols + i];
/*
** TAKE FORWARD FFT
*/
rvfft(viewFft, fftSize, log2fftSize, bit_rev, ifftSize, twiddle);
/* Since we really wanted to inject zeros between every point
in the projection, use the DSP property that when zeros
are injected, the effect is to replicate the data in freq.
space. The fft would be periodic w/ freqInterp periods.
*/
/* freq. pt. @ Nyquist is a special case when we do interpolation
since it was origninally scaled by fftSize (not by fftSize/2
like the other non-zero frequencies)
*/
if (freqInterp > 1)
viewFft[fftSizeD2] *= 0.5;
/*
** NOW REPLICATE THE SPECTRUM freqInterp-1 TIMES
*/
tempArr = &freqWindow[0];
/*
** REPLICATE THE SPECTRUM
*/
if (freqInterp > 1) {
for (j=0; j<freqInterp/2; j++) {
int tempindex,tempindex1, tempindex2, tempindex3;
int index1, index2;
tempindex = j*fftSize;
tempindex1 = (j+1)*fftSize;
tempindex2 = freqInterp/4+2;
tempindex3 = freqInterp/4+1;
for (i=1; i<fftSizeD2; i++) {
/*
** THIS IS THE REAL PART
*/
index1 = i + tempindex;
index2 = i;
tempArr[index1] = viewFft[index2];
index1 = tempindex1 - i;
tempArr[index1] = viewFft[index2];
/*
** THIS IS THE IMAGINARY PART
*/
index1 = tempindex+(tempindex2*fftSize)-i;
index2 = fftSize - i;
tempArr[index1] = viewFft[index2];
index1 = tempindex+(tempindex3*fftSize)+i;
tempArr[index1] = -viewFft[index2];
}
/*
** THESE ARE THE SPECIAL CASES FOR THE REAL PART
*/
tempArr[j*fftSize] = viewFft[0];
tempArr[(j+1)*fftSize] = viewFft[0];
tempArr[(j*fftSize)+fftSizeD2] = 2.0*viewFft[fftSizeD2];
/*
** THESE ARE THE SPECIAL CASES FOR THE IMAGINARY PART
*/
tempArr[3*ifftSize/4] = 0.0;
index1 = (unsigned int)((0.5* (freqInterp + 1) + j) *fftSize);
tempArr[index1] = 0.0;
}
}
else /* no interpolation */
{
memcpy(tempArr, viewFft, fftSize*sizeof(double));
}
/*
** MULTIPLY BY THE FILTER AND TAKE THE INVERSE TRNASFORM
** WE TAKE INTO ACCOUNT THAT THE IMAGINARY PART OF THE
** RECON FILTER IS ZERO.
** (a+bi)(c+di) = ac + bci when d = 0
*/
viewFft[0] = reconFilterFft[0] * tempArr[0];
for (i=1; i < ifftSizeD2; i++)
{
viewFft[i] = reconFilterFft[i] * tempArr[i];
}
viewFft[ifftSizeD2] = reconFilterFft[ifftSizeD2] * tempArr[ifftSizeD2];
for (i=1; i < ifftSizeD2; i++)
{
viewFft[ifftSizeD2+i] = reconFilterFft[ifftSizeD2-i] * tempArr[ifftSizeD2+i];
}
/*
** TAKE INVERSE FFT
*/
irvfft(viewFft, ifftSize, log2ifftSize, bit_rev, twiddle);
/*
** CONVERT TO FLOAT FROM DOUBLE
*/
for (i=0; i<numConvolvedPts; i++)
sino_out[viewNum*numRows*freqInterp*numCols + rows*numCols*freqInterp + i] = (float)(viewFft[i]);
}
} /* end FILTERing VIEW LOOP */
}
#ifdef WIN32
__declspec(dllexport)
#endif
void gemsramp(float*sino_in, float *sino_out, int windowType,
int freqInterp, float dfov, float detSpacing,
float fpixf, float fmax, float flow, float polyCoefs[5],
int numRows, int numCols, int numViews) {
int numPtsToConvolve = numCols;
int numDets = numPtsToConvolve;
int ifftSize;
/* find smallest power of 2 >= to numDets */
for (ifftSize = 1; ifftSize<numDets; ifftSize = ifftSize * 2);
ifftSize = ifftSize * 2; /* float fft size to avoid aliasing
due to circular convolution */
ifftSize = ifftSize * freqInterp;
/* account for zero padding */
/* cutoff frequency calculations */
float sampleSizeAtIso = detSpacing;
float pixelSize = dfov / 512; /* ASSUME 512 image size */
float pixelCutoff = sampleSizeAtIso / pixelSize;
float cutoffs[2];
/* high cutoff */
if (fmax < fpixf*pixelCutoff)
cutoffs[1] = fmax;
else
cutoffs[1] = fpixf*pixelCutoff;
/* low cutoff */
cutoffs[0] = flow * cutoffs[1];
/* divide cutoff freq's by freqInterp factor to avoid aliasing
due to the high freq we may have injected by adding
zeros between points */
cutoffs[1] = cutoffs[1] / freqInterp;
cutoffs[0] = cutoffs[0] / freqInterp;
int fftSize = ifftSize / freqInterp;
int numConvolvedPts = numPtsToConvolve * freqInterp;
make_par_starter(freqInterp, ifftSize, detSpacing, starterKernel);
/*
** NEW FFT
** INIT REAL ROOTS FOR FFT ROUTINES
*/
initrealroots(twiddle, ifftSize);
int ifftSizeD2 = ifftSize/2;
int fftSizeD2 = fftSize/2;
/* generate frequency domain "window" function */
make_window(cutoffs, POLY_ORDER, polyCoefs, windowType, freqInterp, ifftSize, freqWindow);
int log2ifftSize = (int)( log((double)ifftSize) / log(2.0) + 0.0001 );
int log2fftSize = log2ifftSize - freqInterp/2;
starterKernelFft = &starterKernel[0];
rvfft(starterKernelFft, ifftSize, log2ifftSize,
bit_rev, ifftSize, twiddle);
/* multiply window and fft of starter kernel and scale
(scale factor is non-unity only for parallel beam case)
note that imaginary portion of fft should be 0
since starterKernel is symmetric
*/
int i, j;
int viewNum, rows;
for (i=0; i<= ifftSize/2; i++) {
reconFilterFft[i] = freqWindow[i] * starterKernelFft[i];
}
/* what is ifft? */
/*** 'FILTERing VIEW LOOP' ***/
/* loop through projections. viewNum is 0-based and relative
to first view to process.
*/
for (viewNum=0; viewNum<numViews; viewNum++)
{
for(rows = 0; rows < numRows; rows++)
{
memset(viewFft, '\0', ifftSize*sizeof(double));
for (i=0; i<numPtsToConvolve; i++)
viewFft[i] = (double) sino_in[viewNum*numRows*numCols + rows*numCols + i];
/*
** TAKE FORWARD FFT
*/
rvfft(viewFft, fftSize, log2fftSize, bit_rev, ifftSize, twiddle);
/* Since we really wanted to inject zeros between every point
in the projection, use the DSP property that when zeros
are injected, the effect is to replicate the data in freq.
space. The fft would be periodic w/ freqInterp periods.
*/
/* freq. pt. @ Nyquist is a special case when we do interpolation
since it was origninally scaled by fftSize (not by fftSize/2
like the other non-zero frequencies)
*/
viewFft[fftSizeD2] *= 0.5;
/*
** NOW REPLICATE THE SPECTRUM freqInterp-1 TIMES
*/
tempArr = &freqWindow[0];
/*
** REPLICATE THE SPECTRUM
*/
if (freqInterp > 1) {
for (j=0; j<freqInterp/2; j++) {
int tempindex,tempindex1, tempindex2, tempindex3;
int index1, index2;
tempindex = j*fftSize;
tempindex1 = (j+1)*fftSize;
tempindex2 = freqInterp/4+2;
tempindex3 = freqInterp/4+1;
for (i=1; i<fftSizeD2; i++) {
/*
** THIS IS THE REAL PART
*/
index1 = i + tempindex;
index2 = i;
tempArr[index1] = viewFft[index2];
index1 = tempindex1 - i;
tempArr[index1] = viewFft[index2];
/*
** THIS IS THE IMAGINARY PART
*/
index1 = tempindex+(tempindex2*fftSize)-i;
index2 = fftSize - i;
tempArr[index1] = viewFft[index2];
index1 = tempindex+(tempindex3*fftSize)+i;
tempArr[index1] = -viewFft[index2];
}
/*
** THESE ARE THE SPECIAL CASES FOR THE REAL PART
*/
tempArr[j*fftSize] = viewFft[0];
tempArr[(j+1)*fftSize] = viewFft[0];
tempArr[(j*fftSize)+fftSizeD2] = 2.0*viewFft[fftSizeD2];
/*
** THESE ARE THE SPECIAL CASES FOR THE IMAGINARY PART
*/
tempArr[3*ifftSize/4] = 0.0;
index1 = (unsigned int)((0.5* (freqInterp + 1) + j) *fftSize);
tempArr[index1] = 0.0;
}
}
else /* no interpolation */
{
memcpy(tempArr, viewFft, fftSize*sizeof(double));
}
/*
** MULTIPLY BY THE FILTER AND TAKE THE INVERSE TRNASFORM
** WE TAKE INTO ACCOUNT THAT THE IMAGINARY PART OF THE
** RECON FILTER IS ZERO.
** (a+bi)(c+di) = ac + bci when d = 0
*/
viewFft[0] = reconFilterFft[0] * tempArr[0];
for (i=1; i < ifftSizeD2; i++)
{
viewFft[i] = reconFilterFft[i] * tempArr[i];
}
viewFft[ifftSizeD2] = reconFilterFft[ifftSizeD2] * tempArr[ifftSizeD2];
for (i=1; i < ifftSizeD2; i++)
{
viewFft[ifftSizeD2+i] = reconFilterFft[ifftSizeD2-i] * tempArr[ifftSizeD2+i];
}
/*
** TAKE INVERSE FFT
*/
irvfft(viewFft, ifftSize, log2ifftSize, bit_rev, twiddle);
/*
** CONVERT TO FLOAT FROM DOUBLE
*/
for (i=0; i<numConvolvedPts; i++)
sino_out[viewNum*numRows*freqInterp*numCols + rows*numCols*freqInterp + i] = (float)(viewFft[i]);
}
} /* end FILTERing VIEW LOOP */
}
/*
* Includes the erroneous PI frequency
*/
void gemsramp_old(float*sino_in, float *sino_out, int windowType,
int freqInterp, float dfov, float detSpacing,
float fpixf, float fmax, float flow, float polyCoefs[5],
int numRows, int numCols, int numViews) {
int numPtsToConvolve = numCols;
int numDets = numPtsToConvolve;
int ifftSize;
/* find smallest power of 2 >= to numDets */
for (ifftSize = 1; ifftSize<numDets; ifftSize = ifftSize * 2);
ifftSize = ifftSize * 2; /* float fft size to avoid aliasing
due to circular convolution */
ifftSize = ifftSize * freqInterp;
/* account for zero padding */
/* cutoff frequency calculations */
float sampleSizeAtIso = detSpacing;
float pixelSize = dfov / 512; /* ASSUME 512 image size */
float pixelCutoff = sampleSizeAtIso / pixelSize;
float cutoffs[2];
/* high cutoff */
if (fmax < fpixf*pixelCutoff)
cutoffs[1] = fmax;
else
cutoffs[1] = fpixf*pixelCutoff;
/* low cutoff */
cutoffs[0] = flow * cutoffs[1];
/* divide cutoff freq's by freqInterp factor to avoid aliasing
due to the high freq we may have injected by adding
zeros between points */
cutoffs[1] = cutoffs[1] / freqInterp;
cutoffs[0] = cutoffs[0] / freqInterp;
int fftSize = ifftSize / freqInterp;
int numConvolvedPts = numPtsToConvolve * freqInterp;
make_par_starter(freqInterp, ifftSize, detSpacing, starterKernel);
/*
** NEW FFT
** INIT REAL ROOTS FOR FFT ROUTINES
*/
initrealroots(twiddle, ifftSize);
int ifftSizeD2 = ifftSize/2;
int fftSizeD2 = fftSize/2;
/* generate frequency domain "window" function */
make_window(cutoffs, POLY_ORDER, polyCoefs, windowType, freqInterp, ifftSize, freqWindow);
int log2ifftSize = (int)( log((double)ifftSize) / log(2.0) + 0.0001 );
int log2fftSize = log2ifftSize - freqInterp/2;
starterKernelFft = &starterKernel[0];
rvfft(starterKernelFft, ifftSize, log2ifftSize,
bit_rev, ifftSize, twiddle);
/* multiply window and fft of starter kernel and scale
(scale factor is non-unity only for parallel beam case)
note that imaginary portion of fft should be 0
since starterKernel is symmetric
*/
int i, j;
int viewNum, rows;
for (i=0; i<= ifftSize/2; i++) {
reconFilterFft[i] = freqWindow[i] * starterKernelFft[i];
}
/* what is ifft? */
/*** 'FILTERing VIEW LOOP' ***/
/* loop through projections. viewNum is 0-based and relative
to first view to process.
*/
for (viewNum=0; viewNum<numViews; viewNum++)
{
for(rows = 0; rows < numRows; rows++)
{
memset(viewFft, '\0', ifftSize*sizeof(double));
for (i=0; i<numPtsToConvolve; i++)
viewFft[i] = (double) sino_in[viewNum*numRows*numCols + rows*numCols + i];
/*
** TAKE FORWARD FFT
*/
rvfft(viewFft, fftSize, log2fftSize, bit_rev, ifftSize, twiddle);
/* Since we really wanted to inject zeros between every point
in the projection, use the DSP property that when zeros
are injected, the effect is to replicate the data in freq.
space. The fft would be periodic w/ freqInterp periods.
*/
/* freq. pt. @ Nyquist is a special case when we do interpolation
since it was origninally scaled by fftSize (not by fftSize/2
like the other non-zero frequencies)
*/
viewFft[fftSizeD2] *= 0.5;
/*
** NOW REPLICATE THE SPECTRUM freqInterp-1 TIMES
*/
tempArr = &freqWindow[0];
/*
** REPLICATE THE SPECTRUM
*/
if (freqInterp > 1) {
for (j=0; j<freqInterp/2; j++) {
int tempindex,tempindex1, tempindex2, tempindex3;
int index1, index2;
tempindex = j*fftSize;
tempindex1 = (j+1)*fftSize;
tempindex2 = freqInterp/4+2;
tempindex3 = freqInterp/4+1;
for (i=1; i<fftSizeD2; i++) {
/*
** THIS IS THE REAL PART
*/
index1 = i + tempindex;
index2 = i;
tempArr[index1] = viewFft[index2];
index1 = tempindex1 - i;
tempArr[index1] = viewFft[index2];
/*
** THIS IS THE IMAGINARY PART
*/
index1 = tempindex+(tempindex2*fftSize)-i;
index2 = fftSize - i;
tempArr[index1] = viewFft[index2];
index1 = tempindex+(tempindex3*fftSize)+i;
tempArr[index1] = -viewFft[index2];
}
/*
** THESE ARE THE SPECIAL CASES FOR THE REAL PART
*/
tempArr[j*fftSize] = viewFft[0];
tempArr[(j+1)*fftSize] = viewFft[0];
tempArr[(j*fftSize)+fftSizeD2] = viewFft[fftSizeD2];
/*
** THESE ARE THE SPECIAL CASES FOR THE IMAGINARY PART
*/
tempArr[3*ifftSize/4] = 0.0;
index1 = (unsigned int)((0.5* (freqInterp + 1) + j) *fftSize);
tempArr[index1] = 0.0;
}
}
else /* no interpolation */
{
memcpy(tempArr, viewFft, fftSize*sizeof(double));
}
/*
** MULTIPLY BY THE FILTER AND TAKE THE INVERSE TRNASFORM
** WE TAKE INTO ACCOUNT THAT THE IMAGINARY PART OF THE
** RECON FILTER IS ZERO.
** (a+bi)(c+di) = ac + bci when d = 0
*/
viewFft[0] = reconFilterFft[0] * tempArr[0];
for (i=1; i < ifftSizeD2; i++)
{
viewFft[i] = reconFilterFft[i] * tempArr[i];
}
viewFft[ifftSizeD2] = reconFilterFft[ifftSizeD2] * tempArr[ifftSizeD2];
for (i=1; i < ifftSizeD2; i++)
{
viewFft[ifftSizeD2+i] = reconFilterFft[ifftSizeD2-i] * tempArr[ifftSizeD2+i];
}
/*
** TAKE INVERSE FFT
*/
irvfft(viewFft, ifftSize, log2ifftSize, bit_rev, twiddle);
/*
** CONVERT TO FLOAT FROM DOUBLE
*/
for (i=0; i<numConvolvedPts; i++)
sino_out[viewNum*numRows*freqInterp*numCols + rows*numCols*freqInterp + i] = (float)(viewFft[i]);
}
} /* end FILTERing VIEW LOOP */
}
|
the_stack_data/176706784.c
|
/* ヘッダを使い、循環させる場合の連結リストのプログラム
* L => Head => Cell(1) => Cell(2) => ... => Cell(n) => Head => ...
*/
#include<stdlib.h>
#include<stdio.h>
typedef int elemtype;
typedef struct Lcell *List;
struct Lcell {
elemtype element;
struct Lcell *next;
};
struct Lcell *GetNewCell() {
struct Lcell *cell;
cell = (struct Lcell *)malloc(sizeof(struct Lcell));
return cell;
}
List LCreate() {
List head;
head = GetNewCell();
head->next = head; // 循環させる
return head;
}
List Tail(List L) {
List p = L;
while(p->next != L) {
p = p->next;
}
return p;
}
int Length(List L) {
int len = 0;
List p = L->next;
while(p != L) { // Lはヘッダ
len++;
p = p->next;
}
return len;
}
List Insert(elemtype x, List p) {
// pの末尾にxを追加する
struct Lcell *newcell;
newcell = GetNewCell();
newcell->element = x;
newcell->next = p;
Tail(p)->next = newcell;
return p;
}
List Merge(List L1, List L2) {
List head = LCreate(), p1 = L1->next, p2 = L2->next;
// p1とp2を比較しながら末尾にインサートする
while (p1 != L1 && p2 != L2) { // L1とL2はヘッダ
if (p1->element < p2->element) {
Insert(p1->element, head);
p1 = p1->next;
} else {
Insert(p2->element, head);
p2 = p2->next;
}
}
// p1かp2の要素がまだ残っている場合はマージした後に付け加える
while (p1 != L1) {
Insert(p1->element, head);
p1 = p1->next;
}
while (p2 != L2) {
Insert(p2->element, head);
p2 = p2->next;
}
return head;
}
void Show(List L) {
List p = L->next;
while(p != L) {
printf("%d ", p->element);
p = p->next;
}
printf("\n");
}
void Delete(List L) {
List p = Tail(L);
while (p != L) {
printf("ただいまのリスト"); Show(L);
Tail(Tail(L))->next = L; // Tail(Tail(L))は末尾から2番目なのでこれをヘッダにつなぐ
free(p);
p = Tail(L);
}
}
int main() {
List L1, L2;
int buf;
L1 = LCreate();
L2 = LCreate();
printf("要素をリストL1, L2の末尾に追加します\n");
printf("L1の要素を入力\n");
while(scanf("%d", &buf) != EOF) {
L1 = Insert(buf, L1);
}
printf("L2の要素を入力\n");
while(scanf("%d", &buf) != EOF) {
L2 = Insert(buf, L2);
}
printf("L1の長さは %d\n", Length(L1));
printf("L2の長さは %d\n", Length(L2));
printf("L1の要素は "); Show(L1);
printf("L2の要素は "); Show(L2);
printf("L1とL2をマージしたリストの要素は "); Show(Merge(L1, L2));
Delete(L1);
Delete(L2);
return 0;
}
|
the_stack_data/206392034.c
|
/*
* set-baudrate.c
*
* Based on direct-tcgets2-test.c in http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=683826
*
* Created on: 22 Jan 2014
* Author: henryk
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include "/usr/include/asm-generic/termbits.h"
#include "/usr/include/asm-generic/ioctls.h"
static int set_baudrate(int fh, int baudrate)
{
int r;
struct termios2 to;
r = ioctl(0, TCGETS2, &to);
if(r) {
perror("TCGETS2");
return -1;
}
to.c_ispeed = to.c_ospeed = baudrate;
to.c_cflag &= ~CBAUD;
to.c_cflag |= BOTHER;
r = ioctl(0, TCSETS2, &to);
if(r) {
perror("TCSETS2");
return -1;
}
return 0;
}
int main(int argc, const char **argv)
{
int fh, baudrate;
if(argc != 3) {
fprintf(stderr, "Usage: %s devicenode baudrate\n", argv[0]);
return -1;
}
fh = open(argv[1], O_RDWR | O_NOCTTY);
if(fh < 0) {
perror("open");
return -1;
}
baudrate = atoi(argv[2]);
if(set_baudrate(fh, baudrate) < 0) {
return -1;
}
return 0;
}
|
the_stack_data/215767685.c
|
#include <stdio.h>
static struct sss{
double f;
struct {float m;} snd;
} sss;
#define _offsetof(st,f) ((char *)&((st *) 16)->f - (char *) 16)
int main (void) {
printf ("+++Struct float inside struct starting with double:\n");
printf ("size=%d,align=%d\n", sizeof (sss), __alignof__ (sss));
printf ("offset-double=%d,offset-sss-float=%d,\nalign-double=%d,align-sss-float=%d\n",
_offsetof (struct sss, f), _offsetof (struct sss, snd),
__alignof__ (sss.f), __alignof__ (sss.snd));
return 0;
}
|
the_stack_data/90272.c
|
#include<stdio.h>
int comb_num(int, int);
int main()
{
int m, n;
scanf("%d%d", &m, &n);
printf("%d\n", comb_num(m, n));
return 0;
}
int comb_num(int m, int n)
{
if ( m<n || m<1 || n<1 )
return 0;
if ( n == 1 )
return m;
if ( n == m )
return 1;
return comb_num(m-1, n) +comb_num(m-1, n-1);
}
|
the_stack_data/93888670.c
|
/* File csplit14.src-a/pretty14.c */
int i;
void prettyprint(void)
{
/* File csplit14.src-a/pretty14.c */
i = 1;
}
|
the_stack_data/780279.c
|
/*
SDL_mixer: An audio mixer library based on the SDL library
Copyright (C) 1997-2017 Sam Lantinga <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#ifdef MUSIC_MP3_MAD
#include "music_mad.h"
#include "mad.h"
/* NOTE: The dithering functions are GPL, which should be fine if your
application is GPL (which would need to be true if you enabled
libmad support in SDL_mixer). If you're using libmad under the
commercial license, you need to disable this code.
*/
/************************ dithering functions ***************************/
#ifdef MUSIC_MP3_MAD_GPL_DITHERING
/* All dithering done here is taken from the GPL'ed xmms-mad plugin. */
/* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */
/* Any feedback is very welcome. For any question, comments, */
/* see http://www.math.keio.ac.jp/matumoto/emt.html or email */
/* [email protected] */
/* Period parameters */
#define MP3_DITH_N 624
#define MP3_DITH_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)
static unsigned long mt[MP3_DITH_N]; /* the array for the state vector */
static int mti=MP3_DITH_N+1; /* mti==MP3_DITH_N+1 means mt[MP3_DITH_N] is not initialized */
/* initializing the array with a NONZERO seed */
static void sgenrand(unsigned long seed)
{
/* setting initial seeds to mt[MP3_DITH_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<MP3_DITH_N; mti++)
mt[mti] = (69069 * mt[mti-1]) & 0xffffffff;
}
static unsigned long genrand(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= MP3_DITH_N) { /* generate MP3_DITH_N words at one time */
int kk;
if (mti == MP3_DITH_N+1) /* if sgenrand() has not been called, */
sgenrand(4357); /* a default initial seed is used */
for (kk=0;kk<MP3_DITH_N-MP3_DITH_M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+MP3_DITH_M] ^ (y >> 1) ^ mag01[y & 0x1];
}
for (;kk<MP3_DITH_N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(MP3_DITH_M-MP3_DITH_N)] ^ (y >> 1) ^ mag01[y & 0x1];
}
y = (mt[MP3_DITH_N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[MP3_DITH_N-1] = mt[MP3_DITH_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);
return y;
}
static long triangular_dither_noise(int nbits) {
/* parameter nbits : the peak-to-peak amplitude desired (in bits)
* use with nbits set to 2 + nber of bits to be trimmed.
* (because triangular is made from two uniformly distributed processes,
* it starts at 2 bits peak-to-peak amplitude)
* see The Theory of Dithered Quantization by Robert Alexander Wannamaker
* for complete proof of why that's optimal
*/
long v = (genrand()/2 - genrand()/2); /* in ]-2^31, 2^31[ */
long P = 1 << (32 - nbits); /* the power of 2 */
v /= P;
/* now v in ]-2^(nbits-1), 2^(nbits-1) [ */
return v;
}
#endif /* MUSIC_MP3_MAD_GPL_DITHERING */
#define MAD_INPUT_BUFFER_SIZE (5*8192)
enum {
MS_input_eof = 0x0001,
MS_input_error = 0x0001,
MS_decode_error = 0x0002,
MS_error_flags = 0x000f,
};
typedef struct {
int play_count;
SDL_RWops *src;
int freesrc;
struct mad_stream stream;
struct mad_frame frame;
struct mad_synth synth;
mad_timer_t next_frame_start;
int volume;
int status;
SDL_AudioStream *audiostream;
unsigned char input_buffer[MAD_INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
} MAD_Music;
static int MAD_Seek(void *context, double position);
static void *MAD_CreateFromRW(SDL_RWops *src, int freesrc)
{
MAD_Music *music;
music = (MAD_Music *)SDL_calloc(1, sizeof(MAD_Music));
if (!music) {
SDL_OutOfMemory();
return NULL;
}
music->src = src;
music->volume = MIX_MAX_VOLUME;
mad_stream_init(&music->stream);
mad_frame_init(&music->frame);
mad_synth_init(&music->synth);
mad_timer_reset(&music->next_frame_start);
music->freesrc = freesrc;
return music;
}
static void MAD_SetVolume(void *context, int volume)
{
MAD_Music *music = (MAD_Music *)context;
music->volume = volume;
}
/* Starts the playback. */
static int MAD_Play(void *context, int play_count)
{
MAD_Music *music = (MAD_Music *)context;
music->play_count = play_count;
return MAD_Seek(music, 0.0);
}
/* Reads the next frame from the file.
Returns true on success or false on failure.
*/
static SDL_bool read_next_frame(MAD_Music *music)
{
if (music->stream.buffer == NULL ||
music->stream.error == MAD_ERROR_BUFLEN) {
size_t read_size;
size_t remaining;
unsigned char *read_start;
/* There might be some bytes in the buffer left over from last
time. If so, move them down and read more bytes following
them. */
if (music->stream.next_frame != NULL) {
remaining = music->stream.bufend - music->stream.next_frame;
memmove(music->input_buffer, music->stream.next_frame, remaining);
read_start = music->input_buffer + remaining;
read_size = MAD_INPUT_BUFFER_SIZE - remaining;
} else {
read_size = MAD_INPUT_BUFFER_SIZE;
read_start = music->input_buffer;
remaining = 0;
}
/* Now read additional bytes from the input file. */
read_size = SDL_RWread(music->src, read_start, 1, read_size);
if (read_size == 0) {
if ((music->status & (MS_input_eof | MS_input_error)) == 0) {
/* FIXME: how to detect error? */
music->status |= MS_input_eof;
/* At the end of the file, we must stuff MAD_BUFFER_GUARD
number of 0 bytes. */
SDL_memset(read_start + read_size, 0, MAD_BUFFER_GUARD);
read_size += MAD_BUFFER_GUARD;
}
}
/* Now feed those bytes into the libmad stream. */
mad_stream_buffer(&music->stream, music->input_buffer,
read_size + remaining);
music->stream.error = MAD_ERROR_NONE;
}
/* Now ask libmad to extract a frame from the data we just put in
its buffer. */
if (mad_frame_decode(&music->frame, &music->stream)) {
if (MAD_RECOVERABLE(music->stream.error)) {
return SDL_FALSE;
} else if (music->stream.error == MAD_ERROR_BUFLEN) {
return SDL_FALSE;
} else {
Mix_SetError("mad_frame_decode() failed, corrupt stream?");
music->status |= MS_decode_error;
return SDL_FALSE;
}
}
mad_timer_add(&music->next_frame_start, music->frame.header.duration);
return SDL_TRUE;
}
/* Scale a MAD sample to 16 bits for output. */
static Sint16 scale(mad_fixed_t sample)
{
const int n_bits_to_loose = MAD_F_FRACBITS + 1 - 16;
/* round */
sample += (1L << (n_bits_to_loose - 1));
#ifdef MUSIC_MP3_MAD_GPL_DITHERING
sample += triangular_dither_noise(n_bits_to_loose + 1);
#endif
/* clip */
if (sample >= MAD_F_ONE)
sample = MAD_F_ONE - 1;
else if (sample < -MAD_F_ONE)
sample = -MAD_F_ONE;
/* quantize */
return (Sint16)(sample >> n_bits_to_loose);
}
/* Once the frame has been read, copies its samples into the output buffer. */
static SDL_bool decode_frame(MAD_Music *music)
{
struct mad_pcm *pcm;
unsigned int i, nchannels, nsamples;
mad_fixed_t const *left_ch, *right_ch;
Sint16 *buffer, *dst;
int result;
mad_synth_frame(&music->synth, &music->frame);
pcm = &music->synth.pcm;
if (!music->audiostream) {
music->audiostream = SDL_NewAudioStream(AUDIO_S16, pcm->channels, pcm->samplerate, music_spec.format, music_spec.channels, music_spec.freq);
if (!music->audiostream) {
return SDL_FALSE;
}
}
nchannels = pcm->channels;
nsamples = pcm->length;
left_ch = pcm->samples[0];
right_ch = pcm->samples[1];
buffer = SDL_stack_alloc(Sint16, nsamples*nchannels);
if (!buffer) {
SDL_OutOfMemory();
return SDL_FALSE;
}
dst = buffer;
if (nchannels == 1) {
for (i = nsamples; i--;) {
*dst++ = scale(*left_ch++);
}
} else {
for (i = nsamples; i--;) {
*dst++ = scale(*left_ch++);
*dst++ = scale(*right_ch++);
}
}
result = SDL_AudioStreamPut(music->audiostream, buffer, (nsamples * nchannels * sizeof(Sint16)));
SDL_stack_free(buffer);
if (result < 0) {
return SDL_FALSE;
}
return SDL_TRUE;
}
static int MAD_GetSome(void *context, void *data, int bytes, SDL_bool *done)
{
MAD_Music *music = (MAD_Music *)context;
int filled;
if (music->audiostream) {
filled = SDL_AudioStreamGet(music->audiostream, data, bytes);
if (filled != 0) {
return filled;
}
}
if (!music->play_count) {
/* All done */
*done = SDL_TRUE;
return 0;
}
if (read_next_frame(music)) {
if (!decode_frame(music)) {
return -1;
}
} else if (music->status & MS_input_eof) {
int play_count = -1;
if (music->play_count > 0) {
play_count = (music->play_count - 1);
}
if (MAD_Play(music, play_count) < 0) {
return -1;
}
} else if (music->status & MS_decode_error) {
return -1;
}
return 0;
}
static int MAD_GetAudio(void *context, void *data, int bytes)
{
MAD_Music *music = (MAD_Music *)context;
return music_pcm_getaudio(context, data, bytes, music->volume, MAD_GetSome);
}
static int MAD_Seek(void *context, double position)
{
MAD_Music *music = (MAD_Music *)context;
mad_timer_t target;
int int_part;
int_part = (int)position;
mad_timer_set(&target, int_part, (int)((position - int_part) * 1000000), 1000000);
if (mad_timer_compare(music->next_frame_start, target) > 0) {
/* In order to seek backwards in a VBR file, we have to rewind and
start again from the beginning. This isn't necessary if the
file happens to be CBR, of course; in that case we could seek
directly to the frame we want. But I leave that little
optimization for the future developer who discovers she really
needs it. */
mad_timer_reset(&music->next_frame_start);
music->status &= ~MS_error_flags;
SDL_RWseek(music->src, 0, RW_SEEK_SET);
}
/* Now we have to skip frames until we come to the right one.
Again, only truly necessary if the file is VBR. */
while (mad_timer_compare(music->next_frame_start, target) < 0) {
if (!read_next_frame(music)) {
if ((music->status & MS_error_flags) != 0) {
/* Couldn't read a frame; either an error condition or
end-of-file. Stop. */
return Mix_SetError("Seek position out of range");
}
}
}
/* Here we are, at the beginning of the frame that contains the
target time. Ehh, I say that's close enough. If we wanted to,
we could get more precise by decoding the frame now and counting
the appropriate number of samples out of it. */
return 0;
}
static void MAD_Delete(void *context)
{
MAD_Music *music = (MAD_Music *)context;
mad_stream_finish(&music->stream);
mad_frame_finish(&music->frame);
mad_synth_finish(&music->synth);
if (music->audiostream) {
SDL_FreeAudioStream(music->audiostream);
}
if (music->freesrc) {
SDL_RWclose(music->src);
}
SDL_free(music);
}
Mix_MusicInterface Mix_MusicInterface_MAD =
{
"MAD",
MIX_MUSIC_MAD,
MUS_MP3,
SDL_FALSE,
SDL_FALSE,
NULL, /* Load */
NULL, /* Open */
MAD_CreateFromRW,
NULL, /* CreateFromFile */
MAD_SetVolume,
MAD_Play,
NULL, /* IsPlaying */
MAD_GetAudio,
MAD_Seek,
NULL, /* Pause */
NULL, /* Resume */
NULL, /* Stop */
MAD_Delete,
NULL, /* Close */
NULL, /* Unload */
};
#endif /* MUSIC_MP3_MAD */
/* vi: set ts=4 sw=4 expandtab: */
|
the_stack_data/148577992.c
|
/******************************************************************************
* Copyright (C) 2019 - 2020 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
/******************************************************************************/
/***************************** Include Files *********************************/
#include <stdio.h>
/************************** Function Definitions *****************************/
/*****************************************************************************/
/*
*
* This API skips N number of lines for a file
*
* @param fp: File pointer of the file
* @param numlines: number of lines to skip
*
* @return None.
*
* @note Internal API only.
*
******************************************************************************/
void skip_lines(FILE *fp, int numlines)
{
int cnt;
char ch;
cnt = 0;
while((cnt < numlines) && ((ch = getc(fp)) != EOF))
{
if (ch == '\n')
cnt++;
}
}
|
the_stack_data/141707.c
|
int X;
void deleteThenBranch(int a) {
if (0) {
printf("Then");
} else {
printf("Else");
}
X = 1;
}
void deleteElseBranch(int a) {
if (1) {
printf("Then");
} else {
printf("Else");
}
X = 1;
}
void NoOptimize(int a) {
if (X) {
} else {
}
}
void main() {
}
|
the_stack_data/190766919.c
|
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<netinet/ip_icmp.h>
#include<netinet/udp.h>
#include<netinet/tcp.h>
#include<netinet/ip.h>
#include<netinet/igmp.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<net/ethernet.h>
#include<linux/if_packet.h>
#include<linux/if_ether.h>
#include<netdb.h>
#define PATH "logfile.txt"
#define MAX_PACKET_SIZE 65536
void perror2(char *str);
void handle_ipv4(char *buff);
void print_tcp(char *buff);
void print_udp(char *buff);
void print_icmp(char *buff);
void print_igmp(char *buff);
int raw_sockfd;
FILE *logfile;
int tcp,udp,igmp,icmp,others;
struct sockaddr_in src,dst;
int main(int argc, char *argv[]){
int len,bytes_read;
struct sockaddr addr;
struct in_addr inaddr;
char buff[MAX_PACKET_SIZE];
tcp=0;
udp=0;
igmp=0;
icmp=0;
others=0;
logfile = fopen(PATH,"w");
if(logfile == NULL)
perror2("logfile open");
raw_sockfd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if(raw_sockfd < 0)
perror2("socket()");
len = sizeof(addr);
while(1){
bytes_read = recvfrom(raw_sockfd,buff, MAX_PACKET_SIZE, 0, &addr,(socklen_t *)&len);
if(bytes_read<0)
perror2("recvfrom()");
struct ethhdr *eth = (struct ethhdr *) buff;
printf("\n\nETHERNET HEADER:\n");
printf("\t|-Source Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n",eth->h_source[0],eth->h_source[1],eth->h_source[2],eth->h_source[3],eth->h_source[4],eth->h_source[5]);
printf("\t|-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X\n",eth->h_dest[0],eth->h_dest[1],eth->h_dest[2],eth->h_dest[3],eth->h_dest[4],eth->h_dest[5]);
printf("\t|-Protocol : 0x%X\t",ntohs(eth->h_proto));
switch (ntohs(eth->h_proto)){
case 2048: printf("\tIPv4 Protocol\n");
handle_ipv4(buff);
break;
//case 34525: handle_ipv6(buff);
//case 2054: handle_arp(buff);
default: printf("\tUnknown Protocol\n");
}
}
}
void perror2(char *str){
perror(str);
exit(0);
}
void handle_ipv4(char *buff){
int iphdrlen;
struct sockaddr_in source, dest;
struct protoent *prt = (struct protoent *) malloc(sizeof(struct protoent));
struct iphdr *myiphdr = (struct iphdr *) (buff + sizeof(struct ethhdr));
iphdrlen = myiphdr->ihl << 2;
memset(&source, 0, sizeof(source));
source.sin_addr.s_addr = myiphdr->saddr;
memset(&dest, 0, sizeof(dest));
dest.sin_addr.s_addr = myiphdr->daddr;
prt = getprotobynumber((int)myiphdr->protocol);
printf("\n\tIPv4 HEADER:\n\n");
printf("\t|-Version : %d\n",(unsigned int)myiphdr->version);
printf("\t|-Internet Header Length : %d DWORDS or %d Bytes\n",(unsigned int)myiphdr->ihl,((unsigned int)(myiphdr->ihl))*4);
printf("\t|-Type Of Service : %d\n",(unsigned int)myiphdr->tos);
printf("\t|-Total Length : %d Bytes\n",ntohs(myiphdr->tot_len));
printf("\t|-Identification : %d\n",ntohs(myiphdr->id));
printf("\t|-Time To Live : %d\n",(unsigned int)myiphdr->ttl);
printf("\t|-Protocol : %d Protocol name : %s\n",(unsigned int)myiphdr->protocol,prt->p_name);
printf("\t|-Header Checksum : %d\n",ntohs(myiphdr->check));
printf("\t|-Source IP : %s\n", inet_ntoa(source.sin_addr));
printf("\t|-Destination IP : %s\n",inet_ntoa(dest.sin_addr));
switch (myiphdr->protocol){
case 6: print_tcp(buff + sizeof(struct ethhdr) + iphdrlen);
tcp++;
break;
case 17: print_udp(buff + sizeof(struct ethhdr) + iphdrlen);
udp++;
break;
case 1: print_icmp(buff + sizeof(struct ethhdr) + iphdrlen);
icmp++;
break;
case 2: print_igmp(buff + sizeof(struct ethhdr) + iphdrlen);
igmp++;
break;
default: break;
}
return;
}
void print_tcp(char *buff){
struct tcphdr *tcph = (struct tcphdr *) malloc(sizeof(struct tcphdr));
tcph = (struct tcphdr *) buff;
printf("\n\tTCP Header: \n\n");
printf("\t\t |-Source Port : %u\n",ntohs(tcph->source));
printf("\t\t |-Destination Port : %u\n",ntohs(tcph->dest));
printf("\t\t |-Sequence Number : %u\n",ntohl(tcph->seq));
printf("\t\t |-Acknowledge Number : %u\n",ntohl(tcph->ack_seq));
printf("\t\t |-Header Length : %d DWORDS or %d BYTES\n" ,(unsigned int)tcph->doff,(unsigned int)tcph->doff*4);
printf("\t\t |-Urgent Flag : %d\n",(unsigned int)tcph->urg);
printf("\t\t |-Acknowledgement Flag : %d\n",(unsigned int)tcph->ack);
printf("\t\t |-Push Flag : %d\n",(unsigned int)tcph->psh);
printf("\t\t |-Reset Flag : %d\n",(unsigned int)tcph->rst);
printf("\t\t |-Synchronise Flag : %d\n",(unsigned int)tcph->syn);
printf("\t\t |-Finish Flag : %d\n",(unsigned int)tcph->fin);
printf("\t\t |-Window : %d\n",ntohs(tcph->window));
printf("\t\t |-Checksum : %d\n",ntohs(tcph->check));
printf("\t\t |-Urgent Pointer : %d\n",tcph->urg_ptr);
printf("\n");
//printf("\t\t DATA Dump \n");
return;
}
void print_udp(char *buff){
struct udphdr *udph = (struct udphdr *) malloc(sizeof(struct udphdr));
udph = (struct udphdr *) buff;
printf("\n\tUDP HEADER: \n\n");
printf("\t\t |-Source Port : %d\n" , ntohs(udph->source));
printf("\t\t |-Destination Port : %d\n" , ntohs(udph->dest));
printf("\t\t |-UDP Length : %d\n" , ntohs(udph->len));
printf("\t\t |-UDP Checksum : %d\n" , ntohs(udph->check));
printf("\n");
return;
}
void print_icmp(char *buff){
struct icmp *icmp = (struct icmp *) buff;
printf("\n\tICMP HEADER: \n\n");
printf("\t\tICMP Seq No. : %u \t\tICMP Type : %d \t\tICMP Code : %d \t\tICMP ID : %d\n\n",icmp->icmp_seq, icmp->icmp_type, icmp->icmp_code, icmp->icmp_id);
return;
}
void print_igmp(char *buff){
struct igmp *igmph = (struct igmp *) malloc(sizeof(struct igmp));
igmph = (struct igmp *) buff;
printf("\n\tIGMP HEADER: \n\n");
printf("\t\tIGMP Type : %d \t\tIGMP Code : %d \t\tIGMP Checksum : %u\n\n",igmph->igmp_type, igmph->igmp_code, igmph->igmp_cksum);
return;
}
|
the_stack_data/80328.c
|
#include <stdio.h>
#define MAX 1024
#define BASE10 10
#define BASE2 2
#define NBIT 10
/*
Scrivere un programma che chiede all'utente un numero intero
positivo minore di 1024 e se il valore non è valido stampa un
messaggio di errore e lo richiede. Il programma converte in binario
naturale su 10 bit il valore acquisito mediante il metodo dei resti
e visualizza il risultato.
*/
int main() {
int n10, i;
int n2[NBIT];
scanf("%d", &n10);
while (n10 <= 0 || n10 >= MAX) {
printf("Valore non valido.\n");
scanf("%d", &n10);
}
for (i = 0; i < NBIT; i++)
n2[i] = 0;
for (i = NBIT - 1; n10 > 0 && i >= 0; n10 /= BASE2, i--) {
n2[i] = n10 % BASE2;
}
for (i = 0; i < NBIT; i++)
printf("%d", n2[i]);
printf("\n");
return 0;
}
|
the_stack_data/187643787.c
|
#include <stdio.h>
#include <stdlib.h>
typedef struct _plate_t {
int length;
int width;
} plate_t;
int N; // 1 <= N <= 5000
int Li[5000];
int Wi[5000];
int Answer;
int compare(plate_t *p1, plate_t *p2) {
if(p1->length != p2->length) {
return (p1->length > p2->length ? 1 : -1);
}else if(p1->width == p2->width){
return 0;
}else {
return (p1->width > p2->width ? 1 : -1);
}
}
void insertion_sort_asc(int size, plate_t **plates) {
int i, j;
for(i = 1; i < size; i++) {
plate_t *tmp = plates[i];
for(j = (i - 1); j >= 0; j--) {
if(compare(tmp, plates[j]) < 0) {
plates[j + 1] = plates[j];
}else {
break;
}
}
plates[j + 1] = tmp;
}
}
int getAnswer(int N, plate_t **plates) {
int answer = 0;
insertion_sort_asc(N, plates);
int remain = N;
while(remain > 0) {
int i, j, current;
for(i = 0; i < N; i++) {
if(plates[i] == NULL) {
continue;
}
current = plates[i]->width;
free(plates[i]);
plates[i] = NULL;
remain--;
for(j = (i + 1); j < N; j++) {
if(plates[j] != NULL && plates[j]->width >= current) {
current = plates[j]->width;
free(plates[j]);
plates[j] = NULL;
remain--;
}
}
answer++;
}
}
return answer;
}
int main(void)
{
int test_case;
int T;
/*
The freopen function below opens input.txt file in read only mode, and afterward,
the program will read from input.txt file instead of standard(keyboard) input.
To test your program, you may save input data in input.txt file,
and use freopen function to read from the file when using scanf function.
You may remove the comment symbols(//) in the below statement and use it.
But before submission, you must remove the freopen function or rewrite comment symbols(//).
*/
// freopen("input.txt", "r", stdin);
/*
If you remove the statement below, your program's output may not be rocorded
when your program is terminated after the time limit.
For safety, please use setbuf(stdout, NULL); statement.
*/
setbuf(stdout, NULL);
scanf("%d", &T);
for(test_case = 0; test_case < T; test_case++)
{
int i;
scanf("%d", &N);
plate_t ** plates = (plate_t **)malloc(N * (sizeof(plate_t *)));
for(i=0; i < N; i++)
{
scanf("%d %d", &Li[i], &Wi[i]);
plate_t *plate = (plate_t *)malloc(sizeof(plate_t));
plate->length = Li[i];
plate->width = Wi[i];
plates[i] = plate;
}
/**********************************
* Implement your algorithm here. *
***********************************/
Answer = getAnswer(N, plates);
// Print the answer to standard output(screen).
printf("%d\n", Answer);
}
return 0;//Your program should return 0 on normal termination.
}
|
the_stack_data/126703645.c
|
//PLL3MUL10
//I2S_DIV = 11
//I2S_ODD = 1
//Fs = 44157
|
the_stack_data/154830532.c
|
#include "stdlib.h"
#include "stdio.h"
#include "malloc.h"
#include <stdbool.h>
#include "assert.h"
// Counts the number of words in the given file.
/*@
fixpoint int wcount(list<char> cs, bool inword) {
switch(cs) {
case nil: return inword ? 1 : 0;
case cons(h, t): return 0 == h ? (inword ? 1 : 0) : (' ' == h ? ((inword ? 1 : 0) + wcount(t, false)) : wcount(t, true));
}
}
@*/
int wc(char* string, bool inword)
//@ requires [?f]string(string, ?cs);
//@ ensures [f]string(string, cs) &*& result == wcount(cs, inword);
{
//@ open [f]string(string, cs);
char head = * string;
if(head == 0) {
//@ close [f]string(string, cs);
return inword ? 1 : 0;
} else {
if(head == ' ') {
int result = wc(string + 1, false);
//@ close [f]string(string, cs);
return inword ? 1 + result: result;
} else {
int result = wc(string + 1, true);
//@ close [f]string(string, cs);
return result;
}
}
}
void test()
//@ requires true;
//@ ensures true;
{
int nb = wc("This line of text contains 8 words.", false);
assert(nb == 7);
}
int main(int argc, char** argv) //@ : main
//@ requires 0 <= argc &*& [_]argv(argv, argc, _);
//@ ensures true;
{
bool inword = false; struct file* fp = 0; char* buff = 0; int total = 0; char* res = 0;
if(argc < 2) { puts("No input file specified."); return -1; }
//@ open [_]argv(argv, argc, _);
//@ open [_]argv(argv + 1, argc - 1, _);
fp = fopen(* (argv + 1), "r");
buff = malloc(100);
if(buff == 0 || fp == 0) { abort(); }
res = fgets(buff, 100, fp);
while(res != 0)
//@ invariant file(fp) &*& chars(buff, 100, ?cs) &*& res != 0 ? mem('\0', cs) == true : true;
{
//@ chars_separate_string(buff);
int tmp = wc(buff, inword);
//@ chars_unseparate_string(buff);
total = total + tmp;
res = fgets(buff, 100, fp);
}
printf("%i", total);
free(buff);
fclose(fp);
return 0;
}
|
the_stack_data/115766480.c
|
#include <stdio.h>
int main() {
// Ler 2 valores, calcular e escrever a soma dos inteiros existentes entre os 2 valores lidos (incluindo os valores lidos na soma). considere que o segundo valor lido poderá ser maior ou menor que o primeiro valor lido, ou seja, deve-se testá-los.
int num1 = 0;
int num2 = 0;
int contador = 0;
int total = 0;
printf("Informe o primeiro número: \n");
scanf("%d", &num1);
printf("Informe o segundo número: \n");
scanf("%d", &num2);
if(num1 < num2) {
contador = num1;
total = num1;
while (contador < num2) {
contador++;
num1 = num1 + 1;
if (num1 < num2) {
total = total + num1;
}
}
total = total + num2;
printf("A soma dos números inteiros do menor para o maior é de %d.\n", total);
} else {
contador = num2;
total = num2;
while (contador < num1) {
contador++;
num2 = num2 + 1;
if (num2 < num1) {
total = total + num2;
}
}
total = total + num1;
printf("A soma dos números inteiros do menor para o maior é de %d.\n", total);
}
//Resultado
//Programa funcionou corretamente exibindo a soma dos valores inteiros do menor número inserido para o maior.
}
|
the_stack_data/93887666.c
|
/*
* POK header
*
* The following file is a part of the POK project. Any modification should
* made according to the POK licence. You CANNOT use this file or a part of
* this file is this part of a file for your own project
*
* For more information on the POK licence, please see our LICENCE FILE
*
* Please follow the coding guidelines described in doc/CODING_GUIDELINES
*
* Copyright (c) 2007-2009 POK team
*
* Created by julien on Fri Jan 30 14:41:34 2009
*/
/* @(#)w_log10.c 5.1 93/09/24 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#ifdef POK_NEEDS_LIBMATH
/*
* wrapper log2(X)
*/
#include <libm.h>
#include "math_private.h"
double
log2(double x) /* wrapper log10 */
{
#ifdef _IEEE_LIBM
return __ieee754_log2(x);
#else
double z;
z = __ieee754_log2(x);
if(_LIB_VERSION == _IEEE_ || isnan(x)) return z;
if(x<=0.0) {
if(x==0.0)
return __kernel_standard(x,x,48); /* log2(0) */
else
return __kernel_standard(x,x,49); /* log2(x<0) */
} else
return z;
#endif
}
#endif
|
the_stack_data/47128.c
|
/*EXERCICIO 3
Leia uma matriz 5 x 5 e também um valor inteiro para uma
variável simples. O programa deverá fazer uma busca por esse valor na matriz e, ao
final, escrever a localização (linha e coluna) caso encontre o valor ou uma
mensagem de “não encontrado”.*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int matriz[5][5], valor, i, j, n = 0;
srand(time(NULL));
printf("Gerando uma matriz 5x5...\n");
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
matriz[i][j] = rand()%100;
}
}
printf("Insira um valor inteiro para buscar na matriz \n");
scanf("%d", &valor);
printf("Buscando o valor na matriz...\n");
for(i = 0; i < 5; i++){
for(j = 0; j < 5; j++){
if(matriz[i][j] == valor){
printf("A localização é linha %d e coluna %d \n", i, j);
n = n + 1;
}
}
}
if (n == 0){
printf("Não foi encontrado o número \n");
}
return 0;
}
|
the_stack_data/148578984.c
|
extern void exit (int);
int
f()
{
int j = 1;
long i;
for (i = -0x70000000L; i < 0x60000000L; i += 0x10000000L) j <<= 1;
return j;
}
int
main ()
{
if (f () != 8192)
abort ();
exit (0);
}
|
the_stack_data/1240365.c
|
/* Taxonomy Classification: 0000000000000022000300 */
/*
* WRITE/READ 0 write
* WHICH BOUND 0 upper
* DATA TYPE 0 char
* MEMORY LOCATION 0 stack
* SCOPE 0 same
* CONTAINER 0 no
* POINTER 0 no
* INDEX COMPLEXITY 0 constant
* ADDRESS COMPLEXITY 0 constant
* LENGTH COMPLEXITY 0 N/A
* ADDRESS ALIAS 0 none
* INDEX ALIAS 0 none
* LOCAL CONTROL FLOW 0 none
* SECONDARY CONTROL FLOW 0 none
* LOOP STRUCTURE 2 do-while
* LOOP COMPLEXITY 2 one
* ASYNCHRONY 0 no
* TAINT 0 no
* RUNTIME ENV. DEPENDENCE 0 no
* MAGNITUDE 3 4096 bytes
* CONTINUOUS/DISCRETE 0 discrete
* SIGNEDNESS 0 no
*/
/*
Copyright 2005 Massachusetts Institute of Technology
All rights reserved.
Redistribution and use of software 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 set of conditions and the disclaimer below.
- Redistributions in binary form must reproduce the copyright notice, this
set of conditions, and the disclaimer below in the documentation and/or
other materials provided with the distribution.
- Neither the name of the Massachusetts Institute of Technology 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".
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*/
int main(int argc, char *argv[])
{
int test_value;
int loop_counter;
char buf[10];
test_value = 4105;
loop_counter = 0;
do
{
/* BAD */
buf[4105] = 'A';
loop_counter++;
}
while(loop_counter <= test_value);
return 0;
}
|
the_stack_data/76700558.c
|
/***************************************
* EECS2031AC 21F – Lab1 *
* Author: Rahman, Mahfuz *
* Email: [email protected] *
* eecs_username: mafu *
* York Student #: 217847518
****************************************/
#include <stdio.h> // define EOF
main(){
int c;
int count = 0;
c = getchar();
while(c != EOF) /* no end of file*/
{
if (c != '\n'){
count++;
}
c = getchar(); /* read next */
}
printf("# of chars: %d\n",count);
}
|
the_stack_data/1109142.c
|
/*****************************************
Emitting C Generated Code
*******************************************/
#include <unistd.h>
#include <errno.h>
#include <err.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <sys/mman.h>
#include <stdbool.h>
/************* Functions **************/
#ifndef MAP_FILE
#define MAP_FILE MAP_SHARED
#endif
int fsize(int fd) {
struct stat stat;
int res = fstat(fd,&stat);
return stat.st_size;
}
int printll(char* s) {
while (*s != '\n' && *s != ',' && *s != '\t') {
putchar(*s++);
}
return 0;
}
long hash(char *str0, int len) {
unsigned char* str = (unsigned char*)str0;
unsigned long hash = 5381;
int c;
while ((c = *str++) && len--)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
/**************** Snippet ****************/
void Snippet(char* x0) {
printf("%s\n", "Name");
int x1 = open("src/data/t.csv",0);
int x2 = fsize(x1);
char* x3 = malloc(x2);
read(x1, x3, x2);
int x4 = 0;
while (x3[x4] != ',') x4 = x4 + 1;
x4 = x4 + 1;
while (x3[x4] != ',') x4 = x4 + 1;
x4 = x4 + 1;
while (x3[x4] != '\n') x4 = x4 + 1;
x4 = x4 + 1;
while (x4 < x2) {
int x5 = x4;
while (x3[x4] != ',') x4 = x4 + 1;
x4 = x4 + 1;
char* x6 = x3 + x5;
while (x3[x4] != ',') x4 = x4 + 1;
int x7 = x4 + 1;
x4 = x7;
while (x3[x4] != '\n') x4 = x4 + 1;
int x8 = x4 - x7;
x4 = x4 + 1;
if (x8 == 3 && ({
char* x9 = x3 + x7;
int x10 = 0;
while (x10 < x8 && x9[x10] == "yes"[x10]) x10 = x10 + 1;
x10 == x8;
})) {
printll(x6);
printf("%s\n", "");
}
}
close(x1);
}
/*****************************************
End of C Generated Code
*******************************************/
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("usage: %s <arg>\n", argv[0]);
return 0;
}
Snippet(argv[1]);
return 0;
}
|
the_stack_data/439442.c
|
/*************************************************************************
* Program ascii_to_latex_to_ascii
* To convert an ASCII list to a LaTeX table
*
*
* JLP
* Version 15/02/2008
*************************************************************************/
#include <stdio.h>
#include <math.h>
#include <string.h>
/* Maximum length for one line will be 170 characters: */
#define NMAX 170
#define DEBUG
/*
*/
static int jlp_ascii_to_latex(FILE *fp_in, FILE *fp_out, int *iy, int nn);
int read_int_array_from_string(char *buffer, int len, int *out, int nmax, int *nn);
int main(int argc, char *argv[])
{
char filein[60], fileout[60], buffer[80];
int iy[20], nmax = 20, nn = 0;
register int i;
FILE *fp_in, *fp_out;
printf("ascii_to_latex/ JLP/ Version 15/02/2008\n");
if(argc == 7 && *argv[4]) argc = 5;
if(argc == 7 && *argv[3]) argc = 4;
if(argc == 7 && *argv[2]) argc = 3;
if(argc == 7 && *argv[1]) argc = 2;
if(argc != 4)
{
printf("Error: argc=%d\n\n", argc);
printf("Syntax: ascii_to_latex in_ascii_list out_latex_table iy1,iy2,iy3,iy4,iy5,...,iyn\n");
printf("\n(iy1,iy2, etc are the location of the separators (blanks) max=%d)\n", nmax);
return(-1);
}
strcpy(filein,argv[1]);
strcpy(fileout,argv[2]);
strcpy(buffer,argv[3]);
read_int_array_from_string(buffer, 80, iy, nmax, &nn);
printf(" OK: filein=%s fileout=%s nn=%d\n", filein, fileout, nn);
for(i = 0; i < nn; i++) printf(" iy[%d]=%d", i, iy[i]);
printf("\n");
if((fp_in = fopen(filein,"r")) == NULL)
{
printf(" Fatal error opening input file %s \n",filein);
return(-1);
}
if((fp_out = fopen(fileout,"w")) == NULL)
{
printf(" Fatal error opening output file %s \n",fileout);
fclose(fp_in);
return(-1);
}
/* Scan the file and make the conversion: */
jlp_ascii_to_latex(fp_in,fp_out, iy, nn);
fclose(fp_in);
fclose(fp_out);
return(0);
}
/*********************************************************************************
* read_int_array_from_string
*
* INPUT:
* buffer: string to be read
* len: length of buffer
* nmax: maximum number of values to be read
*
* OUTPUT:
* nn: number of values read
* out[nn]: integer array
*********************************************************************************/
int read_int_array_from_string(char *buffer, int len, int *out, int nmax, int *nn)
{
register int i;
int ival, nval;
char *pc;
for(i = 0; i < nmax; i++) out[i] = 0;
*nn = 0;
pc = buffer;
for(i = 0; i < len; i++){
if(buffer[i] == '\0' || buffer[i] == ',') {
nval = sscanf(pc,"%d", &ival);
if(nval == 1) {
out[*nn] = ival;
(*nn)++;
if(*nn >= nmax) {
if(buffer[i] !='\0')
fprintf(stderr,"Error: max number of values =%d)\n", nmax);
break;
}
}
if(buffer[i] == '\0') break;
/* Next step: */
i++;
pc = &buffer[i];
}
} /* EOF for i=0, i< len */
return(0);
}
/*************************************************************************
*
* INPUT:
* iy[nn]: array with the location indices of the separations (blanks)
* nn : number of separation indices
*************************************************************************/
static int jlp_ascii_to_latex(FILE *fp_in, FILE *fp_out, int *iy, int nn)
{
char b_in[NMAX], b_out[NMAX+100];
register int i, j, k, l;
while(!feof(fp_in))
{
/* Maximum length for a line will be 170 characters: */
if(fgets(b_in,NMAX,fp_in))
{
k = 0;
j = 0;
for(i = 0; i < NMAX; i++){
if(b_in[i] == '\n' || b_in[i] == '\0' || b_in[i] == '\r') break;
if(i == iy[k]) {
b_out[j++] = '&';
b_out[j++] = ' ';
b_out[j++] = b_in[i];
k++;
if(k == nn) break;
} else {
b_out[j++] = b_in[i];
}
}
/* Completes the line with the required number of separators if needed */
b_out[j++] = ' ';
for(l = k+1; l < nn; l++){
b_out[j++] = '&';
b_out[j++] = ' ';
}
b_out[j++] = '\\';
b_out[j++] = '\\';
b_out[j++] = '\0';
printf("in=>%s<\n", b_in);
printf("out=>%s<\n", b_out);
fprintf(fp_out,"%s\n", b_out);
}
} /* EOF while !feof(fp_in) */
return(0);
}
|
the_stack_data/215768693.c
|
extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern void __VERIFIER_assume(int);
void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } }
extern int __VERIFIER_nondet_int(void);
int N;
int main()
{
N = __VERIFIER_nondet_int();
if(N <= 0) return 1;
int i;
int sum[1];
int a[N];
for(i=0; i<N; i++)
{
a[i] = i%4;
}
for(i=0; i<N; i++)
{
if(i==0) {
sum[0] = 0;
} else {
sum[0] = sum[0] + a[i];
}
}
__VERIFIER_assert(sum[0] <= 3*N);
return 1;
}
|
the_stack_data/845509.c
|
/* ヘッダファイルのインクルード */
#include <stdio.h> /* 標準入出力 */
#include <time.h> /* UNIX時間 */
/* main関数の定義 */
int main(void){
/* 変数の宣言 */
clock_t start; /* 開始時刻start(プロセッサ時間単位) */
clock_t end; /* 終了時刻end(プロセッサ時間単位) */
double elapsed; /* 経過時間elapsed(秒単位) */
long i; /* ループ用変数i */
/* 開始時刻start */
start = clock(); /* clockで開始時刻(プロセッサ時間単位)を取得し, startに格納. */
/* iが1000000になるまでループする. */
for (i = 0; i != 1000000; i++){ /* iを0から足し続けて, 1000000になるまでループ. */
/* iを出力 */
printf("i = %ld\n", i); /* printfでiを出力. */
}
/* iが1000000の時. */
printf("i = %ld\n", i); /* printfでi( = 1000000)を出力. */
/* 終了時刻end */
end = clock(); /* clockで終了時刻(プロセッサ時間単位)を取得し, endに格納. */
/* 経過時間の計算 */
elapsed = (double)(end - start) / (double)CLOCKS_PER_SEC; /* endからstartを引いてCLOCKS_PER_SECで割ると秒単位の経過時間が算出できるので, それをelapsedに格納. */
/* 経過時間の出力 */
printf("elapsed = %lf\n", elapsed); /* printfで経過時間elapsedを出力. */
/* プログラムの終了 */
return 0;
}
|
the_stack_data/58064.c
|
//Remove duplicate nodes from an unsorted linked list
/*
First sort the list using merge sort
Then, remove duplicate nodes from the sorted list
*/
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* newNode(int x){
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->next=NULL;
return temp;
}
void insert(struct node** head1,int x){
struct node*last=*head1;
if(last==NULL){
last->data=x;
last->next=NULL;
}
while(last->next!=NULL){
last=last->next;
}
last->next=newNode(x);
}
void printList(struct node* head){
while(head!=NULL){
printf("%d\t",head->data);
head=head->next;
}
}
struct node* merge(struct node*a, struct node*b){
struct node* temp=NULL;
if(a==NULL){
return b;
}
if(b==NULL){
return a;
}
if(a->data<=b->data){
temp=a;
temp->next=merge(a->next,b);
}else{
temp=b;
temp->next=merge(a,b->next);
}
return temp;
}
void frontBackPartition(struct node* root, struct node** front, struct node ** back){
struct node* a=root;
struct node* b=root->next;
//a advances one node
//b advances two nodes
while(b!=NULL){
b=b->next;
if(b!=NULL){
a=a->next;
b=b->next;
}
}
*front=root;
*back=a->next;
a->next=NULL;
}
void sortList(struct node** head){
//Create front and back
//similar to left right arrays in merge sort
struct node* front=NULL;
struct node* back=NULL;
struct node* root=*head;
if(root==NULL){
return;
}
//Sinlge node->No need to sort
if(root->next==NULL){
return;
}
frontBackPartition(root,&front,&back);
sortList(&front);
sortList(&back);
//Merge the sorted front and back list and assign to head
*head=merge(front,back);
}
void removeDup(struct node*head){
struct node* cur=head;
struct node* temp=NULL;
if(cur==NULL){
return;
}
while(cur->next!=NULL){
if(cur->data==cur->next->data){
temp=cur->next->next;
free(cur->next);
cur->next=temp;
}else{
cur=cur->next;
}
}
}
int main(){
struct node* head = newNode(5);
insert(&head,1);
insert(&head,5);
insert(&head,2);
insert(&head,4);
printf("Input Linked List :\n");
printList(head);
sortList(&head);
printf("\nResultant list after removing duplicates in an array:\n");
removeDup(head);
printList(head);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.